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

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

import { drawerFormSchema } from './gainSetting-data';

import {
  addGainSetting,
  updateGainSetting,
  getGainSettingDetail,
} from '#/api/system/infoEntry/gainSetting/gainSetting';

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 getGainSettingDetail(id);
        await formApi.setValues(response);
      }
      // Update the form schema to make lossGainType read-only when editing
      const schema = formApi.getSchema();
      const lossGainTypeField = schema.find(field => field.fieldName === 'lossGainType');
      if (lossGainTypeField) {
        lossGainTypeField.componentProps = {
          ...lossGainTypeField.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();
      // 提交数据
      if (isUpdateRef.value) {
        await updateGainSetting(data);
      } else {
        await addGainSetting(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>
