<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备ID" prop="deviceId">
        <el-input v-model="formData.deviceId" placeholder="请输入设备ID" />
      </el-form-item>
      <el-form-item label="维修单号" prop="orderNumber">
        <el-input v-model="formData.orderNumber" placeholder="请输入维修单号" />
      </el-form-item>
      <el-form-item label="报修人姓名" prop="reporterName">
        <el-input v-model="formData.reporterName" placeholder="请输入报修人姓名" />
      </el-form-item>
      <el-form-item label="报修人手机号" prop="reporterPhone">
        <el-input v-model="formData.reporterPhone" placeholder="请输入报修人手机号" />
      </el-form-item>
      <el-form-item label="报修时间" prop="reportTime">
        <el-date-picker
          v-model="formData.reportTime"
          type="date"
          value-format="x"
          placeholder="选择报修时间"
        />
      </el-form-item>
      <el-form-item label="故障类型" prop="faultType">
        <el-select v-model="formData.faultType" placeholder="请选择故障类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DEVICE_FAULT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障等级" prop="faultLevel">
        <el-select v-model="formData.faultLevel" placeholder="请选择故障等级">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DEVICE_FAULT_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障描述" prop="faultDescription">
        <Editor v-model="formData.faultDescription" height="150px" />
      </el-form-item>
      <el-form-item label="报修附件" prop="attachmentUrls">
        <UploadImg v-model="formData.attachmentUrls" />
      </el-form-item>
      <el-form-item label="来源" prop="reportSource">
        <el-input v-model="formData.reportSource" placeholder="请输入来源" />
      </el-form-item>
      <el-form-item label="来源单号" prop="sourceOrderNumber">
        <el-input v-model="formData.sourceOrderNumber" placeholder="请输入来源单号" />
      </el-form-item>
      <el-form-item label="工单状态" prop="state">
        <el-select v-model="formData.state" placeholder="请选择工单状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_WORK_ORDER_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="故障原因" prop="faultReason">
        <el-input v-model="formData.faultReason" placeholder="请输入故障原因" />
      </el-form-item>
      <el-form-item label="计划维修时间" prop="plannedMaintenanceTime">
        <el-date-picker
          v-model="formData.plannedMaintenanceTime"
          type="date"
          value-format="x"
          placeholder="选择计划维修时间"
        />
      </el-form-item>
      <el-form-item label="处理人姓名" prop="assigneeName">
        <el-input v-model="formData.assigneeName" placeholder="请输入处理人姓名" />
      </el-form-item>
      <el-form-item label="处理人手机" prop="assigneePhone">
        <el-input v-model="formData.assigneePhone" placeholder="请输入处理人手机" />
      </el-form-item>
      <el-form-item label="实际开始时间" prop="actualStartTime">
        <el-date-picker
          v-model="formData.actualStartTime"
          type="date"
          value-format="x"
          placeholder="选择实际开始时间"
        />
      </el-form-item>
      <el-form-item label="实际完成时间" prop="actualEndTime">
        <el-date-picker
          v-model="formData.actualEndTime"
          type="date"
          value-format="x"
          placeholder="选择实际完成时间"
        />
      </el-form-item>
      <el-form-item label="维修方式" prop="maintenanceType">
        <el-select v-model="formData.maintenanceType" placeholder="请选择维修方式">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.DEVICE_MAINTENANCE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维修工种" prop="maintenanceCategory">
        <el-input v-model="formData.maintenanceCategory" placeholder="请输入维修工种" />
      </el-form-item>
      <el-form-item label="处理内容" prop="assigneeContent">
        <Editor v-model="formData.assigneeContent" height="150px" />
      </el-form-item>
      <el-form-item label="预防措施" prop="preventiveMeasures">
        <el-input v-model="formData.preventiveMeasures" placeholder="请输入预防措施" />
      </el-form-item>
      <el-form-item label="难易度" prop="difficultyLevel">
        <el-input v-model="formData.difficultyLevel" placeholder="请输入难易度" />
      </el-form-item>
      <el-form-item label="维修附件" prop="assigneeUrls">
        <UploadImg v-model="formData.assigneeUrls" />
      </el-form-item>
      <el-form-item label="停机开始时间" prop="shutdownStartTime">
        <el-date-picker
          v-model="formData.shutdownStartTime"
          type="date"
          value-format="x"
          placeholder="选择停机开始时间"
        />
      </el-form-item>
      <el-form-item label="停机结束时间" prop="shutdownEndTime">
        <el-date-picker
          v-model="formData.shutdownEndTime"
          type="date"
          value-format="x"
          placeholder="选择停机结束时间"
        />
      </el-form-item>
      <el-form-item label="验收人姓名" prop="inspectorName">
        <el-input v-model="formData.inspectorName" placeholder="请输入验收人姓名" />
      </el-form-item>
      <el-form-item label="验收时间" prop="inspectionTime">
        <el-date-picker
          v-model="formData.inspectionTime"
          type="date"
          value-format="x"
          placeholder="选择验收时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { WorkOrdersApi, WorkOrders } from '@/api/device/workorders'

/** 设备维修 表单 */
defineOptions({ name: 'WorkOrdersForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceId: undefined,
  orderNumber: undefined,
  reporterName: undefined,
  reporterPhone: undefined,
  reportTime: undefined,
  faultType: undefined,
  faultLevel: undefined,
  faultDescription: undefined,
  attachmentUrls: undefined,
  reportSource: undefined,
  sourceOrderNumber: undefined,
  state: undefined,
  faultReason: undefined,
  plannedMaintenanceTime: undefined,
  assigneeName: undefined,
  assigneePhone: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  maintenanceType: undefined,
  maintenanceCategory: undefined,
  assigneeContent: undefined,
  preventiveMeasures: undefined,
  difficultyLevel: undefined,
  assigneeUrls: undefined,
  shutdownStartTime: undefined,
  shutdownEndTime: undefined,
  inspectorName: undefined,
  inspectionTime: undefined,
})
const formRules = reactive({
  deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
  orderNumber: [{ required: true, message: '维修单号不能为空', trigger: 'blur' }],
  reporterName: [{ required: true, message: '报修人姓名不能为空', trigger: 'blur' }],
  reportTime: [{ required: true, message: '报修时间不能为空', trigger: 'blur' }],
  faultDescription: [{ required: true, message: '故障描述不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await WorkOrdersApi.getWorkOrders(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as WorkOrders
    if (formType.value === 'create') {
      await WorkOrdersApi.createWorkOrders(data)
      message.success(t('common.createSuccess'))
    } else {
      await WorkOrdersApi.updateWorkOrders(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceId: undefined,
    orderNumber: undefined,
    reporterName: undefined,
    reporterPhone: undefined,
    reportTime: undefined,
    faultType: undefined,
    faultLevel: undefined,
    faultDescription: undefined,
    attachmentUrls: undefined,
    reportSource: undefined,
    sourceOrderNumber: undefined,
    state: undefined,
    faultReason: undefined,
    plannedMaintenanceTime: undefined,
    assigneeName: undefined,
    assigneePhone: undefined,
    actualStartTime: undefined,
    actualEndTime: undefined,
    maintenanceType: undefined,
    maintenanceCategory: undefined,
    assigneeContent: undefined,
    preventiveMeasures: undefined,
    difficultyLevel: undefined,
    assigneeUrls: undefined,
    shutdownStartTime: undefined,
    shutdownEndTime: undefined,
    inspectorName: undefined,
    inspectionTime: undefined,
  }
  formRef.value?.resetFields()
}
</script>
