<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 68em">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row >
      <el-col :span="12">
      <el-form-item :label="t('faultForm.device')" prop="deviceName">
        <el-select
          v-if="disabled"
          :disabled="disabled"
          v-model="formData.deviceName"
          :placeholder="t('faultForm.choose')"
          clearable
          @clear="handleClear"
        />
        <el-select
          v-if="!disabled"
          v-model="formData.deviceName"
          :placeholder="t('faultForm.choose')"
          @click="openForm"
          clearable
          @clear="handleClear"
        />
      </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('faultForm.solve')" prop="ifDeal">
            <el-select v-model="formData.ifDeal" :placeholder="t('faultForm.choose')" @change="dealChange" clearable :disabled="disabled">
              <el-option
                v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="dict.label"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('faultForm.assist')" prop="needHelp" >
            <el-select v-model="formData.needHelp" :placeholder="t('faultForm.choose')" @change="helpChange" clearable :disabled="disabled">
              <el-option
                v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="dict.label"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('faultForm.faultySystem')" prop="failureSystem" :disabled="disabled">
            <el-input v-model="formData.failureSystem" :placeholder="t('faultForm.faultySystemHolder')" :disabled="disabled" />
          </el-form-item>
        </el-col>
      <el-col :span="12">
      <el-form-item :label="t('faultForm.failureTime')" prop="failureTime" :disabled="disabled">
        <el-date-picker
          :disabled="disabled"
          style="width: 150%"
          v-model="formData.failureTime"
          type="datetime"
          value-format="x"
          :placeholder="t('faultForm.failureTimeHolder')"
        />
      </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.ifDeal">
          <el-form-item :label="t('faultForm.dealTime')" prop="dealTime">
            <el-date-picker
              @change="endTimeBlur"
              :disabled="disabled"
              style="width: 150%"
              v-model="formData.dealTime"
              type="datetime"
              value-format="x"
              placeholder="选择故障解决时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('faultForm.shutDown')" prop="ifStop">
            <el-select v-model="formData.ifStop" :placeholder="t('faultForm.choose')" clearable :disabled="disabled">
              <el-option
                v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                :key="dict.label"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('faultForm.picture')" prop="pic">
            <UploadImg v-model="formData.pic" height="60px" :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!formData.ifDeal">
          <el-form-item :label="t('faultForm.approvalId')" prop="approvalId" :rules="!formData.ifDeal?approvalRule:[]">
            <el-select multiple v-model="formData.approvalId" :placeholder="t('faultForm.approvalHolder')" filterable clearable :disabled="disabled">
              <el-option
                v-for="ap in approver"
                :key="ap.id"
                :label="ap.nickname"
                :value="ap.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('faultForm.faultImpact')" prop="failureInfluence">
            <el-input type="textarea" v-model="formData.failureInfluence" :placeholder="t('faultForm.faultImpactHolder')" :disabled="disabled" />
          </el-form-item>
        </el-col>
      <el-col :span="24">
      <el-form-item label="解决办法" v-if="formData.ifDeal" prop="solution" :rules="formData.ifDeal?solutionRule:[]">
        <el-input v-model="formData.solution" type="textarea" placeholder="请输入解决办法" :disabled="disabled" />
      </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('faultForm.faultDescription')" prop="description">
            <el-input type="textarea" v-model="formData.description" :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
      <el-form-item :label="t('faultForm.remark')" prop="remark">
        <el-input v-model="formData.remark" type="textarea" :placeholder="t('faultForm.rHolder')" :disabled="disabled" />
      </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" v-if="!disabled" :disabled="formLoading">{{t('faultForm.ok')}}</el-button>
      <el-button @click="dialogVisible = false">{{t('faultForm.cancel')}}</el-button>
    </template>
    <DeviceList ref="deviceFormRef" @choose="deviceChoose" />
  </Dialog>
</template>
<script setup lang="ts">
import { IotFailureReportApi, IotFailureReportVO } from '@/api/pms/failure'
import {DICT_TYPE, getBoolDictOptions} from "@/utils/dict";
import DeviceList from "@/views/pms/failure/DeviceList.vue";
import dayjs from "dayjs";

