<template>
  <el-dialog title="停机" v-model="visible" width="800px" append-to-body @close="handleClose">
    <el-alert type="info" :closable="false" style="border-color: #0ea5e9; background-color: #ecf7ff; color: #0369a1; height: 35px;">
      <template #default>
        <i class="fa fa-refresh mr-2" style="color: #0369a1;"> 请填写停机相关信息，完成工单停机。</i>
      </template>
    </el-alert>
    <!-- 工单信息 -->
    <h3 class="text-sm font-medium text-gray-800 mb-3"></h3>
    <el-form ref="shutdownRef" :model="formData" :rules="restartRules" 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-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.realStartTime">
          <el-form-item label="开始时间"><el-input v-model="formData.realStartTime" disabled /> </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.infoEntry == '1'">
          <el-form-item label="MIS工单编码">
            <el-input v-model="formData.misNo" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.infoEntry == '2'">
          <el-form-item label="工作票编号">
            <el-input v-model="formData.workPermitNum" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="停机时间" prop="pauseTime">
            <el-date-picker
                v-model="formData.pauseTime"
                type="datetime"
                placeholder="请选择停机时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--      </div>-->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确认停机</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
  }
})

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

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

// 表单验证规则
const restartRules = ref({
  pauseTime: [
    { required: true, message: "请选择停机时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        debugger
        if (value && new Date(value) > new Date()) {
          callback(new Error('停机时间不能大于当前时间'));
        } else if(value && formData.value.realStartTime && new Date(value) < new Date(formData.value.realStartTime)) {
          callback(new Error('停机时间不能小于开始时间'));
        } else {
          callback();
        }
      },
      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 (shutdownRef.value) {
        shutdownRef.value.clearValidate()
      }
    })
  }
})

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

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

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

  debugger
  await shutdownRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用父组件传入的提交函数
        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("停机成功")
        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>
