<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" min-label-width="68px">
      <el-form-item :label="t('MoldManagement.MoldWorkOrderInquiry.planNo')" prop="planNo">
        <el-input
          v-model="queryParams.planNo"
          :placeholder="t('MoldManagement.MoldWorkOrderInquiry.placeholderPlanNo')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('MoldManagement.MoldWorkOrderInquiry.planType')" prop="planType">
        <el-select
          v-model="queryParams.planType"
          :placeholder="t('MoldManagement.MoldWorkOrderInquiry.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('MoldManagement.MoldWorkOrderInquiry.jobStatus')" prop="jobStatus">
        <el-select
          v-model="queryParams.jobStatus"
          :placeholder="t('MoldManagement.MoldWorkOrderInquiry.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('MoldManagement.MoldWorkOrderInquiry.jobResult')" prop="jobResult" v-show="showAllFilters">
        <el-select
          v-model="queryParams.jobResult"
          :placeholder="t('MoldManagement.MoldWorkOrderInquiry.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 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('MoldManagement.MoldWorkOrderInquiry.reset') }}
        </el-button>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('MoldManagement.MoldWorkOrderInquiry.query') }}
        </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('MoldManagement.MoldWorkOrderInquiry.cancelTask') }}
      </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="t('MoldManagement.MoldWorkOrderInquiry.index')" align="center" width="70" />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.planNo')" align="center" prop="planNo" min-width="160"  sortable />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.moldName')" align="center" prop="moldName" min-width="200"  sortable />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.planType')" align="center" prop="planType" min-width="110" sortable>
        <template #default="scope">
          <el-tag v-if="String(scope.row.planType) === '1'" type="primary">{{ t('MoldManagement.MoldWorkOrderInquiry.planTypeInspect') }}</el-tag>
          <el-tag v-else-if="String(scope.row.planType) === '2'" type="success">{{ t('MoldManagement.MoldWorkOrderInquiry.planTypeMaintain') }}</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.configName')" align="center" prop="configName" min-width="180"  sortable />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.jobStatus')" align="center" prop="jobStatus" min-width="140" sortable>
        <template #default="scope">
          <dict-tag :type="'job_status'" :value="scope.row.jobStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.operatorName')" align="center" prop="operatorName" min-width="160"  sortable />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.taskTime')" align="center" prop="taskTime" :formatter="dateFormatter" min-width="190"  sortable />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.taskEndTime')" align="center" prop="taskEndTime" :formatter="dateFormatter" min-width="200"  sortable />
      <el-table-column :label="t('MoldManagement.MoldWorkOrderInquiry.jobResult')" align="center" prop="jobResult" min-width="110">
        <template #default="scope">
          <el-tag v-if="scope.row.jobResult == '1'" type="success">{{ t('MoldManagement.MoldWorkOrderInquiry.jobResultOk') }}</el-tag>
          <el-tag v-else-if="scope.row.jobResult == '2'" type="danger">{{ t('MoldManagement.MoldWorkOrderInquiry.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('MoldManagement.MoldWorkOrderInquiry.createTime')" align="center" prop="createTime" :formatter="dateFormatter" min-width="190"  sortable />
    </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/mold/ticketManagement'
import TicketResultDialog from '@/views/mold/workOrderInquiry/components/TicketResultDialog.vue'

const { t } = useI18n()

defineOptions({ name: 'MoldWorkOrderInquiry' })

const message = useMessage()
const dictStore = useDictStoreWithOut()

const planTypeOptions = [
  { label: t('MoldManagement.MoldWorkOrderInquiry.planTypeInspect'), value: '1' },
  { label: t('MoldManagement.MoldWorkOrderInquiry.planTypeMaintain'), value: '2' }
]
const jobResultOptions = [
  { label: t('MoldManagement.MoldWorkOrderInquiry.jobResultOk'), value: 'OK' },
  { label: t('MoldManagement.MoldWorkOrderInquiry.jobResultNg'), 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 showAllFilters = ref(false)
const filterCount = 4
const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
}

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('MoldManagement.MoldWorkOrderInquiry.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('MoldManagement.MoldWorkOrderInquiry.cancelSuccess'))
    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,
    jobStatus: row.jobStatus,
    cancelReason: row.cancelReason,
    title: row.planNo
      ? `${t('MoldManagement.MoldWorkOrderInquiry.inspectResultTitlePrefix')}${row.planNo}`
      : t('MoldManagement.MoldWorkOrderInquiry.inspectResultTitle')
  })
}

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