<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">
        <el-select
          v-model="dataForm.userId"
          placeholder="请输入姓名或工号搜索"
          filterable
          remote
          clearable
          reserve-keyword
          :remote-method="searchUser"
          :loading="userLoading"
          style="width: 100%"
          @change="handleUserChange"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.teacherNo"
            :label="(item.commonDeptName ? item.commonDeptName + ' - ' : '') + (item.realName || item.name) + ' (' + item.teacherNo + ')'"
            :value="item.teacherNo"
          >
            <span>{{ item.commonDeptName ? item.commonDeptName + ' - ' : '' }}{{ item.realName || item.name }}</span>
            <span style="color: #999; font-size: 12px; margin-left: 8px;">{{ item.teacherNo }}</span>
          </el-option>
        </el-select>
      </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/purchase/purchasingschoolleader';
import { searchTeachers } from '/@/api/purchase/purchasingrequisition';
import { useMessage } from '/@/hooks/message';

const emit = defineEmits(['refresh']);

const formRef = ref();
const userOptions = ref<any[]>([]);
const userLoading = ref(false);
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 searchUser = async (query: string) => {
  if (!query) {
    userOptions.value = [];
    return;
  }
  userLoading.value = true;
  try {
    const res = await searchTeachers(query);
    userOptions.value = res?.data || [];
  } catch (_) {
    userOptions.value = [];
  } finally {
    userLoading.value = false;
  }
};

const handleUserChange = (teacherNo: string) => {
  if (!teacherNo) {
    dataForm.userId = '';
    dataForm.username = '';
    dataForm.name = '';
    return;
  }
  const selected = userOptions.value.find((item: any) => item.teacherNo === teacherNo);
  if (selected) {
    dataForm.userId = selected.teacherNo;
    dataForm.username = selected.teacherNo;
    dataForm.name = selected.realName || selected.name;
  }
};

const openDialog = async (type: string, rowData?: any) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.userId = '';
  dataForm.username = '';
  dataForm.name = '';
  dataForm.remark = '';
  userOptions.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 (dataForm.userId) {
            userOptions.value = [{ teacherNo: dataForm.userId, realName: dataForm.name, name: dataForm.name }];
          }
        }
        loading.value = false;
      }).catch((err: any) => {
        useMessage().error(err.msg || '获取详情失败');
        loading.value = false;
      });
    }
  });
};

const onSubmit = async () => {
  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> 