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

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  networkAdd,
  networkInfo,
  networkUpdate,
} from '#/api/operations/network';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { drawerSchema } from './data';

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

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 120,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  // 在这里更改宽度
  class: 'w-[800px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { id } = drawerApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    if (isUpdate.value && id) {
      const record = await networkInfo(id);

      // 解析网络配置JSON
      if (record.networkConfig) {
        try {
          const configData = JSON.parse(record.networkConfig);
          // 将解析的配置数据合并到表单中
          const formData = { ...record, ...configData };
          await formApi.setValues(formData);
        } catch (error) {
          console.error('解析网络配置失败:', error);
          await formApi.setValues(record);
        }
      } else {
        await formApi.setValues(record);
      }
    } else {
      // 确保表单有初始值
      await formApi.setValues({
        networkType: 'MQTT_CLIENT',
      });
    }

    await markInitialized();
    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const formData = cloneDeep(await formApi.getValues());

    // 分离基础字段和配置字段
    const baseFields = new Set([
      'description',
      'enabled',
      'id',
      'name',
      'networkType',
    ]);
    const baseData: any = {};
    const configData: any = {};

    Object.keys(formData).forEach((key) => {
      if (baseFields.has(key)) {
        baseData[key] = formData[key];
      } else {
        configData[key] = formData[key];
      }
    });

    // 将配置字段转换为JSON字符串
    baseData.networkConfig = JSON.stringify(configData);

    await (isUpdate.value ? networkUpdate(baseData) : networkAdd(baseData));
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title">
    <BasicForm />
  </BasicDrawer>
</template>
