<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row >
      <el-col :span="12">
      <el-form-item label="设备" prop="deviceName">
        <el-select
          v-model="formData.deviceName"
          :model-value="deviceLabel"
          placeholder="请选择设备"
          @click="openForm"
        />
      </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否解决" prop="ifDeal">
            <el-select v-model="formData.ifDeal" placeholder="请选择" @change="dealChange">
              <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="是否协助" prop="needHelp">
            <el-select v-model="formData.needHelp" placeholder="请选择" @change="helpChange">
              <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="是否停机" prop="ifStop">
        <el-select v-model="formData.ifStop" placeholder="请选择">
          <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="故障时间" prop="failureTime">
        <el-date-picker
          v-model="formData.failureTime"
          type="datetime"
          value-format="x"
          placeholder="选择故障时间"
        />
      </el-form-item>
        </el-col>
      <el-col :span="12">
      <el-form-item label="故障系统" prop="failureSystem">
        <el-input v-model="formData.failureSystem" placeholder="请输入故障系统" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="图片" prop="pic">
            <UploadImg v-model="formData.pic" height="60px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障影响" prop="failureInfluence">
            <el-input type="textarea" v-model="formData.failureInfluence" placeholder="请输入故障影响" />
          </el-form-item>
        </el-col>
      <el-col :span="12">
      <el-form-item label="解决办法" prop="solution">
        <el-input v-model="formData.solution" type="textarea" placeholder="请输入解决办法" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障描述" prop="description">
            <el-input type="textarea" v-model="formData.description" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
          </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</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";

/** 故障上报 表单 */
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 formData = ref({
  id: undefined,
  failureCode: undefined,
  failureName: undefined,
  deviceId: undefined,
  deviceName: undefined,
  status: undefined,
  ifStop: undefined,
  failureTime: undefined,
  failureInfluence: undefined,
  failureSystem: undefined,
  description: undefined,
  pic: undefined,
  ifDeal: undefined,
  needHelp: undefined,
  solution: undefined,
  remark: undefined,
  deptId: undefined,
})
const dealChange = () => {
  formData.value.needHelp = !formData.value.ifDeal
}
const helpChange = () => {
  formData.value.ifDeal = !formData.value.needHelp
}
const deviceChoose = (row) => {
  formData.value.deviceId = row.id
  formData.value.deviceName = row.deviceName
  formData.value.deptId = row.deptId;
  deviceLabel.value = row.deviceName
}
/** 添加/修改操作 */
const deviceFormRef = ref()
const openForm = () => {
  deviceFormRef.value.open()
}
const formRules = reactive({
  // failureCode: [{ required: true, message: '故障编码不能为空', trigger: 'blur' }],
  // failureName: [{ required: true, message: '故障名称不能为空', trigger: 'blur' }],
  deviceName: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  ifDeal: [{ required: true, message: '是否解决不能为空', trigger: 'blur' }],
  needHelp: [{ required: true, message: '是否协助不能为空', trigger: 'blur' }],
  // deviceId: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  //status: [{ 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()
  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 (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>
