<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 {
  gatewayAdd,
  gatewayInfo,
  gatewayUpdate,
} from '#/api/operations/gateway';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import {
  drawerSchema,
  getNetworkOptions,
  getProtocolOptions,
  providerOptions,
  registerNetworkOptionsUpdate,
} 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: 80,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

// 更新抽屉表单的网络组件选项
async function updateDrawerNetworkOptions(provider: string) {
  try {
    if (provider && provider !== 'child-device') {
      const networkOptions = await getNetworkOptions(provider);
      console.log('网络组件选项:', provider);
      await formApi.updateSchema(
        drawerSchema().map((field: any) => {
          if (field.fieldName === 'channelId') {
            return {
              ...field,
              componentProps: {
                ...field.componentProps,
                options: networkOptions,
              },
            };
          }
          return field;
        }),
      );
      await formApi.setFieldValue('channelId', ''); // 清空选中值
      providerOptions.forEach((option) => {
        if (option.value === provider) {
          formApi.setFieldValue('channel', option.channel);
          formApi.setFieldValue('transport', option.transport);
        }
      });
    } else {
      // 如果是网关子设备接入，清空网络组件选项
      await formApi.updateSchema(
        drawerSchema().map((field: any) => {
          if (field.fieldName === 'channelId') {
            return {
              ...field,
              componentProps: {
                ...field.componentProps,
                options: [],
              },
            };
          }
          return field;
        }),
      );
      await formApi.setFieldValue('channelId', ''); // 清空选中值
      providerOptions.forEach((option) => {
        if (option.value === provider) {
          formApi.setFieldValue('channel', option.channel);
          formApi.setFieldValue('transport', option.transport);
        }
      });
    }
  } catch (error) {
    console.error('更新抽屉表单网络组件选项失败:', error);
  }
}

// 注册网络组件更新回调
registerNetworkOptionsUpdate(updateDrawerNetworkOptions);

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

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

    // 动态加载选项数据并更新schema
    try {
      const protocolOptions = await getProtocolOptions();

      const updatedSchema = drawerSchema().map((field: any) => {
        if (field.fieldName === 'protocol') {
          return {
            ...field,
            componentProps: {
              ...field.componentProps,
              options: protocolOptions,
            },
          };
        }
        return field;
      });

      await formApi.updateSchema(updatedSchema);
    } catch (error) {
      console.error('加载选项数据失败:', error);
    }

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

    if (isUpdate.value && id) {
      const record = await gatewayInfo(id);
      await formApi.setValues(record);

      // 如果是编辑模式，根据provider加载对应的网络组件选项
      if (record.provider && record.provider !== 'child-device') {
        await loadNetworkOptions(String(record.provider));
      }
    }
    await markInitialized();

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

// 根据接入方式加载网络组件选项
async function loadNetworkOptions(provider: string) {
  try {
    if (provider && provider !== 'child-device') {
      const networkOptions = await getNetworkOptions(provider);

      await formApi.updateSchema(
        drawerSchema().map((field: any) => {
          if (field.fieldName === 'channelId') {
            return {
              ...field,
              componentProps: {
                ...field.componentProps,
                options: networkOptions,
              },
            };
          }
          return field;
        }),
      );
    }
  } catch (error) {
    console.error('加载网络组件选项失败:', error);
  }
}

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? gatewayUpdate(data) : gatewayAdd(data));
    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>
