import { getMenuData } from '@/services/menu';
import { APPLETS_PERMISSION_IDENTIFIER } from '@/utils/constants';

export const filterPermission = list => {
  const permissionData = {};
  const filterArr = (arr, v) => {
    arr.forEach(item => {
      permissionData[item.node.code] = true;
      if (item.childNodes.length) {
        filterArr(item.childNodes, v);
      }
    });
  };
  filterArr(list);
  return permissionData;
};

const MenuModel = {
  namespace: 'menu',
  state: {
    menuData: [
      {
        path: '/',
        name: $t('homepage'),
        icon: 'home',
        key: '',
      },
    ],
    permissions: {},
  },
  effects: {
    *getMenuData({ payload }, { put, call }) {
      const response = yield call(getMenuData, payload);
      if (response.code === 2000) {
        // window.localStorage.setItem('permissions', JSON.stringify(response.data));
        // 拿到数据后response.data后组装成新的数据复制给menuData
        yield put({
          type: 'save',
          payload: response.data,
        });
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      const initializationData = tableData => {
        const value = [];
        const data = [...tableData];
        data
          .filter(
            item =>
              item.node &&
              item.node.code !== APPLETS_PERMISSION_IDENTIFIER &&
              item.node.type.value < 3,
          )
          .forEach(item => {
            let obj = {};
            obj = { ...item.node };
            obj.path = obj.uri;
            obj.icon = obj.picture;
            obj.name = obj.name;
            if (item.childNodes.length) {
              obj.children = initializationData(item.childNodes);
            } else {
              obj.children = [];
            }
            value.push(obj);
          });
        return value;
      };
      const menuData = initializationData(payload);

      // console.log('payload', payload, JSON.parse(localStorage.getItem('permissions')))
      // 设置全局权限数据rules
      let { permissions } = state;
      if (JSON.stringify(permissions) === '{}') {
        const currentPermissions = payload;
        if (currentPermissions) {
          const arr = currentPermissions;
          permissions = filterPermission(arr);
        }
        window.localStorage.setItem('permissions', JSON.stringify(permissions));
      }
      return { ...state, menuData, permissions };
    },
  },
};
export default MenuModel;
