<template>
  <el-dialog title="申请挂起工单" v-model="visible" width="800px" append-to-body @close="handleClose">
    <el-form ref="suspendFormRef" :model="formData" :rules="suspendRules" label-width="120px" label-position="top">
      <el-alert type="warning" :closable="false" title="请选择挂起原因，提交后需等待班长审批。" show-icon />
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单编码">
            <el-input v-model="formData.workOrderProjectNo" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风机编号">
            <el-input v-model="formData.pcsDeviceName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障代码"><el-input v-model="formData.faultCode" disabled /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障条文"><el-input v-model="formData.faultBarcode" disabled /></el-form-item>
        </el-col>
        <el-col :span="24" v-if="formData.faultDesc">
          <el-form-item label="故障描述">
            <el-input
                v-model="formData.faultDesc"
                type="textarea"
                :rows="3"
                disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="挂起原因" prop="suspendReason">
            <el-select v-model="formData.suspendReason" placeholder="请选择挂起原因" style="width: 100%" @change="handleSuspendReasonChange">
              <el-option
                v-for="dict in suspendReasonOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="formData.suspendReason == '4'">
          <el-form-item label="说明" prop="suspendExplain">
            <el-input
                v-model="formData.suspendExplain"
                type="textarea"
                :rows="3"
                placeholder="请输入说明"
                maxlength="500"
                show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交申请</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, getCurrentInstance, watch } from 'vue'

// 获取当前实例
const { proxy } = getCurrentInstance()

// 定义属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  },
  suspendReasonOptions: {
    type: Array,
    default: () => ([])
  },
  onSubmit: {
    type: Function,
    default: null
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'success'])

// 响应式数据
const visible = ref(false)
const formData = ref({})
const suspendFormRef = ref()
const submitLoading = ref(false)

// 表单验证规则
const suspendRules = ref({
  suspendReason: [
    { required: true, message: "请选择挂起原因", trigger: "change" }
  ],
  suspendExplain: [
    { required: true, message: "说明不能为空", trigger: "change" }
  ]
})

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    // 初始化表单数据
    formData.value = { ...props.data }
  }
})

// 监听props.data变化
watch(() => props.data, (newData) => {
  if (visible.value) {
    // 只有在对话框打开时才更新数据
    formData.value = { ...newData }
  }
}, { deep: true })

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (val) {
    // 打开对话框后重置表单验证错误
    proxy.$nextTick(() => {
      if (suspendFormRef.value) {
        suspendFormRef.value.clearValidate()
      }
    })
  }
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 取消操作
const handleCancel = () => {
  visible.value = false
}

// 提交操作
const handleSubmit = async () => {
  if (!suspendFormRef.value) return

  await suspendFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        submitLoading.value = true

        // 调用父组件传入的提交函数
        if (props.onSubmit && typeof props.onSubmit === 'function') {
          formData.value.createTime = null
          formData.value.updateTime = null
          await props.onSubmit(formData.value)
        } else {
          throw new Error("未提供提交方法")
        }

        proxy.$modal.msgSuccess("挂起申请提交成功")
        visible.value = false
        emit('success')
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + (error.message || "未知错误"))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 挂起原因变化处理
const handleSuspendReasonChange = (val) => {
  // 不为其他清空说明
  if (val != '4') {
    formData.value.suspendExplain = undefined
  }
}
</script>

<style scoped>
/* 表单中的列间距调整 */
:deep(.el-col) {
  padding-left: 5px;
  padding-right: 5px;
}
</style>
