<template>
  <div class="platform-authFun-btns">
    <h-b-button-group
      id="AuthIndex-buttonGroup"
      v-bind="menuProps"
      ref="menuRef"
      :checkPermission="false"
      @click="authFunClick"
    />
  </div>
  <div class="auth-fun-tree">
    <h-b-tree
      ref="demoHbtreeRef"
      id="AuthIndex-selectTree"
      v-bind="props"
      v-model:checkedKeys="props.checkedKeys"
      :checkable="state.checkable"
      :check-strictly="state.checkStrictly"
      :draggable="state.draggable"
      :show-header="state.showHeader"
      :show-search="state.showSearch"
      :show-tool-bar="state.showToolBar"
      :show-line="state.showLine"
      :selectable="state.selectable"
      :useUniqueKey="true"
      :fieldNames="{ key: 'key' }"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, inject, watch, ref, computed } from 'vue';
import { useTree, useButtonGroup } from '@crami/bui-platform';
import { getInfo, ICP_CONFIG } from '@remote/icpx-platform/utils';
/* import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { cloneDeep } from 'lodash-es';
import { saveMenu } from '@/api/platform/auth/index';
import { message } from '@crami/ui';
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'AuthPage',
  setup() {
    const { t } = useI18n();
    const selectData: any = inject('selectData');
    const radioType: any = ref('');

    const commonParams = computed(() => {
      return getInfo(ICP_CONFIG);
    });

    // const paraList = {
    //   loadAllStructure: false,
    //   lang: commonParams.value?.lang,
    //   connect: commonParams.value?.connect,
    //   companyId: commonParams.value?.companyId,
    // };
    // console.log('paraList', paraList);

    const [demoHbtreeRef, props, methods] = useTree({
      // immediate: false,
      treeDataApi: {
        url: '/api/menupermission/menuPer/getSelectedMenus',
        method: 'post',
        params: {
          // paraList: JSON.stringify(paraList),
          lang: commonParams.value?.lang,
          connect: commonParams.value?.connect,
          companyId: commonParams.value?.companyId,
          productLine: selectData?.project,
          objectId: selectData?.objectId,
          appId: selectData?.appId,
          permissionType: selectData?.permissionType,
          appName: selectData?.appName,
          userType: commonParams.value?.user_type,
          projectCode: commonParams.value?.projectCode,
          timeZone: commonParams.value?.TIME_ZONE,
        },
      },
      beforeRequest: params => {
        return {
          ...params,
          objectId: selectData?.objectId,
          appId: selectData?.appId,
          permissionType: selectData?.permissionType,
          appName: selectData?.appName,
          productLine: selectData?.project,
        };
      },
      afterRequest: (data: any) => {
        return methods.addIsLeaf(data);
      },
    });

    const state = reactive({
      checkable: true,
      draggable: false,
      checkStrictly: false,
      showHeader: false,
      showToolBar: false,
      showSearch: false,
      showLine: false,
      selectable: false,
    });

    watch([() => selectData?.objectId, () => selectData.appId], () => {
      methods?.expandAll(false);
      methods?.setAllCheckState(false);
      if (selectData?.objectId && selectData.appId) {
        methods?.refresh().then(() => {});
      }
    });

    const [menuRef, menuProps, menuMethods] = useButtonGroup({
      sortRule: 'default',
      pageName: 'AuthIndex',
      items: [
        {
          text: t('authManage.allOk'),
          name: 'allOk',
          menuType: 'button',
          size: 'small',
          menuPosition: 'menu',
          key: '1',
        },
        {
          text: t('authManage.allNo'),
          name: 'allNo',
          menuType: 'button',
          menuPosition: 'menu',
          key: '2',
        },
        {
          text: t('platform.common.reset'),
          name: 'reset',
          menuType: 'button',
          menuPosition: 'menu',
          key: '3',
        },
        {
          text: t('platform.common.save'),
          name: 'save',
          menuType: 'button',
          type: 'primary',
          menuPosition: 'menu',
          key: '4',
        },
      ],
    });

    // 点击功能授权按钮
    const authFunClick = data => {
      if (data.name == 'allOk') {
        // 全部允许
        allSelectNode();
      } else if (data.name == 'allNo') {
        // 全部禁止
        allNoSelectNode();
      } else if (data.name == 'reset') {
        // 重置
        resetHandler();
      } else if (data.name == 'save') {
        // 保存
        saveHandler();
      }
    };

    // 全选操作
    const allSelectNode = () => {
      const treeData = cloneDeep(methods.getData()) || [];
      if (!treeData || treeData?.length <= 0) return;
      methods.setAllCheckState(true);
      // saveMenuFun();
    };

    // 全部禁止操作
    const allNoSelectNode = () => {
      const treeData = cloneDeep(methods.getData()) || [];
      if (!treeData || treeData?.length <= 0) return;
      methods.setAllCheckState(false);
      // saveMenuFun();
    };

    // 重置
    const resetHandler = () => {
      if (methods.getData()?.length === 0) return;
      authFunBtnLoading();
      methods.setAllCheckState(false);
      methods.refresh().then(() => {
        successHandler();
      });
    };

    // 保存
    const saveHandler = () => {
      saveMenuFun();
    };

    // 控制功能授权按钮loading状态
    const authFunBtnLoading = () => {
      menuMethods.setButtonLoadingState('allOk', { loading: true });
      menuMethods.setButtonLoadingState('allNo', { loading: true });
      menuMethods.setButtonLoadingState('save', { loading: true });
      menuMethods.setButtonLoadingState('reset', { loading: true });
    };

    // 执行成功后的回调
    const successHandler = () => {
      menuMethods.setButtonLoadingState('allOk', { loading: false });
      menuMethods.setButtonLoadingState('allNo', { loading: false });
      menuMethods.setButtonLoadingState('save', { loading: false });
      menuMethods.setButtonLoadingState('reset', { loading: false });
    };

    //根据id删除数组中重复的数据
    function delRepeat(data) {
      let obj = {};
      let arr = [];
      for (let i = 0, leni = data.length; i < leni; i++) {
        let item = data[i];
        if (!obj[item.key]) {
          obj[item.key] = item;
          arr.push(item);
        }
      }
      return arr;
    }

    //把树型数据转化为同级数据（拉平）
    function getSameLevalData(treeData, arr = []) {
      for (let i = 0, leni = treeData.length; i < leni; i++) {
        let item = treeData[i];
        let cloneItem = cloneDeep(item);
        cloneItem.children = [];
        arr.push(cloneItem);
        if (item.children && item.children.length) {
          arr = getSameLevalData(item.children, arr);
        }
      }
      return arr;
    }

    function getDirMenus(allData, keys, parentId, menuArr = [], permissionArr = []) {
      if (parentId && parentId != -1) {
        for (let i = 0, leni = allData.length; i < leni; i++) {
          let itemi = allData[i];
          //找到parentId这条数据,这条数据肯定是菜单数据，因为权限的父级肯定是菜单
          if (itemi.key === parentId) {
            //判断parentId是否存在与选中数据中
            if (keys.findIndex(key => `${key}` === `${itemi.key}`) > -1) {
              let obj = { ...itemi, isAll: 1 };
              menuArr.push(obj);
            } else {
              let obj = { ...itemi, isAll: 0 };
              menuArr.push(obj);
            }
            //通过parentId继续向上查找
            if (itemi.parentId && itemi.parentId != -1) {
              let result = getDirMenus(allData, keys, itemi.parentId, menuArr, permissionArr);
              menuArr = result.menuArr;
              permissionArr = result.permissionArr;
            }
          }
        }
      } else {
        if (allData && allData.length) {
          for (let i = 0, leni = allData.length; i < leni; i++) {
            let itemi = allData[i];
            //判断id是否存在与已选中的数据中
            if (keys.findIndex(key => `${key}` === `${itemi.key}`) > -1) {
              //存在
              if (itemi.authType == 2) {
                //如果是权限，则需要找到当前同级数据，进行判断是否都是选中状态
                // let sameParentData = getSameParentId(allData, itemi.parentId);
                //判断相同父级的数据的id是不是都在选中数据中，是的话返回1，不是的话返回0
                // let state = getSelectedState(sameParentData, keys);
                let obj = { ...itemi, isAll: 1 };
                menuArr.push(obj);
                permissionArr.push(itemi.key);
              } else {
                let obj = { ...itemi, isAll: 1 };
                menuArr.push(obj);
              }
              //是菜单，且存在的情况，继续寻找父级数据
              //通过parentId继续向上查找
              if (itemi.parentId && itemi.parentId != -1) {
                let result = getDirMenus(allData, keys, itemi.parentId, menuArr, permissionArr);
                menuArr = result.menuArr;
                permissionArr = result.permissionArr;
              }
            }
          }
        }
      }
      return { menuArr, permissionArr };
    }

    //找到相同parentId的数据返回一个数组
    // function getSameParentId(allData, parentId) {
    //   let arr = [];
    //   arr = allData.filter(item => item.parentId == parentId);
    //   return arr;
    // }

    // 判断数据是否都存在与数组中
    // function getSelectedState(data, keys) {
    //   let result = 1;
    //   for (let i = 0, leni = data.length; i < leni; i++) {
    //     let itemi = data[i];
    //     if (!keys.includes(itemi.key)) {
    //       result = 0;
    //       return result;
    //     }
    //   }
    //   return result;
    // }

    // 保存授权
    const saveMenuFun = () => {
      if (methods.getData()?.length === 0) return;
      authFunBtnLoading();
      const checkedKeys = methods.getCheckedKeys();
      const treeData = cloneDeep(methods.getData()) || [];
      // 获取拉平数据
      let sameLevalTreeData = getSameLevalData(treeData);
      // 获取到权限数据
      const { menuArr } = getDirMenus(sameLevalTreeData, checkedKeys, null);
      let paramMenuId = cloneDeep(delRepeat(menuArr));
      saveMenu({
        lang: commonParams.value?.lang,
        connect: commonParams.value?.connect,
        companyId: commonParams.value?.companyId,
        objectId: selectData?.objectId,
        appId: selectData?.appId,
        permissionType: selectData?.permissionType,
        data: paramMenuId || [],
        userId: commonParams.value?.user_id,
      })
        .then(result => {
          if (result.code == 200) {
            message.success(result.msg);
            successHandler();
          } else {
            message.error(result.msg);
            successHandler();
          }
        })
        .catch(() => {
          successHandler();
          message.error(t('authManage.errorMsg'));
        });
    };

    return {
      commonParams,
      demoHbtreeRef,
      props,
      state,
      radioType,
      menuRef,
      menuProps,
      authFunClick,
    };
  },
});
</script>
<style lang="less" scoped>
.platform-dict-auth-page {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.platform-authFun-btns {
  position: absolute;
  top: 12px;
  right: 20px;
  width: calc(100% - 115px);
  text-align: right;
}
.auth-fun-tree {
  height: calc(100vh - 300px);
  margin-bottom: 20px;
}
</style>
