<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysMenuApi } from '#/api/auth/menu';
import type { TenantPackageApi } from '#/api/system/sysTenantPackage';

import { computed, nextTick, ref } from 'vue';

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

import { omit } from 'lodash-es';

import { useVbenForm } from '#/adapter/form';
import { apiMenuTree } from '#/api/auth/menu';
import { apiAdd, apiDetail, apiUpdate } from '#/api/system/sysTenantPackage';
import { MenuSelectTable } from '#/components/tree';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

type MenuOption = SysMenuApi.MenuOption;

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<TenantPackageApi.TenantPackage>();

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'packageName',
    label: '套餐名称',
    rules: 'required',
  },
  {
    component: 'menuIds',
    defaultValue: [],
    fieldName: 'menuIds',
    label: '关联菜单ID',
    // rules: 'required',
  },
  // {
  //   component: 'RadioGroup',
  //   componentProps: {
  //     buttonStyle: 'solid',
  //     optionType: 'button',
  //     options: getDictOptions('sys_common_status', true),
  //   },
  //   defaultValue: 1,
  //   fieldName: 'status',
  //   label: '状态',
  //   rules: 'required',
  // },
  {
    component: 'Textarea',
    fieldName: 'remark',
    label: '备注',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

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

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const { id } = drawerApi.getData() as { id: number };
    let checkedKeys: number[] = [];
    if (id) {
      const data = await apiDetail(id);
      formData.value = omit(data, ['menuIds']);
      await formApi.setValues(formData.value);
      checkedKeys = data.menuIds ? data.menuIds.split(',').map(Number) : [];
    } else {
      formApi.resetForm();
    }
    await setupMenuTree(checkedKeys);
    await markInitialized();
  },
});
const menuSelectRef = ref<InstanceType<typeof MenuSelectTable>>();
const menuTree = ref<MenuOption[]>([]);

async function setupMenuTree(menuIds: number[]) {
  // if (id) {
  //   const resp = await roleMenuTreeSelect(id);
  //   // const menus = resp.menus;
  //   // 设置菜单信息
  //   menuTree.value = resp.menus;
  //   // keys依赖于menu 需要先加载menu
  //   await nextTick();
  //   await formApi.setFieldValue('menuIds', resp.checkedKeys);
  // } else {
  const resp = await apiMenuTree();
  // 设置菜单信息
  menuTree.value = resp;
  // keys依赖于menu 需要先加载menu
  await nextTick();
  await formApi.setFieldValue('menuIds', menuIds);
  // }
}
async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const menuIds = menuSelectRef.value?.getCheckedKeys?.() ?? [];
    const data = cloneDeep(await formApi.getValues());
    data.menuIds = menuIds;
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改租户套餐' : '新增租户套餐',
);
/**
 * 通过回调更新 无法通过v-model
 * @param value 菜单选择是否严格模式
 */
function handleMenuCheckStrictlyChange(value: boolean) {
  formApi.setFieldValue('menuCheckStrictly', value);
}
</script>
<template>
  <Drawer class="w-[800px]" :title="getDrawerTitle">
    <BasicForm class="mx-4">
      <template #menuIds="slotProps">
        <div class="h-[600px] w-full">
          <!-- association为readonly 不能通过v-model绑定 -->
          <MenuSelectTable
            ref="menuSelectRef"
            :checked-keys="slotProps.value"
            :association="formApi.form.values.menuCheckStrictly"
            :menus="menuTree"
            @update:association="handleMenuCheckStrictlyChange"
          />
        </div>
      </template>
    </BasicForm>
  </Drawer>
</template>
