<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" min-label-width="68px">
      <el-form-item :label="t('EquipmentManagement.RepairItems.subjectCode')" prop="subjectCode">
        <el-input
          v-model="queryParams.subjectCode"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderSubjectCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.RepairItems.subjectName')" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderSubjectName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.RepairItems.deviceType')" prop="deviceType">
        <el-select
          v-model="queryParams.deviceType"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderDeviceType')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option v-for="opt in deviceTypeOptions" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <!--
      <el-form-item label="检验方式" prop="inspectionMethod">
        <el-select v-model="queryParams.inspectionMethod" placeholder="请选择检验方式" clearable filterable class="!w-240px">
          <el-option v-for="dict in inspectionMethodOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="值类型" prop="valueType">
        <el-select v-model="queryParams.valueType" placeholder="请选择值类型" clearable filterable class="!w-240px">
          <el-option v-for="dict in valueTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="判定基准" prop="judgmentCriteria">
        <el-input
          v-model="queryParams.judgmentCriteria"
          placeholder="请输入判定基准"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      -->
      <el-form-item :label="t('EquipmentManagement.RepairItems.projectContent')" prop="projectContent">
        <el-input
          v-model="queryParams.projectContent"
          :placeholder="t('EquipmentManagement.RepairItems.placeholderProjectContent')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.RepairItems.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('EquipmentManagement.RepairItems.placeholderCreateTimeStart')"
          :end-placeholder="t('EquipmentManagement.RepairItems.placeholderCreateTimeEnd')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </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:repair-tems:create']">
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" :disabled="!selectedIds.length" v-hasPermi="['mes:repair-tems:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> {{ t('EquipmentManagement.RepairItems.batchDelete') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['mes:repair-tems: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.RepairItems.subjectCode')" align="center" prop="subjectCode" min-width="130" :formatter="cellOrDash" />
      <el-table-column :label="t('EquipmentManagement.RepairItems.subjectName')" align="center" prop="subjectName" min-width="160" :formatter="cellOrDash" />
      <el-table-column :label="t('EquipmentManagement.RepairItems.deviceType')" align="center" prop="deviceType" min-width="140">
        <template #default="scope">
          <el-tag effect="light">{{ getDeviceTypeName(scope.row.deviceType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('EquipmentManagement.RepairItems.deviceName')" align="center" prop="deviceName" min-width="160" :formatter="cellOrDash" />
      <el-table-column :label="t('EquipmentManagement.RepairItems.componentName')" align="center" prop="componentName" min-width="160" :formatter="cellOrDash" />
      <!--
      <el-table-column label="检验方式" align="center" prop="inspectionMethod" width="120">
        <template #default="scope">
          <dict-tag type="Inspection_method" :value="scope.row.inspectionMethod" />
        </template>
      </el-table-column>
      <el-table-column label="值类型" align="center" prop="valueType" width="120">
        <template #default="scope">
          <dict-tag type="value_types" :value="scope.row.valueType" />
        </template>
      </el-table-column>
      <el-table-column label="判定基准" align="center" prop="judgmentCriteria" min-width="180" />
      -->
      <el-table-column :label="t('EquipmentManagement.RepairItems.projectContent')" align="center" prop="projectContent" min-width="200" :formatter="cellOrDash" />
      <el-table-column :label="t('EquipmentManagement.RepairItems.createTime')" align="center" prop="createTime" :formatter="dateOrDash" width="180" />
      <el-table-column :label="t('EquipmentManagement.RepairItems.operate')" align="center" width="140" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
            v-hasPermi="['mes:repair-tems:update']"
          >
            {{ t('action.update') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['mes:repair-tems: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>

  <RepairItemsForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { RepairItemsApi, RepairItemVO } from '@/api/mes/repairItems'
import RepairItemsForm from './RepairItemsForm.vue'
// import { getStrDictOptions } from '@/utils/dict'
// import { useDictStoreWithOut } from '@/store/modules/dict'

defineOptions({ name: 'RepairItems' })

const message = useMessage()
const { t } = useI18n()

// const dictStore = useDictStoreWithOut()
// const dictReady = ref(false)
// const inspectionMethodOptions = computed(() => (dictReady.value ? getStrDictOptions('Inspection_method') : []))
// const valueTypeOptions = computed(() => (dictReady.value ? getStrDictOptions('value_types') : []))

const loading = ref(true)
const list = ref<RepairItemVO[]>([])
const total = ref(0)
const exportLoading = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  subjectCode: undefined as string | undefined,
  subjectName: undefined as string | undefined,
  deviceType: undefined as number | undefined,
  inspectionMethod: undefined as string | undefined,
  valueType: undefined as string | undefined,
  judgmentCriteria: undefined as string | undefined,
  isEnable: undefined as string | undefined,
  projectContent: undefined as string | undefined,
  createTime: [] as string[]
})

const queryFormRef = ref()
const tableRef = ref()
const selectedIds = ref<number[]>([])
const formRef = ref()

const deviceTypeOptions = ref<{ label: string; value: number }[]>([
  { label: t('EquipmentManagement.RepairItems.deviceTypeDevice'), value: 1 },
  { label: t('EquipmentManagement.RepairItems.deviceTypeComponent'), value: 2 }
])

const getDeviceTypeName = (value: any) => {
  if (value === undefined || value === null || value === '') return '-'
  const v = typeof value === 'number' ? value : Number(value)
  if (v === 1) return t('EquipmentManagement.RepairItems.deviceTypeDevice')
  if (v === 2) return t('EquipmentManagement.RepairItems.deviceTypeComponent')
  return String(value)
}

const cellOrDash = (_row: any, _column: any, cellValue: any) => {
  if (cellValue === undefined || cellValue === null || cellValue === '') return '-'
  return String(cellValue)
}

const dateOrDash = (row: any, column: any, cellValue: any) => {
  const text = dateFormatter(row, column, cellValue)
  if (text === undefined || text === null || text === '') return '-'
  return String(text)
}


const getList = async () => {
  loading.value = true
  try {
    const data = await RepairItemsApi.getRepairItemsPage(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 handleSelectionChange = (rows: any[]) => {
  selectedIds.value = rows?.map((row) => row.id).filter((id) => id !== undefined) ?? []
}

const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

const buildIdsParam = (ids: number | number[]) => {
  return Array.isArray(ids) ? ids.join(',') : String(ids)
}

const handleDelete = async (ids: number | number[]) => {
  try {
    await message.delConfirm()
    await RepairItemsApi.deleteRepairItems(buildIdsParam(ids))
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    tableRef.value?.clearSelection?.()
    await getList()
  } catch {}
}

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

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await RepairItemsApi.exportRepairItems(params)
    download.excel(data, t('EquipmentManagement.RepairItems.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

onMounted(async () => {
  await getList()
})
</script>
