<template>
  <el-dialog
    :title="formType === 'create' ? '新增工序' : '编辑工序'"
    v-model="visible"
    width="500px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" v-loading="formLoading">
      <el-form-item label="工序编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入工序编码" />
      </el-form-item>
      <el-form-item label="工序名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入工序名称" />
      </el-form-item>
      <el-form-item label="工序描述" prop="description">
        <el-input v-model="form.description" placeholder="请输入工序描述" />
      </el-form-item>
      <el-form-item label="工序类型" prop="type">
        <el-input v-model.number="form.type" placeholder="请输入工序类型（数字）" />
      </el-form-item>
      <el-form-item label="标准工时(分钟)" prop="standardTime">
        <el-input v-model.number="form.standardTime" placeholder="请输入标准工时" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  YVHcreateProcessOperation,
  YVHupdateProcessOperation,
  YVHgetProcessOperation
} from '@/api/mes/production/process-operation'

// 生成工序编码
const generateOperationCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, '0')
  return `OP${year}${month}${day}${random}`
}

const emits = defineEmits(['success'])

const visible = ref(false)
const loading = ref(false)
const formLoading = ref(false) // 表单加载状态
const formType = ref<'create' | 'update'>('create')
const form = reactive<any>({})
const formRef = ref()

const rules = {
  code: [{ required: true, message: '请输入工序编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const open = async (type: 'create' | 'update', id?: number) => {
  formType.value = type
  visible.value = true
  formLoading.value = true // 开始加载，禁用表单

  try {
    // 重置表单
    Object.assign(form, {
      code: type === 'create' ? generateOperationCode() : '',
      name: '',
      description: '',
      type: 1, // 默认工序类型为1
      standardTime: 30, // 默认标准工时30分钟
      status: 1,
      remark: ''
    })

    if (type === 'update' && id) {
      const res = await YVHgetProcessOperation(id)
      // 直接使用接口返回的数据，不进行解构
      Object.assign(form, res)
    }
  } catch (error) {
    console.error('初始化表单失败:', error)
    ElMessage.error('加载数据失败，请重试')
    visible.value = false
  } finally {
    formLoading.value = false // 加载完成，启用表单
  }
}

const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      if (formType.value === 'create') {
        await YVHcreateProcessOperation(form)
        ElMessage.success('新增成功')
      } else {
        await YVHupdateProcessOperation(form)
        ElMessage.success('修改成功')
      }
      visible.value = false
      emits('success')
    } finally {
      loading.value = false
    }
  })
}

const handleClose = () => {
  formRef.value?.resetFields()
}

// 对外暴露 open 方法
defineExpose({ open })
</script>
