<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
      <el-form-item :label="t('MoldManagement.MoldRepair.repairCode')" prop="repairCode">
        <el-input
          v-model="queryParams.repairCode"
          :placeholder="t('MoldManagement.MoldRepair.placeholderRepairCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldRepair.repairName')" prop="repairName">
        <el-input
          v-model="queryParams.repairName"
          :placeholder="t('MoldManagement.MoldRepair.placeholderRepairName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

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

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

      <el-form-item :label="t('MoldManagement.MoldRepair.requireDate')" prop="requireDate">
        <el-date-picker
          v-model="queryParams.requireDate" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          :start-placeholder="t('MoldManagement.MoldRepair.placeholderRequireDateStart')"
          :end-placeholder="t('MoldManagement.MoldRepair.placeholderRequireDateEnd')"
          :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('MoldManagement.MoldRepair.finishDate')" prop="finishDate">
        <el-date-picker
          v-model="queryParams.finishDate" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          :start-placeholder="t('MoldManagement.MoldRepair.placeholderFinishDateStart')"
          :end-placeholder="t('MoldManagement.MoldRepair.placeholderFinishDateEnd')"
          :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('MoldManagement.MoldRepair.confirmDate')" prop="confirmDate">
        <el-date-picker
          v-model="queryParams.confirmDate" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          :start-placeholder="t('MoldManagement.MoldRepair.placeholderConfirmDateStart')"
          :end-placeholder="t('MoldManagement.MoldRepair.placeholderConfirmDateEnd')"
          :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('MoldManagement.MoldRepair.repairUser')" prop="acceptedBy">
        <el-input
          v-model="queryParams.acceptedBy"
          :placeholder="t('MoldManagement.MoldRepair.placeholderRepairUser')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item :label="t('MoldManagement.MoldRepair.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('MoldManagement.MoldRepair.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('MoldManagement.MoldRepair.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('MoldManagement.MoldRepair.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('MoldManagement.MoldRepair.add') }}
        </el-button>
        <el-button type="danger" plain @click="handleBatchDelete" v-hasPermi="['mes:dv-repair:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> {{ t('MoldManagement.MoldRepair.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('MoldManagement.MoldRepair.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('MoldManagement.MoldRepair.repairCode')" align="center" prop="repairCode" min-width="150" />
      <el-table-column :label="t('MoldManagement.MoldRepair.repairName')" align="center" prop="repairName" min-width="150" />
      <el-table-column :label="t('MoldManagement.MoldRepair.moldName')" align="center" prop="moldName" min-width="160">
        <template #default="scope">
          {{ scope.row.moldName ?? scope.row.machineryName ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldRepair.moldCode')" align="center" prop="moldCode" min-width="160">
        <template #default="scope">
          {{ scope.row.moldCode ?? scope.row.machineryCode ?? '-' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="品牌" align="center" prop="machineryBrand" />
      <el-table-column label="规格型号" align="center" prop="machinerySpec" />
      <el-table-column label="设备类型" 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('MoldManagement.MoldRepair.requireDate')" align="center" prop="requireDate"
        :formatter="dateFormatter2" min-width="130"
      />
      <el-table-column
        :label="t('MoldManagement.MoldRepair.finishDate')" align="center" prop="finishDate"
        :formatter="dateFormatter2" min-width="130"
      />
      <el-table-column
        :label="t('MoldManagement.MoldRepair.confirmDate')" align="center" prop="confirmDate"
        :formatter="dateFormatter2" min-width="130"
      />
      <el-table-column :label="t('MoldManagement.MoldRepair.repairResult')" align="center" prop="repairResult" min-width="160" />
      <el-table-column :label="t('MoldManagement.MoldRepair.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="t('MoldManagement.MoldRepair.acceptUser')" align="center" prop="acceptedBy" min-width="140" />
      <el-table-column :label="t('MoldManagement.MoldRepair.confirmUserShort')" align="center" prop="confirmBy" min-width="140" />
      <el-table-column :label="t('MoldManagement.MoldRepair.status')" align="center" prop="status" min-width="130">
        <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('MoldManagement.MoldRepair.createTime')" align="center" prop="createTime"
        :formatter="dateFormatter" min-width="170" />
      <el-table-column :label="t('MoldManagement.MoldRepair.operate')" align="center" fixed="right" min-width="220">
        <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('MoldManagement.MoldRepair.repair') }}</el-button>
          <el-button
            link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:dv-repair:update']">
            {{ t('MoldManagement.MoldRepair.edit') }}
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:dv-repair:delete']">
            {{ t('MoldManagement.MoldRepair.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>

  <MoldRepairForm 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 { MoldRepairApi, MoldRepairVO } from '@/api/mold/moldrepair'
import MoldRepairForm from './MoldRepairForm.vue'

defineOptions({ name: 'MoldRepair' })

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

const loading = ref(true)
const list = ref<MoldRepairVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  repairCode: undefined,
  repairName: undefined,
  machineryId: undefined,
  moldCode: undefined,
  moldName: 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('MoldManagement.MoldRepair.statusPending'), value: '0' },
  { label: t('MoldManagement.MoldRepair.statusDone'), value: '1' }
]

const getResultLabel = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (v === '0') return t('MoldManagement.MoldRepair.repairResultPending')
  if (v === '1') return t('MoldManagement.MoldRepair.repairResultOk')
  if (v === '2') return t('MoldManagement.MoldRepair.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 getStatusLabel = (value: any) => {
  const v = value === '' || value === null || value === undefined ? undefined : String(value)
  if (v === '0') return t('MoldManagement.MoldRepair.statusPending')
  if (v === '1') return t('MoldManagement.MoldRepair.statusDone')
  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 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 params = {
      ...queryParams,
      moldCode: queryParams.moldCode ?? queryParams.machineryCode,
      moldName: queryParams.moldName ?? queryParams.machineryName,
      machineryCode: queryParams.machineryCode ?? queryParams.moldCode,
      machineryName: queryParams.machineryName ?? queryParams.moldName
    }
    const data = await MoldRepairApi.getMoldRepairPage(params)
    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 MoldRepairApi.deleteMoldRepair(idsParam)
    message.success(t('common.delSuccess'))
    selectedIds.value = []
    tableRef.value?.clearSelection?.()
    await getList()
  } catch { }
}

const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    message.error('请选择需要删除的数据')
    return
  }
  await handleDelete(selectedIds.value)
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await MoldRepairApi.exportMoldRepair(
      selectedIds.value.length
        ? {
            ids: selectedIds.value.join(','),
          }
        : queryParams
    )
    download.excel(data, '设备维修记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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