<template>
  <el-dialog 
    :title="dataForm.id ? '编辑' : '新增'" 
    v-model="visible" 
    width="600px"
    :close-on-click-modal="false"
    draggable>
    <el-form 
      ref="formRef" 
      :model="dataForm" 
      :rules="dataRules" 
      label-width="100px" 
      v-loading="loading">
      <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="dataForm.name" 
          placeholder="请选择用户后自动填充" 
          readonly />
      </el-form-item>
      <el-form-item label="用户工号" prop="username">
        <el-input 
          v-model="dataForm.username" 
          placeholder="请选择用户后自动填充" 
          readonly />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="dataForm.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="PurchasingSchoolLeaderForm">
import { reactive, ref, nextTick } from 'vue'
import { getObj, addObj, editObj } from '/@/api/finance/purchasingschoolleader';
import { useMessage } from '/@/hooks/message';
import orgSelector from '/@/components/OrgSelector/index.vue';

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

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

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

// 处理用户选择变化
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 (type: string, rowData?: any) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.userId = '';
  dataForm.username = '';
  dataForm.name = '';
  dataForm.remark = '';
  userList.value = [];

  nextTick(() => {
    formRef.value?.resetFields();
    if (type === 'edit' && rowData?.id) {
      // 编辑时，先获取详情数据
      loading.value = true;
      getObj(rowData.id).then((res: any) => {
        if (res.data) {
          Object.assign(dataForm, {
            id: res.data.id || '',
            userId: res.data.userId || '',
            username: res.data.username || '',
            name: res.data.name || '',
            remark: res.data.remark || '',
          });
          // 设置用户列表用于回显
          if (res.data.userId) {
            userList.value = [{
              userId: res.data.userId,
              username: res.data.username,
              name: res.data.name,
              id: res.data.userId,
              userName: res.data.username,
              realName: res.data.name,
            }];
          }
        }
        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 formRef.value.validate().catch(() => {});
    if (!valid) {
      loading.value = false;
      return false;
    }

    if (dataForm.id) {
      await editObj(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>

