<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="单号" prop="planNo">
        <el-input
v-model="queryParams.planNo" placeholder="请输入单号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="类型" prop="planType">
        <el-select v-model="queryParams.planType" placeholder="请选择类型" 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="作业状态" prop="jobStatus">
        <el-select v-model="queryParams.jobStatus" placeholder="请选择作业状态" 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="结果" prop="jobResult">
        <el-select v-model="queryParams.jobResult" placeholder="请选择结果" 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" /> 重置
        </el-button>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" 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">
        取消任务
      </el-button>
    </div>

    <el-table
v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange" @row-click="handleRowClick">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" align="center" width="70" />
      <el-table-column label="单号" align="center" prop="planNo" min-width="160" />
      <el-table-column label="设备名称" align="center" prop="deviceName" min-width="160" />
      <el-table-column label="类型" align="center" prop="planType" width="90">
        <template #default="scope">
          <el-tag v-if="String(scope.row.planType) === '1'" type="primary">点检</el-tag>
          <el-tag v-else-if="String(scope.row.planType) === '2'" type="success">保养</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="计划配置名称" align="center" prop="configName" min-width="160" />
      <el-table-column label="作业状态" 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="作业人" align="center" prop="operatorName" width="140" />
      <el-table-column label="作业时间" align="center" prop="taskTime" :formatter="dateFormatter" width="180" />
      <el-table-column label="计划结束作业时间" align="center" prop="taskEndTime" :formatter="dateFormatter" width="180" />
      <el-table-column label="结果" align="center" prop="jobResult" width="90">
        <template #default="scope">
          <el-tag v-if="scope.row.jobResult == '1'" type="success">通过</el-tag>
          <el-tag v-else-if="scope.row.jobResult == '2'" type="danger">不通过</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="创建时间" 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" />
</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: '点检', value: '1' },
  { label: '保养', value: '2' }
]
const jobResultOptions = [
  { label: '通过', value: 'OK' },
  { label: '不通过', value: 'NG' }
]

const loading = ref(true)
const list = ref<TicketManagementVO[]>([])
const total = ref(0)
const selectedIds = ref<number[]>([])
const cancelLoading = 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 {
    await message.confirm('确认取消选中的任务吗？')
    cancelLoading.value = true
    await TicketManagementApi.batchUpdateTicketStatus({ ids: selectedIds.value.join(','), jobStatus: '2' })
    message.success('取消任务成功')
    selectedIds.value = []
    await getList()
  } catch {
  } finally {
    cancelLoading.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,
    title: row.planNo ? `检验结果-${row.planNo}` : '检验结果'
  })
}

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