<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="userId">
        <el-select
          v-model="form.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="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="deptId">
        <el-select
          v-model="form.deptId"
          placeholder="请选择部门"
          filterable
          clearable
          style="width: 100%"
          @change="handleDeptChange"
        >
          <el-option
            v-for="item in deptOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </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="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="PurchasingPurchaseManagerForm">
import { reactive, ref, nextTick } from 'vue'
import { getObj, addObj, putObj } from '/@/api/purchase/purchasingPurchaseManager';
import { searchTeachers, getSecondDeptList } from '/@/api/purchase/purchasingrequisition';
import { useMessage } from '/@/hooks/message';

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

const dataFormRef = ref();
const deptOptions = ref<any[]>([]);
const userOptions = ref<any[]>([]);
const userLoading = ref(false);
const form = reactive({
  id: '',
  deptId: '',
  deptName: '',
  userId: '',
  username: '',
  name: '',
  remark: '',
});
const visible = ref(false);
const loading = ref(false);

const dataRules = ref({
  userId: [
    { required: true, message: '请选择人员', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请先选择人员', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请先选择人员', trigger: 'blur' }
  ],
});

const loadDeptOptions = async () => {
  try {
    const res = await getSecondDeptList();
    deptOptions.value = res?.data || [];
  } catch (_) {
    deptOptions.value = [];
  }
};

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 handleDeptChange = (deptId: string) => {
  if (!deptId) {
    form.deptId = '';
    form.deptName = '';
    return;
  }
  const selected = deptOptions.value.find((item: any) => item.deptId === deptId);
  if (selected) {
    form.deptId = selected.deptId;
    form.deptName = selected.deptName;
  }
};

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

const openDialog = async (id?: string) => {
  visible.value = true;
  form.id = '';
  form.deptId = '';
  form.deptName = '';
  form.userId = '';
  form.username = '';
  form.name = '';
  form.remark = '';
  userOptions.value = [];
  
  await loadDeptOptions();

  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(form, {
            id: data.id || '',
            deptId: data.deptId || '',
            deptName: data.deptName || '',
            userId: data.userId || '',
            username: data.username || '',
            name: data.name || '',
            remark: data.remark || '',
          });
          if (form.userId) {
            userOptions.value = [{ teacherNo: form.userId, realName: form.name, name: form.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 dataFormRef.value.validate().catch(() => {});
    if (!valid) {
      loading.value = false;
      return false;
    }

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

defineExpose({
  openDialog,
});
</script>

<style scoped>
</style> 