/** 故障上报 表单 */
defineOptions({ name: 'IotFailureReportForm' })

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 deviceLabel = ref('') // 表单的类型：create - 新增；update - 修改
const approver = ref([])
const formData = ref({
  approvalId:undefined,
  id: undefined,
  failureCode: undefined,
  failureName: undefined,
  deviceId: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  status: undefined,
  ifStop: undefined,
  failureTime: undefined,
  dealTime: undefined,
  failureInfluence: undefined,
  failureSystem: undefined,
  description: undefined,
  pic: undefined,
  ifDeal: undefined,
  needHelp: undefined,
  solution: undefined,
  remark: undefined,
  deptId: undefined,
})
const dealChange = () => {
  console.log(formData.value.ifDeal)
  formData.value.needHelp = !formData.value.ifDeal
  if (!formData.value.ifDeal){
    IotFailureReportApi.getApproval().then(res=>{
      approver.value = res
    })
  }
}
const helpChange = () => {
  formData.value.ifDeal = !formData.value.needHelp
}
const deviceChoose = (row) => {
  formData.value.deviceId = row.id
  formData.value.deviceName = row.deviceName
  formData.value.deviceCode = row.deviceCode
  formData.value.deptId = row.deptId;
  // deviceLabel.value = row.deviceName
}
const endTimeBlur = () => {
  if (formData.value.dealTime <= formData.value.failureTime) {
    message.error('故障解决时间不得早于故障时间')
    formData.value.dealTime = undefined
  }
  const now = dayjs();
  const target = dayjs(formData.value.dealTime);
  if (target.isAfter(now)) {
    message.error('故障解决时间不得晚于当前时间')
    formData.value.dealTime = undefined
  }
}
const handleClear = () =>{
  formData.value.deviceId = undefined
  formData.value.deviceName = undefined
  formData.value.deptId = undefined
}
/** 添加/修改操作 */
const deviceFormRef = ref()
const openForm = () => {
  deviceFormRef.value.open()
}
const formRules = ref({
  deviceName: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  ifDeal: [{ required: true, message: '是否解决不能为空', trigger: 'blur' }],
  needHelp: [{ required: true, message: '是否协助不能为空', trigger: 'blur' }],
  failureTime:[{ required: true, message: '故障时间不能为空', trigger: 'blur' }],
  failureSystem:[{ required: true, message: '故障系统不能为空', trigger: 'blur' }],
  dealTime:[{ required: true, message: '故障解决时间不能为空', trigger: 'blur' }],
  // solution:[{required: ()=> formData.value.ifDeal==='true', message: '解决办法不能为空', trigger: 'blur'}],
})
const solutionRule = [
  { required: true, message: '解决办法不能为空', trigger: 'blur' }
];
const approvalRule = [
  { required: true, message: '审批人不能为空', trigger: 'blur' }
];
const formRef = ref() // 表单 Ref
const disabled = ref(false)
/** 打开弹窗 */
const open = async (type: string, id?: number, disable?:boolean) => {
  disabled.value = disable
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.deviceId = null;
  formData.value.deviceName = null;
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await IotFailureReportApi.getIotFailureReport(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // formData.value.pic = formData.value.pic.path;
    const data = formData.value as unknown as IotFailureReportVO
    if (!formData.value.ifDeal){
      debugger
      formData.value.approvalId = formData.value.approvalId.join(',')
    }
    if (formType.value === 'create') {
      await IotFailureReportApi.createIotFailureReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotFailureReportApi.updateIotFailureReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    failureCode: undefined,
    failureName: undefined,
    deviceId: undefined,
    status: undefined,
    ifStop: undefined,
    failureTime: undefined,
    failureInfluence: undefined,
    failureSystem: undefined,
    description: undefined,
    pic: undefined,
    ifDeal: undefined,
    needHelp: undefined,
    solution: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>
