<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" min-label-width="68px">
      <el-form-item :label="t('EquipmentManagement.WorkOrderManagement.planNo')" prop="planNo">
        <el-input
          v-model="queryParams.planNo"
          :placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderPlanNo')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.WorkOrderManagement.planType')" prop="planType">
        <el-select
          v-model="queryParams.planType"
          :placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderPlanType')"
          clearable
          class="!w-240px"
        >
          <el-option v-for="opt in planTypeOptions" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.WorkOrderManagement.jobStatus')" prop="jobStatus">
        <el-select
          v-model="queryParams.jobStatus"
          :placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderJobStatus')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="opt in getStrDictOptions('job_status')"
            :key="String(opt.value)"
            :label="opt.label"
            :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.WorkOrderManagement.jobResult')" prop="jobResult">
        <el-select
          v-model="queryParams.jobResult"
          :placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderJobResult')"
          clearable
          class="!w-240px"
        >
          <el-option v-for="opt in jobResultOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.query') }}
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <div class="mb-10px">
      <el-button
        type="warning"
        plain
        @click="handleBatchCancel"
        :disabled="!selectedIds.length"
        :loading="cancelLoading"
      >
        {{ t('EquipmentManagement.WorkOrderManagement.cancelTask') }}
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column
        type="index"
        :label="t('EquipmentManagement.WorkOrderManagement.index')"
        align="center"
        width="70"
      /> -->
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.planNo')"
        align="center"
        prop="planNo"
        min-width="160"
      />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.deviceName')"
        align="center"
        prop="deviceName"
        min-width="160"
      />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.planType')"
        align="center"
        prop="planType"
        width="90"
      >
        <template #default="scope">
          <el-tag v-if="String(scope.row.planType) === '1'" type="primary">
            {{ t('EquipmentManagement.WorkOrderManagement.planTypeInspect') }}
          </el-tag>
          <el-tag v-else-if="String(scope.row.planType) === '2'" type="success">
            {{ t('EquipmentManagement.WorkOrderManagement.planTypeMaintain') }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.configName')"
        align="center"
        prop="configName"
        min-width="160"
      />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.jobStatus')"
        align="center"
        prop="jobStatus"
        width="120"
      >
        <template #default="scope">
          <dict-tag :type="'job_status'" :value="scope.row.jobStatus" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.operatorName')"
        align="center"
        prop="operatorName"
        width="140"
      />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.taskTime')"
        align="center"
        prop="taskTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.taskEndTime')"
        align="center"
        prop="taskEndTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.jobResult')"
        align="center"
        prop="jobResult"
        width="90"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.jobResult == '1'" type="success">
            {{ t('EquipmentManagement.WorkOrderManagement.jobResultOk') }}
          </el-tag>
          <el-tag v-else-if="scope.row.jobResult == '2'" type="danger">
            {{ t('EquipmentManagement.WorkOrderManagement.jobResultNg') }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" min-width="160" /> -->
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.createTime')"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
    </el-table>

    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <TicketResultDialog ref="resultDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { getStrDictOptions } from '@/utils/dict'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { TicketManagementApi, TicketManagementVO } from '@/api/mes/ticketManagement'
import TicketResultDialog from './components/TicketResultDialog.vue'

defineOptions({ name: 'WorkOrderManagement' })

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

const planTypeOptions = [
  { label: t('EquipmentManagement.WorkOrderManagement.planTypeInspect'), value: '1' },
  { label: t('EquipmentManagement.WorkOrderManagement.planTypeMaintain'), value: '2' }
]
const jobResultOptions = [
  { label: t('EquipmentManagement.WorkOrderManagement.jobResultOk'), value: 'OK' },
  { label: t('EquipmentManagement.WorkOrderManagement.jobResultNg'), value: 'NG' }
]

const loading = ref(true)
const list = ref<TicketManagementVO[]>([])
const total = ref(0)
const selectedIds = ref<number[]>([])
const cancelLoading = ref(false)
const exportLoading = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planNo: undefined as string | undefined,
  planType: undefined as string | undefined,
  jobStatus: undefined as string | undefined,
  jobResult: undefined as string | undefined
})

const queryFormRef = ref()

const getList = async () => {
  loading.value = true
  try {
    const data = await TicketManagementApi.getTicketManagementPage(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: TicketManagementVO[]) => {
  selectedIds.value = rows
    .map((r) => r.id)
    .filter((id): id is number => typeof id === 'number')
}

const handleBatchCancel = async () => {
  if (!selectedIds.value.length) return
  try {
    const { value } = await ElMessageBox.prompt('请输入取消原因', t('EquipmentManagement.WorkOrderManagement.cancelTask'), {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/,
      inputErrorMessage: '取消原因不能为空'
    })
    cancelLoading.value = true
    await TicketManagementApi.batchUpdateTicketStatus({
      ids: selectedIds.value.join(','),
      jobStatus: '4',
      cancelReason: value
    })
    message.success(t('EquipmentManagement.WorkOrderManagement.cancelSuccess'))
    selectedIds.value = []
    await getList()
  } catch {
  } finally {
    cancelLoading.value = false
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params: any = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined
    }
    const data = await TicketManagementApi.exportTicketManagement(params)
    // 复用系统通用下载工具
    const download = (await import('@/utils/download')).default
    download.excel(data, '工单管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const resultDialogRef = ref<InstanceType<typeof TicketResultDialog>>()

const handleRowClick = async (row: TicketManagementVO, column: any) => {
  if (column?.type === 'selection') return
  if (!row?.id) return
  await resultDialogRef.value?.open({
    managementId: row.id,
    jobStatus: row.jobStatus,
    cancelReason: row.cancelReason,
    title: row.planNo
      ? `${t('EquipmentManagement.WorkOrderManagement.dialogTitleDefault')}-${row.planNo}`
      : t('EquipmentManagement.WorkOrderManagement.dialogTitleDefault')
  })
}

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