<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible" 
    width="700px"
    :close-on-click-modal="false"
    draggable>
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px" 
      v-loading="loading">
      <el-form-item label="部门" prop="deptId">
        <org-selector 
          v-model:orgList="deptList" 
          type="dept" 
          :multiple="false"
          @update:orgList="handleDeptChange" />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input 
          v-model="form.deptName" 
          placeholder="请选择部门后自动填充" 
          readonly />
      </el-form-item>
      <el-form-item label="分管负责人" prop="userId">
        <org-selector 
          v-model:orgList="userList" 
          type="user" 
          :multiple="false"
          @update:orgList="handleUserChange" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input 
          v-model="form.name" 
          placeholder="请选择用户后自动填充" 
          readonly />
      </el-form-item>
      <el-form-item label="用户工号" prop="username">
        <el-input 
          v-model="form.username" 
          placeholder="请选择用户后自动填充" 
          readonly />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注" 
          clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="PurchasingBusinessDeptForm">
import { reactive, ref, nextTick } from 'vue'
import { getObj, addObj, putObj } from '/@/api/purchase/purchasingBusinessDept';
import { useMessage } from '/@/hooks/message';
import orgSelector from '/@/components/OrgSelector/index.vue';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const deptList = ref<any[]>([]);
const userList = ref<any[]>([]);
const dataForm = reactive({
  id: '',
  deptId: '',
  deptName: '',
  userId: '',
  username: '',
  name: '',
  remark: '',
});
const visible = ref(false);
const loading = ref(false);

const dataRules = ref({
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  userId: [
    { required: true, message: '请选择分管负责人', trigger: 'change' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '用户工号不能为空', trigger: 'blur' }
  ],
});

// 处理部门选择变化
const handleDeptChange = (list: any[]) => {
  if (list && list.length > 0) {
    const dept = list[0];
    dataForm.deptId = dept.deptId || dept.id || '';
    dataForm.deptName = dept.name || dept.deptName || '';
  } else {
    dataForm.deptId = '';
    dataForm.deptName = '';
  }
};

// 处理用户选择变化
const handleUserChange = (list: any[]) => {
  if (list && list.length > 0) {
    const user = list[0];
    dataForm.userId = user.userId || user.id || '';
    dataForm.username = user.username || user.userName || '';
    dataForm.name = user.name || user.realName || '';
  } else {
    dataForm.userId = '';
    dataForm.username = '';
    dataForm.name = '';
  }
};

// 打开弹窗
const openDialog = async (id?: string) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.deptId = '';
  dataForm.deptName = '';
  dataForm.userId = '';
  dataForm.username = '';
  dataForm.name = '';
  dataForm.remark = '';
  deptList.value = [];
  userList.value = [];

  nextTick(() => {
    dataFormRef.value?.resetFields();
    if (id) {
      // 编辑时，先获取详情数据
      loading.value = true;
      getObj({ id }).then((res: any) => {
        if (res.data && res.data.length > 0) {
          const data = res.data[0];
          Object.assign(dataForm, {
            id: data.id || '',
            deptId: data.deptId || '',
            deptName: data.deptName || '',
            userId: data.userId || '',
            username: data.username || '',
            name: data.name || '',
            remark: data.remark || '',
          });
          // 设置部门列表用于回显
          if (data.deptId) {
            deptList.value = [{
              deptId: data.deptId,
              name: data.deptName,
              id: data.deptId,
              type: 'dept',
            }];
          }
          // 设置用户列表用于回显
          if (data.userId) {
            userList.value = [{
              userId: data.userId,
              username: data.username,
              name: data.name,
              id: data.userId,
              userName: data.username,
              realName: data.name,
              type: 'user',
            }];
          }
        }
        loading.value = false;
      }).catch((err: any) => {
        useMessage().error(err.msg || '获取详情失败');
        loading.value = false;
      });
    }
  });
};

// 提交
const onSubmit = async () => {
  // 立即设置 loading，防止重复点击
  if (loading.value) return;
  loading.value = true;

  try {
    const valid = await dataFormRef.value.validate().catch(() => {});
    if (!valid) {
      loading.value = false;
      return false;
    }

    if (dataForm.id) {
      await putObj(dataForm);
      useMessage().success('编辑成功');
    } else {
      await addObj(dataForm);
      useMessage().success('新增成功');
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || (dataForm.id ? '编辑失败' : '新增失败'));
  } finally {
    loading.value = false;
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped>
</style> 