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

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

import { drawerFormSchema } from './gainSetting-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 mockDetail = {
          id,
          assessmentItem: `油品${id}`,
          score: 10 + id,
          description: `油品${id}的考核说明`,
        };
        await formApi.setValues(mockDetail);
      }
      // Update the form schema to make assessmentItem read-only when editing
      const schema = formApi.getSchema();
      const assessmentItemField = schema.find(field => field.fieldName === 'assessmentItem');
      if (assessmentItemField) {
        assessmentItemField.componentProps = {
          ...assessmentItemField.componentProps,
          disabled: isUpdate,
        };
      }
    } 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);
      // 模拟成功
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存考核项信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑考核项' : '新增考核项'">
    <Form />
  </Drawer>
</template>
