<template>
  <el-dialog title="审批挂起申请" v-model="visible" width="800px" append-to-body @close="handleClose">
    <el-form ref="approveFormRef" :model="formData" :rules="approveRules" label-width="120px" label-position="top">
      <el-alert type="info" :closable="false" style="border-color: #a855f7; background-color: #f8f5ff; color: #6d28d9; height: 35px;">
        <template #default>
          <i class="fa fa-edit mr-2" style="color: #6d28d9;"> 请审批该工单的挂起申请，选择通过或驳回。</i>
        </template>
      </el-alert>      <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-select v-model="formData.workOrderStatus" style="width: 100%" disabled>
              <el-option
                v-for="dict in workOrderStatusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维保中心">
            <el-input v-model="formData.gxtCenter" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="场站">
            <el-input v-model="formData.pcsStationName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-input v-model="formData.brand" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.teamLeaderName">
          <el-form-item label="工作负责人">
            <el-input v-model="formData.teamLeaderName" 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="挂起原因">
            <el-select v-model="formData.suspendReason" style="width: 100%" disabled>
              <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="请输入说明"
              disabled
          />
        </el-form-item>
      </el-col>
      </el-row>
      <el-form-item label="审批意见" prop="rejectionReason">
        <el-input
          v-model="formData.rejectionReason"
          type="textarea"
          placeholder="请输入审批意见"
          maxlength="100"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('rejected')">驳 回</el-button>
        <el-button type="primary" @click="handleSubmit('approved')">通 过</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, getCurrentInstance, watch, onMounted } from 'vue'
// 获取当前实例
const { proxy } = getCurrentInstance()

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

// 初始化时设置默认审批状态为通过
onMounted(() => {
  if (props.data && props.data.approvalStatus) {
    formData.value.approvalStatus = props.data.approvalStatus
  } else {
    formData.value.approvalStatus = 'approved' // 默认为通过
  }
})

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

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

// 表单验证规则
const approveRules = ref({
  rejectionReason: [
    { required: true, message: "驳回时审批意见不能为空", trigger: "change" }
  ]
})

// 监听审批状态变化，动态调整验证规则
watch(() => formData.value.approvalStatus, (newVal) => {
  if (newVal === 'approved') {
    // 通过时不需要验证审批意见
    if (approveRules.value.rejectionReason && approveRules.value.rejectionReason[0]) {
      approveRules.value.rejectionReason[0].required = false
    }
  } else {
    // 驳回时需要验证审批意见
    if (approveRules.value.rejectionReason && approveRules.value.rejectionReason[0]) {
      approveRules.value.rejectionReason[0].required = true
    }
  }
}, { immediate: true }) // 立即执行一次以初始化验证规则

// 监听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 (approveFormRef.value) {
        approveFormRef.value.clearValidate()
      }
    })
  }
})

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

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

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

  // 设置审批状态
  formData.value.approvalStatus = approvalStatusValue

  await approveFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 驳回时必须填写审批意见
        if (approvalStatusValue === 'rejected' && !formData.value.rejectionReason) {
          proxy.$modal.msgError("驳回时审批意见不能为空")
          return
        }

        // 通过时清除审批意见
        if (approvalStatusValue === 'approved') {
          formData.value.rejectionReason = ''
        }
        // 调用父组件传入的提交函数
        if (props.onSubmit && typeof props.onSubmit === 'function') {
          // 清除时间字段避免冲突
          const submitData = { ...formData.value }
          submitData.createTime = null
          submitData.updateTime = null
          await props.onSubmit(submitData)
        } else {
          throw new Error("未提供提交方法")
        }

        proxy.$modal.msgSuccess(approvalStatusValue === 'approved' ? "审批通过成功" : "审批驳回成功")
        visible.value = false
        emit('success')
      } catch (error) {
        proxy.$modal.msgError("操作失败: " + (error.message || "未知错误"))
      }
    }
  })
}</script>

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