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

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

import { addCertificateSetting, getCertificateSettingDetail, updateCertificateSetting } from '#/api/system/infoEntry/certificateSetting/certificateSetting';

import { drawerFormSchema } from './certificateSetting-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 res = await getCertificateSettingDetail(id);
        const detailData = res?.data || res;
        await formApi.setValues(detailData);
      }
    } 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 (data.annualReviewToTask === 0) {
        data.taskStartMonth = '';
        data.taskEndMonth = '';
      }

      if (data.renewToTask === 0) {
        data.renewFrequency = '';
        data.renewAdvanceMonths = '';
      }

      await (isUpdateRef.value
        ? updateCertificateSetting(data)
        : addCertificateSetting(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>
