<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务编号" prop="taskNumber">
        <el-input
          v-model="queryParams.taskNumber"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_MAINTENANCE_TASK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!--        <el-button-->
        <!--            type="danger"-->
        <!--            plain-->
        <!--            :disabled="isEmpty(checkedIds)"-->
        <!--            @click="handleDeleteBatch"-->
        <!--            v-hasPermi="['device:maintenance-tasks:delete']"-->
        <!--        >-->
        <!--          <Icon icon="ep:delete" class="mr-5px" /> 批量删除-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="计划名称" align="center" prop="planName" width="120" />
      <el-table-column label="设备名称" align="center" prop="deviceName" width="120" />
      <el-table-column label="任务编号" align="center" prop="taskNumber" width="150" />
      <el-table-column label="任务名称" align="center" prop="taskName" width="180" />
      <el-table-column
        label="计划开始时间"
        align="center"
        prop="planStartTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="计划结束时间"
        align="center"
        prop="planEndTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="实际开始时间"
        align="center"
        prop="actualStartTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="实际完成时间"
        align="center"
        prop="actualEndTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="任务状态"
        align="center"
        prop="taskStatus"
        width="100px"
        fixed="right"
      >
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.DEVICE_MAINTENANCE_TASK_STATUS"
            :value="scope.row.taskStatus"
          />
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        label="创建时间"-->
      <!--        align="center"-->
      <!--        prop="createTime"-->
      <!--        :formatter="dateFormatter"-->
      <!--        width="180px"-->
      <!--      />-->
      <el-table-column label="操作" align="center" min-width="250px" fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.taskStatus === 0"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审核
          </el-button>

          <el-button
            v-if="scope.row.processInstanceId"
            link
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>
          <el-button link type="primary" @click="openForm('detail', scope.row.id)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MaintenanceTasksForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MaintenanceTasksApi, MaintenanceTasksVO } from '@/api/device/maintenancetasks'
import MaintenanceTasksForm from './MaintenanceTasksForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

/** 设备保养任务 列表 */
defineOptions({ name: 'DeviceMaintenanceTasks' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MaintenanceTasksVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  taskNumber: undefined,
  taskName: undefined,
  planId: undefined,
  deviceId: undefined,
  planStartTime: [],
  planEndTime: [],
  actualStartTime: [],
  actualEndTime: [],
  taskStatus: undefined,
  actualMaintainerId: undefined,
  actualMaintainerName: undefined,
  collaboratorIds: undefined,
  collaboratorNames: undefined,
  inspectorId: undefined,
  inspectorName: undefined,
  inspectionTime: [],
  inspectionDescription: undefined,
  maintenanceType: undefined,
  responsibleId: undefined,
  responsibleName: undefined,
  maintenanceInstructions: undefined,
  maintenanceDescription: undefined,
  attachmentUrls: undefined,
  inspectionResult: undefined,
  inspectionAttachmentUrls: undefined,
  processInstanceId: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MaintenanceTasksApi.getMaintenanceTasksPage(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 openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 保养执行操作
const executeMaintenance = (id: number) => {
  formRef.value.open('execute', id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MaintenanceTasksApi.deleteMaintenanceTasks(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除设备保养任务 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await MaintenanceTasksApi.deleteMaintenanceTasksList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: MaintenanceTasksVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MaintenanceTasksApi.exportMaintenanceTasks(queryParams)
    download.excel(data, '设备保养任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const { push } = useRouter()
/** 提交审核 **/
const handleSubmit = async (row: MaintenanceTasksVO) => {
  await message.confirm(`您确定提交【${row.taskName}】审核吗？`)
  await MaintenanceTasksApi.submitAudit(row.id)
  message.success('提交审核成功！')
  await getList()
}
/** 查看审批 */
const handleProcessDetail = (row: MaintenanceTasksVO) => {
  push({
    name: 'BpmProcessInstanceDetail',
    query: { id: row.processInstanceId, path: '/device/maintenance-tasks' }
  })
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
