<template>
  <el-dialog title="退回" v-model="visible" width="800px" append-to-body @close="handleClose">
    <el-alert type="info" :closable="false" style="border-color: #6d28d9; background-color: #f5f3ff; color: #5b21b6; height: 35px;">
      <template #default>
        <i class="fa fa-sign-in mr-2" style="color: #5b21b6;"> 请选择退回类型，填写退回原因，完成工单退回。</i>
      </template>
    </el-alert>
    <h4 class="text-sm font-medium text-gray-800 mb-3"></h4>
    <el-form ref="returnFormRef" :model="formData" :rules="returnRules" label-width="120px" label-position="top">
      <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" v-if="formData.workOrderStatus == 'return' && formData.returnType">
          <el-form-item label="结单退回原因">
            <el-select v-model="formData.returnType" style="width: 100%" disabled>
              <el-option
                  v-for="dict in returnTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.workOrderStatus == 'return' && formData.returnReason">
          <el-form-item label="结单退回说明"><el-input v-model="formData.returnReason" disabled /></el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.workOrderStatus == 'to_finish'">
          <el-form-item label="退回原因" prop="returnType">
            <el-select
              v-model="formData.returnType"
              placeholder="请选择退回原因"
              style="width: 100%"
              :disabled="formData.workOrderStatus === 'return'"
              @change="handleReturnTypeChange"
            >
              <el-option
                v-for="dict in returnTypeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.workOrderStatus == 'assigned' || formData.workOrderStatus == 'return'">
          <el-form-item label="退回原因" prop="acceptReturnType">
            <el-select
                v-model="formData.acceptReturnType"
                placeholder="请选择退回原因"
                style="width: 100%"
                @change="handleReturnTypeChange"
            >
              <el-option
                  v-for="dict in acceptReturnTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="退回说明" prop="returnReason" v-if="formData.returnType == '0' && formData.workOrderStatus == 'to_finish'">
        <el-input
          v-model="formData.returnReason"
          type="textarea"
          placeholder="请输入退回说明"
          maxlength="100"
          show-word-limit
          :rows="3"
          :disabled="formData.workOrderStatus === 'return'"
        />
      </el-form-item>
      <el-form-item label="退回说明" prop="acceptReturnReason" v-if="formData.acceptReturnType == '0' && (formData.workOrderStatus == 'assigned' || formData.workOrderStatus == 'return')">
        <el-input
            v-model="formData.acceptReturnReason"
            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" :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: () => ({})
  },
  workOrderStatusOptions: {
    type: Array,
    default: () => ([])
  },
  returnTypeOptions: {
    type: Array,
    default: () => ([])
  },
  onSubmit: {
    type: Function,
    default: null
  },
  acceptReturnTypeOptions: {
    type: Array,
    default: () => ([])
  },
})

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

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

// 表单验证规则
const returnRules = ref({
  returnType: [
    { required: true, message: "请选择退回原因", trigger: "change" }
  ],
  returnReason: [
    { required: true, message: "请输入退回说明", trigger: "change" }
  ],
  acceptReturnType: [
    { required: true, message: "请选择退回原因", trigger: "change" }
  ],
  acceptReturnReason: [
    { 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 (returnFormRef.value) {
        returnFormRef.value.clearValidate()
      }
    })
  }
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
  returnFormRef.value.clearValidate()
  formData.value.returnType = undefined
  formData.value.returnReason = ''
  formData.value.acppetReturnType = undefined
  formData.value.acceptReturnReason = ''
}

// 取消操作
const handleCancel = () => {
  visible.value = false
  returnFormRef.value.clearValidate()
  formData.value.returnType = undefined
  formData.value.returnReason = ''
  formData.value.acppetReturnType = undefined
  formData.value.acceptReturnReason = ''
}

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

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

        // 调用父组件传入的提交函数
        if (props.onSubmit && typeof props.onSubmit === 'function') {
          if (formData.value.workOrderStatus == 'return' || formData.value.workOrderStatus == 'assigned') {
            formData.value.workOrderStatus = "accept_return";
          } else {
            formData.value.workOrderStatus = "return";
          }
          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 handleReturnTypeChange = (val) => {
  if (val != '0') { // 不为其他清空说明
    formData.value.returnReason = undefined
    formData.value.acceptReturnReason = undefined
  }
}

</script>

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