<script setup lang="ts">
import { ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { getEmployeePerformanceDetail, updateEmployeePerformance } from '#/api/archive/personnelTraining/personnelTraining';
import { drawerFormSchema } from './employeePerfor-data';

const emit = defineEmits<{
  reload: [];
}>();

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

const isUpdateRef = ref<boolean>(false);

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { id, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate && id) {
        // 获取员工绩效详情
        const response = await getEmployeePerformanceDetail({ id });
        if (response) {
          await formApi.setValues(response);
        }
      }
    } catch (error) {
      console.error('获取员工绩效详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();
      console.log(data);
      
      // 保存员工绩效信息
      await updateEmployeePerformance(data);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存员工绩效信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

  onClosed() {
    formApi.resetForm();
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑员工绩效' : '新增员工绩效'">
    <Form />
  </Drawer>
</template>

