<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
      <el-form-item :label="t('QualityManagement.ZjTask.code')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('QualityManagement.ZjTask.placeholderCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.type')" prop="type">
        <el-select
          v-model="queryParams.type"
          clearable
          filterable
          :placeholder="t('QualityManagement.ZjTask.placeholderType')"
          class="!w-240px"
        >
          <el-option
v-for="dict in getStrDictOptions('mes_zj_task_type')" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="工单" prop="ticket">
        <el-input
v-model="queryParams.ticket" placeholder="请输入工单" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item> -->
      <el-form-item :label="t('QualityManagement.ZjTask.orgType')" prop="orgType">
        <el-select
          v-model="queryParams.orgType"
          clearable
          :placeholder="t('QualityManagement.ZjTask.placeholderOrgType')"
          class="!w-240px"
        >
          <el-option v-for="item in orgTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          clearable
          :placeholder="t('QualityManagement.ZjTask.placeholderStatus')"
          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('QualityManagement.ZjTask.result')" prop="result">
        <el-input
          v-model="queryParams.result"
          :placeholder="t('QualityManagement.ZjTask.placeholderResult')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('QualityManagement.ZjTask.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('QualityManagement.ZjTask.placeholderCreateTimeStart')"
          :end-placeholder="t('QualityManagement.ZjTask.placeholderCreateTimeEnd')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> {{ t('common.query') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> {{ t('common.reset') }}
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mes:zj-task:create']">
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.create') }}
        </el-button>
        <el-button
type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mes:zj-task:export']">
          <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="!selectedIds.length"
      >
        {{ t('QualityManagement.ZjTask.cancelTask') }}
      </el-button>
    </div>

    <el-table
      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('QualityManagement.ZjTask.index')" type="index" width="80" />
      <el-table-column :label="t('QualityManagement.ZjTask.code')" align="center" prop="code" />
      <el-table-column :label="t('QualityManagement.ZjTask.type')" align="center">
        <template #default="scope">
          <DictTag type="mes_zj_task_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjTask.status')" align="center" prop="status">
        <template #default="scope">
          <DictTag :type="'job_status'" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjTask.ticketCode')" align="center" prop="ticketCode" />
      <el-table-column :label="t('QualityManagement.ZjTask.orgType')" align="center" prop="orgType">
        <template #default="scope">
          <DictTag :type="DICT_TYPE.MES_ORG_TYPE" :value="scope.row.orgType" />
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjTask.schemaName')" align="center" prop="schemaName" />
      <el-table-column :label="t('QualityManagement.ZjTask.managerName')" align="center" prop="managerName" />
      <el-table-column :label="t('QualityManagement.ZjTask.executorName')" align="center" prop="executorName" />
      <el-table-column
        :label="t('QualityManagement.ZjTask.executeTime')"
        align="center"
        prop="executeTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column :label="t('QualityManagement.ZjTask.remark')" align="center" prop="remark" />
      <el-table-column :label="t('QualityManagement.ZjTask.result')" align="center" prop="result">
        <template #default="scope">
          <el-tag v-if="scope.row.result === '1' || scope.row.result === 1" type="success">
            {{ t('QualityManagement.ZjTask.resultPass') }}
          </el-tag>
          <el-tag v-else-if="scope.row.result === '2' || scope.row.result === 2" type="danger">
            {{ t('QualityManagement.ZjTask.resultFail') }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('QualityManagement.ZjTask.operate')" align="center" min-width="160px">
        <template #default="scope">
          <el-button
            link
            type="warning"
            @click.stop="handleRowClick(scope.row)"
          >
            {{ t('QualityManagement.ZjTask.inspect') }}
          </el-button>
          <el-button
            link
            type="primary"
            @click.stop="openForm('update', scope.row)"
            v-hasPermi="['mes:zj-task:update']"
          >
            {{ t('action.update') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click.stop="handleDelete(scope.row.id)"
            v-hasPermi="['mes:zj-task:delete']"
          >
            {{ t('action.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>

  <ZjTaskForm ref="formRef" @success="getList" />
  <ZjTaskResultDialog ref="resultDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { DictTag } from '@/components/DictTag'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { ZjTaskApi, ZjTaskVO } from '@/api/mes/zjtask'
import ZjTaskForm from './ZjTaskForm.vue'
import ZjTaskResultDialog from './components/ZjTaskResultDialog.vue'

defineOptions({ name: 'ZjTask' })

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

const loading = ref(true)
const list = ref<ZjTaskVO[]>([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined as string | undefined,
  name: undefined as string | undefined,
  type: undefined as string | undefined,
  schemaName: undefined as string | undefined,
  ticket: undefined as string | undefined,
  orgType: undefined as string | undefined,
  managerName: undefined as string | undefined,
  executorName: undefined as string | undefined,
  status: undefined as string | undefined,
  result: undefined as string | undefined,
  createTime: [] as string[] | [],
})

const queryFormRef = ref()
const exportLoading = ref(false)

const orgTypeOptions = getStrDictOptions(DICT_TYPE.MES_ORG_TYPE)

const selectedIds = ref<number[]>([])
const cancelLoading = ref(false)

const getList = async () => {
  loading.value = true
  try {
    const data = await ZjTaskApi.getZjTaskPage(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 formRef = ref()
const resultDialogRef = ref()

const openForm = (type: string, row?: ZjTaskVO) => {
  formRef.value.open(type, row)
}

const handleRowClick = (row: ZjTaskVO) => {
  if (!row?.id) return
  resultDialogRef.value?.open({ id: row.id, status: row.status, cancelReason: row.cancelReason })
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ZjTaskApi.deleteZjTask(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch { }
}

const handleSelectionChange = (rows: ZjTaskVO[]) => {
  selectedIds.value = (rows.map((row) => row.id).filter((id) => id !== undefined && id !== null) as number[])
}

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

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = {
      ...queryParams,
      ids: selectedIds.value.length ? selectedIds.value.join(',') : undefined,
    }
    const data = await ZjTaskApi.exportZjTask(params)
    download.excel(data, t('QualityManagement.ZjTask.exportFilename'))
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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