<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="500px" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #menu>
        <Spin :spinning="spinning">
          <!-- <BasicTable @register="registerTable">
            <template #metacolums="{ record }">
              <a-checkbox-group @change="(e) => columnsCheck(record, e)" :value="getCheckValue(record.id)">
                <Checkbox v-for="item in record.fieldMap" :value="item.propField" :key="item.propField">
                  {{ item.propName }}
                </Checkbox>
              </a-checkbox-group>
            </template>
          </BasicTable> -->

          <!-- <a-checkbox-group @change="(e) => columnsCheck(record, e)" :value="getCheckValue(record.id)">
            <Checkbox v-for="item in record.fieldMap" :value="item.propField" :key="item.propField">
              {{ item.propName }}
            </Checkbox>
          </a-checkbox-group> -->
        </Spin>
      </template>
    </BasicForm>
    <div class="selectPower">
      <p>选择权限</p>
      <a-tree checkable :tree-data="treeData2" v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys"
        v-model:checkedKeys="checkedKeys" :replaceFields="replaceFields">
        <template #title0010><span style="color: #1890ff">sss</span></template>
      </a-tree>
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, nextTick, unref, watch } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { powerSchema, KeysTypeEnum, RoleMenuDictEnum, menuColumns } from './role.data';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { BasicTree, TreeItem } from '/@/components/Tree';
import { useMessage } from '/@/hooks/web/useMessage';
const { t } = useI18n(); //加载国际化
// 加载菜单数据
import { getMenuList, menuList } from '/@/api/sys/menu';
import { useI18n } from '/@/hooks/web/useI18n';
import { MenuRecord } from '/@/api/sys/model/menuModel';
import { saveOrUpdateRoleInfoWithMenu } from '/@/api/system/system';
import { findDictItemByCode } from '/@/api/system/dict';
import { RoleEnum } from '/@/enums/roleEnum';
import { Spin, message } from 'ant-design-vue';
import { useUserStore } from '/@/store/modules/user';
import { session } from '/@/utils/Memory';
import { BasicTable, useTable } from '/@/components/Table';
import { onMounted } from 'vue';
import { getUserMenus, saveUserMenu } from '/@/api/sys/user';



type TreeData = MenuRecord & TreeItem;

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

    const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
      labelWidth: 100,
      schemas: powerSchema,
      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 userStore = useUserStore();
    const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      console.log('data', data);
      var arr = await getRoleMenusWay(data.record.EMPLOYEE_ID)

      // expandedKeys.value = arr;
      // selectedKeys.value = arr;
      checkedKeys.value = arr;

      resetFields();
      roleId.value = '';
      // 在打开弹窗时清除所有选择的菜单
      isUpdate.value = data.isUpdate;
      const roleType = data?.record?.roleType || userStore.getRoleList.at(0);

      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;
          nowRole = data.record;
          setFieldsValue(data.record);
        } else {
        }
      } catch (error) {
        throw error;
      } finally {
        spinning.value = false;
      }
    });





    const getTitle = '编辑用户权限';
    async function handleSubmit() {
      setDrawerProps({ confirmLoading: true });
      const values = await validate()
      saveUserMenu({
        menusId: menusIds.join(","),
        systemId: "1",
        userId: values.EMPLOYEE_ID,
      }).then(r => {
        closeDrawer();
        if (r) {
          setDrawerProps({ confirmLoading: false });
          message.success('权限添加成功！');
        }
      })

    }

    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 colcheckKeys = ref(new Map());
    const visibleFieldList = ref(new Map());
    function columnsCheck(record: Recordable, e: any) {
      debugger
      colcheckKeys.value.set(record.id, e);
      const list = record.fieldMap?.map((item) => {
        if (e.indexOf(item.propField) > -1) {
          return { ...item, isVisible: '1' };
        } else {
          return { ...item, isVisible: '0' };
        }
      });
      visibleFieldList.value.set(record.id, list);
    }

    function getCheckValue(id: string) {
      const list = visibleFieldList.value.get(id);
      if (list && list.length > 0) {
        const templist = list.filter((item) => item.isVisible == '1');

        return templist.map((item) => {
          return item.propField;
        });
      }
      return [];
    }

    const [registerTable, { setSelectedRowKeys, setTableData, getSelectRowKeys }] = useTable({
      title: '权限分配',
      api: getMenuList, //加载数据
      columns: menuColumns, //加载列
      isTreeTable: true,
      pagination: false,
      striped: false,
      showTableSetting: true,
      bordered: true,
      showIndexColumn: false,
      canResize: false,
      rowKey: (record) => record.id,
      rowSelection: {
        type: 'checkbox',
        // selectedRowKeys: roleMenus.value,
      },
    });


    const treeData2 = ref([]);
    const replaceFields = { title: 'name', key: 'id' }
    const expandedKeys = ref<string[]>([]);
    const selectedKeys = ref<string[]>([]);
    const checkedKeys = ref<string[]>([]);
    let menusIds = [];
    watch(expandedKeys, () => {
      menusIds = [...new Set(menusIds.concat(expandedKeys.value))]
    });
    watch(selectedKeys, () => {
      menusIds = [...new Set(menusIds.concat(selectedKeys.value))]
    });
    watch(checkedKeys, () => {
      menusIds = [...new Set([].concat(checkedKeys.value))]
    });

    function getRoleMenusWay(id) {
      return new Promise<void>((resolve, reject) => {
        getUserMenus({
          getMenuId: true,
          getUserConfigMenu: true,
          systemId: "1",
          useOneRole: true,
          userId: id,
        }).then(r => {
          resolve(r)
        }).catch(e => {
          reject(false)
        })
      })
    }

    onMounted(() => {
      // getRoleMenusWay()
      menuList().then(e => treeData2.value = e)
    })

    return {
      replaceFields,
      treeData2,
      expandedKeys,
      selectedKeys,
      checkedKeys,
      registerTable,
      getCheckValue,
      columnsCheck,
      spinning,
      registerDrawer,
      registerForm,
      getTitle,
      handleSubmit,
      treeData,
      roleMenus,
    };
  },
});
</script>

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

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

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

.selectPower {
  padding-left: 36px;
}
</style>
