<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu>
        <Spin :spinning="spinning">
          <BasicTree
            v-if="treeData.length"
            :treeData="treeData"
            :replaceFields="{ title: 'name', key: 'id' }"
            :checkedKeys="roleMenus"
            @check="handleCheckClick"
            checkable
            :toolbar="true"
            ref="treeRef"
            title="权限分配"
          />
        </Spin>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  const { t } = useI18n(); //加载国际化
  // 加载菜单数据
  import { getMenuList, getMenusIdsByRoleId } from '/@/api/sys/menu';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { MenuRecord } from '/@/api/sys/model/menuModel';
  import { saveOrUpdateRoleInfoWithMenu } from '/@/api/system/system';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { KeysTypeEnum, RoleMenuDictEnum } from '../../system/role/role.data';
  import { findDictItemByCode } from '/@/api/system/dict';
  import { Spin } from 'ant-design-vue';

  type TreeData = MenuRecord & TreeItem;

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree, Spin },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeData[]>([]);
      const roleMenus = ref<string[]>([]);
      const allCheckedKeys = ref<string[]>([]);
      const roleId = ref('');
      const treeRef = ref();
      const checked = ref<string[]>([]); //需要选中的节点
      const spinning = ref(false);

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const transformName = (data: TreeData[]) => {
        return data.map((item) => {
          item.name = t(item.name);
          if (item.children && item.children.length) {
            item.children = transformName(item.children as unknown as TreeData[]);
          }
          return item;
        });
      };

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        allCheckedKeys.value = [];
        resetFields();
        roleId.value = '';
        // 在打开弹窗时清除所有选择的菜单
        treeRef.value && treeRef.value?.setCheckedKeys([]);
        isUpdate.value = data.isUpdate;
        const roleType = data?.record?.roleType || RoleEnum.TENANT_ADMIN;
        try {
          spinning.value = true;
          // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告

          if (!unref(treeData).length) {
            // 获取全部的菜单
            const menuListModel = await getMenuList();
            treeData.value = transformName(menuListModel as unknown as TreeData[]);
          }

          const keys = await getPermissionByRole(roleType);
          const { keyType } = RoleMenuDictEnum[roleType];
          treeData.value = getPermissionTreeData(
            unref(treeData) as unknown as TreeData[],
            keys,
            keyType
          );

          // 更新
          if (unref(isUpdate)) {
            checked.value = [];
            roleId.value = data.record.id;

            //通过角色id去获取角色对应的菜单的ids
            allCheckedKeys.value = roleMenus.value = await getMenusIdsByRoleId(data.record.id);
            excludeHalfCheckedKeys(unref(treeData));

            await nextTick();
            treeRef.value.setCheckedKeys(roleMenus.value);
            setFieldsValue(data.record);
          } else {
          }
        } catch (error) {
          throw error;
        } finally {
          spinning.value = false;
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        setDrawerProps({ loading: true });
        setDrawerProps({ confirmLoading: true });
        const { createMessage } = useMessage();
        try {
          const values = await validate();
          const req = {
            id: roleId.value,
            name: values.name,
            remark: values.remark,
            status: values.status,
            roleType: RoleEnum.TENANT_ADMIN,
            menu: unref(allCheckedKeys) || [],
          };
          if (req.menu == undefined) return createMessage.error('请勾选权限菜单');
          const res = await saveOrUpdateRoleInfoWithMenu(req);
          if (res) {
            closeDrawer();
            emit('success');
            createMessage.success(`${unref(isUpdate) ? '编辑' : '新增'}成功`);
            setDrawerProps({ loading: false });
            setDrawerProps({ confirmLoading: false });
          }
        } finally {
          setTimeout(() => {
            setDrawerProps({ loading: false });
            setDrawerProps({ confirmLoading: false });
          }, 300);
        }
      }
      // Tree check事件
      const handleCheckClick = (checkedNodes, { halfCheckedKeys }) => {
        allCheckedKeys.value = [...checkedNodes, ...halfCheckedKeys];
      };

      const getPermissionByRole = async (roleType: RoleEnum) => {
        try {
          const { key } = RoleMenuDictEnum[roleType];
          const res = await findDictItemByCode({ dictCode: key });
          return res.map((item) => item.itemValue);
        } catch (error) {}
        return [];
      };

      const getPermissionTreeData = (
        data: MenuRecord[],
        permissionKeys: string[],
        keysType: KeysTypeEnum
      ) => {
        const setDisabled = (data: MenuRecord[], flag: boolean) => {
          return data.map((item) => {
            item.name = t(item.name);
            if (item.children && item.children.length) {
              item.children = setDisabled(item.children, flag);
            }
            return {
              ...item,
              disabled: flag,
              icon: item.meta.icon,
            } as TreeData;
          });
        };

        const permissionCompare = (
          data: MenuRecord[],
          permissionKeys: string[],
          keysType: KeysTypeEnum
        ) => {
          return data.map((item) => {
            item.name = t(item.name);
            const findFlag = permissionKeys.includes(item.permission);
            if (findFlag) item.isDictCompareDisabled = true;
            const disabledFlag = keysType === KeysTypeEnum.DISABLED ? findFlag : !findFlag;
            item.disabled = disabledFlag;

            if (item.isDictCompareDisabled && item.children && item.children.length) {
              setDisabled(item.children, disabledFlag);
            } else {
              if (item.children && item.children.length) {
                item.children = permissionCompare(item.children, permissionKeys, keysType);
                item.disabled = item.children.every((temp) => temp.disabled);
              }
            }
            return {
              ...item,
              icon: item.meta.icon,
            } as TreeData;
          });
        };

        const result = permissionCompare(data, permissionKeys, keysType).map((item) => {
          if (item.children && item.children.length) {
            const rootDisabledFlag = item.children.every((temp) => temp.disabled);
            item.disabled = rootDisabledFlag;
          }
          return item;
        });

        return result;
      };

      const excludeHalfCheckedKeys = (treeData: MenuRecord[]) => {
        const needExcludeKeys: string[] = [];
        const query = (data: MenuRecord[]) => {
          data.forEach((item) => {
            item.checked = roleMenus.value.includes(item.id);
            if (item.children && item.children.length) {
              query(item.children);
              item.checked = item.children.every((item) => item.checked);
            }
            if (!item.checked) {
              needExcludeKeys.push(item.id);
            }
          });
        };
        query(treeData);
        roleMenus.value = unref(roleMenus).filter((key) => !needExcludeKeys.includes(key));
        return needExcludeKeys;
      };

      return {
        spinning,
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        roleMenus,
        treeRef,
        handleCheckClick,
      };
    },
  });
</script>

<style scoped lang="less">
  :deep(.vben-basic-tree) {
    width: 100% !important;
  }

  :deep(.is-unflod) {
    display: none !important;
  }

  :deep(.is-flod) {
    display: none !important;
  }
</style>
