<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 800px">
    <!-- 表单弹窗 -->

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="24" :xs="24" :sm="24" :md="12">
          <el-form-item label="事件时间" prop="actualTime">
            <el-date-picker
              v-model="formData.actualTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="x"
              placeholder="选择事件发生时间"
              style="width: 100%"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24" :xs="24" :sm="24" :md="12">
          <el-form-item label="事件级别" prop="accidentGrade">
            <el-input
              v-model="formData.accidentGrade"
              placeholder="请输入事件级别"
              clearable
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24" :xs="24" :sm="24" :md="12">
          <el-form-item label="事件类型" prop="accidentType">
            <el-input
              v-model="formData.accidentType"
              placeholder="请选择事件类型"
              clearable
              style="width: 100%"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24" :xs="24" :sm="24" :md="12">
          <el-form-item label="事件地址" prop="accidentAddress">
            <el-input
              v-model="formData.accidentAddress"
              placeholder="请输入事件地址"
              clearable
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24" :xs="24" :sm="24" :md="12">
          <el-form-item label="现场负责人" prop="dutyPerson">
            <el-input
              v-model="formData.dutyPerson"
              placeholder="请输入现场负责人姓名"
              clearable
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="事件损失情况" prop="lossSituation">
            <el-input
              v-model="formData.lossSituation"
              placeholder="请输入事件损失情况"
              clearable
              type="textarea"
              :rows="2"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="现场采取措施" prop="emergencyMeasure">
            <el-input
              v-model="formData.emergencyMeasure"
              type="textarea"
              :rows="2"
              placeholder="请输入现场采取的应急措施"
              maxlength="500"
              show-word-limit
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="事件简要经过" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="2"
              placeholder="请输入事件详细经过"
              maxlength="1000"
              show-word-limit
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="附件/现场图片" prop="pic">
            <UploadImage v-model="formData.pic" width="260px" :disabled="disabled" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="500"
              show-word-limit
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading" color="#626aef">
          确 定
        </el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { IotFailureApi } from '@/api/pms/qhse/index'
import UploadImage from '@/components/UploadFile/src/UploadImg.vue'

// Data
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref()
const disabled = ref(false)
const { t } = useI18n() // 国际化

// 表单数据
const formData = ref({
  actualTime: null, // 使用时间戳格式
  accidentGrade: '',
  accidentType: '',
  accidentAddress: '',

  dutyPerson: '',
  lossSituation: '',
  emergencyMeasure: '',
  description: '',
  pic: '',
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  actualTime: [{ required: true, message: '请选择事件时间', trigger: 'change' }],
  accidentGrade: [{ required: true, message: '请输入事件级别', trigger: 'blur' }],
  accidentType: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  accidentAddress: [{ required: true, message: '请输入事件地址', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
  deptName: [{ required: true, message: '请输入队伍名称', trigger: 'blur' }],
  dutyPerson: [{ required: true, message: '请输入现场负责人', trigger: 'blur' }]
})

const open = async (type, id, disable) => {
  disabled.value = disable
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  reset()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await IotFailureApi.getFailure(id)
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const reset = () => {
  formData.value = {
    id: undefined,
    actualTime: null,
    accidentGrade: '',
    accidentType: '',
    accidentAddress: '',
    // deptId: null,
    // deptName: '',
    dutyPerson: '',
    lossSituation: '',
    emergencyMeasure: '',
    description: '',
    pic: '',
    remark: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await ElMessageBox.confirm(
          '请确认事故事件信息内容，提交后会发送消息至公司总经理及集团领导。',
          '确认提交',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        submitLoading.value = true
        // 在提交前确保时间是时间戳格式
        const submitData = { ...formData.value }

        if (formType.value === 'create' && formData.value.id) {
          // 更新API调用
          submitData.id = formData.value.id
          await IotFailureApi.updateFailure(submitData)
          ElMessage.success('更新成功')
        } else {
          // 创建API调用
          await IotFailureApi.createFailure(submitData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        emit('success')
      } catch (error) {
        if (error === 'cancel' || error === 'close') {
          return
        }
        ElMessage.error(error.message || '操作失败')
      } finally {
        submitLoading.value = false
      }
    } else {
      ElMessage.error('请填写必填项')
    }
  })
}
</script>
