<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="processId">
        <el-select
          v-model="form.processId"
          placeholder="请选择绑定工序"
          filterable
          clearable
          class="!w-full"
        >
          <el-option
            v-for="item in processList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报工人" prop="reporterId">
        <el-select
          v-model="form.reporterId"
          placeholder="请选择报工人"
          filterable
          clearable
          class="!w-full"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </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" type="textarea" placeholder="请输入备注" :rows="3" />
      </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 {
  YVHcreateWorkstationBinding,
  YVHupdateWorkstationBinding,
  YVHgetWorkstationBinding
} from '@/api/mes/production/workstation'
import { YVHgetProcessOperationList } from '@/api/mes/production/process-operation'
import * as UserApi from '@/api/system/user'

// 生成工位编号
const generateWorkstationCode = () => {
  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 `WS${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 processList = ref<any[]>([])
const userList = ref<any[]>([])

const rules = {
  code: [{ required: true, message: '请输入工位编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入工位名称', trigger: 'blur' }],
  processId: [{ required: true, message: '请选择绑定工序', trigger: 'change' }],
  reporterId: [{ required: true, message: '请选择报工人', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取工序列表
const getProcessList = async () => {
  try {
    processList.value = await YVHgetProcessOperationList()
  } catch (error) {
    console.error('获取工序列表失败:', error)
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await UserApi.getSimpleUserList()
    userList.value = res
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const open = async (type: 'create' | 'update', id?: number) => {
  formType.value = type
  visible.value = true
  formLoading.value = true

  try {
    // 获取下拉列表数据
    await Promise.all([getProcessList(), getUserList()])

    // 重置表单
    Object.assign(form, {
      id: undefined,
      code: type === 'create' ? generateWorkstationCode() : '',
      name: '',
      processId: undefined,
      reporterId: undefined,
      status: 1,
      remark: ''
    })

    if (type === 'update' && id) {
      const res = await YVHgetWorkstationBinding(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 YVHcreateWorkstationBinding(form)
        ElMessage.success('新增成功')
      } else {
        await YVHupdateWorkstationBinding(form)
        ElMessage.success('修改成功')
      }
      visible.value = false
      emits('success')
    } finally {
      loading.value = false
    }
  })
}

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

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