﻿<template>
  <template v-if="!resultVisible">
  <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" v-show="showAllFilters">
        <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 :label="t('EquipmentManagement.WorkOrderManagement.operatorName')" prop="operator" v-show="showAllFilters">
        <el-select
          v-model="queryParams.operator"
          filterable
          :placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderOperatorName')"
          clearable
          class="!w-240px"
        >
          <el-option v-for="item in users" :key="String(item.id)" :label="item.nickname" :value="String(item.id)" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('EquipmentManagement.WorkOrderManagement.taskTimeRange')" prop="taskTimeRange" v-show="showAllFilters">
        <el-date-picker
          v-model="queryParams.taskTimeRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          :start-placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderTaskTime')"
          :end-placeholder="t('EquipmentManagement.WorkOrderManagement.placeholderTaskEndTime')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-if="filterCount > 3">
        <el-button type="text" class="text-primary" @click="toggleFilters">
          <Icon :icon="showAllFilters ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-5px" />
          {{ showAllFilters ? t('FactoryModeling.FactoryStructure.collapseText') : t('FactoryModeling.FactoryStructure.expandText') }}
        </el-button>
      </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" />
          {{ t('action.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

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

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :max-height="planTableMaxHeight"
      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"
       sortable />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.deviceName')"
        align="center"
        prop="deviceName"
        min-width="160"
       sortable />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.planType')"
        align="center"
        prop="planType"
        width="90"
       sortable>
        <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"
       sortable />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.jobStatus')"
        align="center"
        prop="jobStatus"
        width="120"
       sortable>
        <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"
       sortable />
      <el-table-column
        :label="t('EquipmentManagement.WorkOrderManagement.taskTime')"
        align="center"
        prop="taskTime"
        :formatter="dateFormatter"
        width="180"
       sortable />
      <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"
       sortable />
    </el-table>

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


  </template>

  <TicketResultDialog
    v-else
    :ticket-row="selectedResultRow"
    :title="resultTitle"
    @success="handleResultSuccess"
    @closed="handleResultClosed"
  />
</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 { getSimpleUserList, UserVO } from '@/api/system/user'
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: '1' },
  { label: t('EquipmentManagement.WorkOrderManagement.jobResultNg'), value: '2' }
]

const loading = ref(true)
const list = ref<TicketManagementVO[]>([])
const total = ref(0)
const tableRef = ref()
const planTableMaxHeight = ref(520)
const planPaginationRef = ref<HTMLElement>()

const updatePlanTableMaxHeight = async () => {
  await nextTick()
  const tableTop = tableRef.value?.$el?.getBoundingClientRect().top ?? 0
  const paginationHeight = planPaginationRef.value?.getBoundingClientRect().height ?? 72
  const pageBottomGap = 56
  const availableHeight = window.innerHeight - tableTop - paginationHeight - pageBottomGap
  planTableMaxHeight.value = Math.min(window.innerHeight, Math.max(240, Math.floor(availableHeight)))
}
const selectedIds = ref<number[]>([])
const selectedRows = ref<TicketManagementVO[]>([])
const cancelLoading = ref(false)
const exportLoading = ref(false)
const users = ref<UserVO[]>([])
const resultVisible = ref(false)
const selectedResultRow = ref<TicketManagementVO>()
const resultTitle = computed(() => {
  const row = selectedResultRow.value
  if (!row) return t('EquipmentManagement.WorkOrderManagement.dialogTitleDefault')
  return row.planNo
    ? `${t('EquipmentManagement.WorkOrderManagement.dialogTitleDefault')}-${row.planNo}`
    : t('EquipmentManagement.WorkOrderManagement.dialogTitleDefault')
})


const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  planNo: undefined as string | undefined,
  planType: undefined as string | undefined,
  jobStatus: '0' as string | undefined,
  jobResult: undefined as string | undefined,
  operator: undefined as string | undefined,
  taskTimeRange: [] as string[]
})

const queryFormRef = ref()
const showAllFilters = ref(false)
const filterCount = 6
const UNWORKED_JOB_STATUS = '0'
const CANCELED_JOB_STATUS = '4'

const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
  updatePlanTableMaxHeight()
}

const isUnworkedTicket = (row?: TicketManagementVO) => String(row?.jobStatus ?? '') === UNWORKED_JOB_STATUS
const hasUncancelableSelection = computed(() => selectedRows.value.some((row) => !isUnworkedTicket(row)))
const isCancelDisabled = computed(() => !selectedIds.value.length || hasUncancelableSelection.value)

const buildQueryParams = () => {
  const { taskTimeRange, ...params } = queryParams
  return {
    ...params,
    taskTime: taskTimeRange?.[0],
    taskEndTime: taskTimeRange?.[1]
  }
}

const getList = async () => {
  loading.value = true
  try {
    const data = await TicketManagementApi.getTicketManagementPage(buildQueryParams())
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
    updatePlanTableMaxHeight()
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleSelectionChange = (rows: TicketManagementVO[]) => {
  selectedRows.value = rows
  selectedIds.value = rows
    .map((r) => r.id)
    .filter((id): id is string => id != null && id !== '')
}

const handleBatchCancel = async () => {
  if (!selectedIds.value.length) return
  if (hasUncancelableSelection.value) {
    message.warning(t('EquipmentManagement.WorkOrderManagement.cancelOnlyUnworkedTip'))
    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: CANCELED_JOB_STATUS,
      cancelReason: value
    })
    message.success(t('EquipmentManagement.WorkOrderManagement.cancelSuccess'))
    selectedIds.value = []
    selectedRows.value = []
    await getList()
  } catch {
  } finally {
    cancelLoading.value = false
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params: any = {
      ...buildQueryParams(),
      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 handleRowClick = (row: TicketManagementVO, column: any) => {
  if (column?.type === 'selection') return
  if (!row?.id) return
  selectedResultRow.value = row
  resultVisible.value = true
}

const handleResultClosed = () => {
  resultVisible.value = false
  selectedResultRow.value = undefined
}

const handleResultSuccess = async () => {
  resultVisible.value = false
  selectedResultRow.value = undefined
  await getList()
}

onMounted(async () => {
  await dictStore.setDictMap()
  users.value = await getSimpleUserList()
  await getList()
  updatePlanTableMaxHeight()
  window.addEventListener("resize", updatePlanTableMaxHeight)
})

onBeforeUnmount(() => {
  window.removeEventListener("resize", updatePlanTableMaxHeight)
})
</script>
