<script setup lang="ts">
import { ref } from 'vue';
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import {
  addDistrictInfo,
  getDistrictInfoDetail,
  updateDistrictInfo,
} from '#/api/system/infoEntry/districtInfo/districtInfo';

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

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

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

const isUpdateRef = ref<boolean>(false);
const confirmLoading = 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 getDistrictInfoDetail(id);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;
        await formApi.setValues(detailData);
      }
    } catch (error) {
      console.error('获取片区详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      confirmLoading.value = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();
      await (isUpdateRef.value ? updateDistrictInfo(data) : addDistrictInfo(data));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存片区信息失败:', error);
    } finally {
      confirmLoading.value = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑片区' : '新增片区'">
    <Form />
  </Drawer>
</template>