<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" min-label-width="68px">
      <el-form-item :label="t('EquipmentManagement.DvRepair.repairCode')" prop="repairCode">
        <el-input
          v-model="queryParams.repairCode"
          :placeholder="t('EquipmentManagement.DvRepair.placeholderRepairCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.DvRepair.repairName')" prop="repairName">
        <el-input
          v-model="queryParams.repairName"
          :placeholder="t('EquipmentManagement.DvRepair.placeholderRepairName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item :label="t('EquipmentManagement.DvRepair.machineryName')" prop="machineryName">
        <el-input
          v-model="queryParams.machineryName"
          :placeholder="t('EquipmentManagement.DvRepair.placeholderMachineryName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item :label="t('EquipmentManagement.DvRepair.requireDate')" prop="requireDate">
        <el-date-picker
          v-model="queryParams.requireDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('common.startTime')"
          :end-placeholder="t('common.endTime')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.DvRepair.finishDate')" prop="finishDate">
        <el-date-picker
          v-model="queryParams.finishDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('common.startTime')"
          :end-placeholder="t('common.endTime')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.DvRepair.confirmDate')" prop="confirmDate">
        <el-date-picker
          v-model="queryParams.confirmDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('common.startTime')"
          :end-placeholder="t('common.endTime')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.DvRepair.acceptedBy')" prop="acceptedBy">
        <el-input
          v-model="queryParams.acceptedBy"
          :placeholder="t('EquipmentManagement.DvRepair.placeholderAcceptedBy')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item :label="t('EquipmentManagement.DvRepair.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('EquipmentManagement.DvRepair.placeholderStatus')"
          clearable
          class="!w-240px"
        >
          <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.query') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mes:dv-repair:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" v-hasPermi="['mes:dv-repair:delete']">
          <Icon icon="ep:delete" class="mr-5px" />
          {{ t('EquipmentManagement.DvRepair.batchDelete') }}
        </el-button>
        <el-button
          type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mes:dv-repair:export']">
          <Icon icon="ep:download" class="mr-5px" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" reserve-selection />
      <el-table-column :label="t('EquipmentManagement.DvRepair.repairCode')" align="center" prop="repairCode" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.repairName')" align="center" prop="repairName" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.machineryName')" align="center" prop="machineryName" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.machineryCode')" align="center" prop="machineryCode" />
      <!-- <el-table-column label="品牌" align="center" prop="machineryBrand" /> -->
      <el-table-column :label="t('EquipmentManagement.DvRepair.machinerySpec')" align="center" prop="machinerySpec" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.machineryType')" align="center" prop="machineryTypeId" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_MACHINE_TYPE" :value="scope.row.machineryTypeId" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('EquipmentManagement.DvRepair.requireDate')"
        align="center"
        prop="requireDate"
        :formatter="dateFormatter2"
        width="110px" />
      <el-table-column
        :label="t('EquipmentManagement.DvRepair.finishDate')"
        align="center"
        prop="finishDate"
        :formatter="dateFormatter2"
        width="110px" />
      <el-table-column
        :label="t('EquipmentManagement.DvRepair.confirmDate')"
        align="center"
        prop="confirmDate"
        :formatter="dateFormatter2"
        width="110px" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.repairResult')" align="center" prop="repairResult" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.acceptedBy')" align="center" prop="acceptedBy" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.confirmBy')" align="center" prop="confirmBy" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.status')" align="center" prop="status" width="110px">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" effect="light">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.DvRepair.repairStatus')" align="center" prop="repairStatus" min-width="120">
        <template #default="scope">
          <el-tag :type="getResultTagType(scope.row.repairStatus)" effect="light">
            {{ getResultLabel(scope.row.repairStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column
        :label="t('EquipmentManagement.DvRepair.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="170px"
        fixed="right" />
      <el-table-column :label="t('EquipmentManagement.DvRepair.operate')" align="center" fixed="right" width="200px">
        <template #default="scope">
          <el-button
            link type="primary" @click="openForm('repair', scope.row.id)"
            v-if="String(scope.row.status) !== '1'" v-hasPermi="['mes:dv-repair:update']">
            {{ t('EquipmentManagement.DvRepair.repair') }}
          </el-button>
          <el-button
            link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:dv-repair:update']">
            {{ t('action.update') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:dv-repair:delete']">
            {{ t('action.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DvRepairForm v-if="formVisible" ref="formRef" @success="getList" @closed="formVisible = false" />
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { DvRepairApi, DvRepairVO } from '@/api/mes/dvrepair'
import DvRepairForm from './DvRepairForm.vue'

/** 设备维修记录 列表 */
defineOptions({ name: 'DvRepair' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DvRepairVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  repairCode: undefined,
  repairName: undefined,
  machineryId: undefined,
  machineryCode: undefined,
  machineryName: undefined,
  machineryBrand: undefined,
  machinerySpec: undefined,
  machineryTypeId: undefined,
  requireDate: [],
  finishDate: [],
  confirmDate: [],
  repairResult: undefined,
  acceptedBy: undefined,
  confirmBy: undefined,
  status: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const statusOptions = [
  { label: t('EquipmentManagement.DvRepair.statusPending'), value: '0' },
  { label: t('EquipmentManagement.DvRepair.statusFinished'), value: '1' }
]

const getStatusLabel = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (v === '0') return t('EquipmentManagement.DvRepair.statusPending')
  if (v === '1') return t('EquipmentManagement.DvRepair.statusFinished')
  return '-'
}

const getStatusTagType = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (v === '1') return 'success'
  if (v === '0') return 'warning'
  return 'info'
}

const getResultLabel = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (v == '0') return t('EquipmentManagement.DvRepair.repairResultPending')
  if (v == '1') return t('EquipmentManagement.DvRepair.repairResultOk')
  if (v == '2') return t('EquipmentManagement.DvRepair.repairResultNg')
  return '-'
}

const getResultTagType = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (v == '1') return 'success'
  if (v == '2') return 'danger'
  if (v == '0') return 'info'
  return 'info'
}

const tableRef = ref()
const selectedIds = ref<number[]>([])
const handleSelectionChange = (rows: any[]) => {
  selectedIds.value = rows?.map((row) => row.id).filter((id) => id !== undefined) ?? []
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DvRepairApi.getDvRepairPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const formVisible = ref(false)

const openForm = async (type: string, id?: number) => {
  formVisible.value = true
  await nextTick()
  formRef.value?.open(type, id)
}

/** 删除按钮操作 */
const buildIdsParam = (ids: number | number[]) => {
  return Array.isArray(ids) ? ids.join(',') : String(ids)
}

const handleDelete = async (ids: number | number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    const idsParam = buildIdsParam(ids)
    await DvRepairApi.deleteDvRepair(idsParam)
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    tableRef.value?.clearSelection?.()
    // 刷新列表
    await getList()
  } catch { }
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    message.error(t('EquipmentManagement.DvRepair.selectDeleteTip'))
    return
  }
  await handleDelete(selectedIds.value)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DvRepairApi.exportDvRepair(
      selectedIds.value.length
        ? {
            ids: selectedIds.value.join(',')
          }
        : queryParams
    )
    download.excel(data, t('EquipmentManagement.DvRepair.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
