import { query as queryUsers } from '@/services/user';
import { queryDepV2 } from '@/services/approval';
import { queryRole } from '@/services/SysAdmin';

function getDepUserTree(data) {
  data.title = `${data.Name}`;
  data.id = data.ID;
  data.value = data.ID;
  // data.selectable = false;
  if (!data.children) data.children = new Array();

  if (data.children) {
    data.children.forEach((item) => {
      getDepUserTree(item);
    });
  }

  if (data.Users && data.Users.length !== 0) {
    data.Users.forEach((item) => {
      item.title = item.CName;
      item.id = item.ID + '||' + data.ID;
      item.value = item.ID + '||' + data.ID;
      // item.selectable = true;
      item.DepId = data.ID;
      data.children.push(item);
    });
  }
  return data;
}

const getRoleList = (data) => {
  let roleList = [];
  (data || []).forEach((dep) => {
    (dep.Role || []).forEach((role) => {
      roleList.push(role);
    });

    if (dep.children) {
      let res = getRoleList(dep.children, roleList);
      roleList = res.concat(res);
    }
  });
  return roleList;
};
export default {
  namespace: 'user',

  state: {
    list: [],
    // currentUser: { Permission: {} },
    message: {},
    userList: [],
    depRole: [],
    depUserTree: [],
    roleList: [],
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUsers);
      if (response) {
        yield put({
          type: 'save',
          payload: response.data.list,
        });
      }
    },
    *getRoleList({ payload }, { call, put }) {
      const response = yield call(queryRole, payload);
      if (response) {
        yield put({
          type: 'saveState',
          payload: { roleList: response.data.list },
        });
      }
    },
    *fetchDepV2({ payload, callback }, { call, put }) {
      const response = yield call(queryDepV2, { pageSize: 999999 });
      if (response) {
        const depUserTree = response.data.list.map((item) => {
          return getDepUserTree(item);
        });
        yield put({
          type: 'saveState',
          payload: { depUserTree },
        });
      }
    },
    // *fetchCurrent(_, { call, put }) {
    //   const response = yield call(queryCurrent);
    //   if (response) {
    //     yield put({
    //       type: 'saveCurrentUser',
    //       payload: response.data,
    //     });
    //   }
    // },
    // *fetchCurrent({ payload }, { call, put }) {
    //   const response = yield call(queryCurrentV2);
    //   let permission = {};
    //   if (response) {
    //     let user = response.data;
    //     user.Permissions?.forEach(item => {
    //       permission = {
    //         ...permission,
    //         ...item.Menus,
    //       };
    //     });
    //     try {
    //       localStorage.setItem('depId', user.DepId);
    //       if (payload?.ID) {
    //         const { data: resData } = yield call(queryProjectMenu, payload);
    //         // permission = resData[0] ? resData[0]?.Menus : {};
    //       }
    //     } catch (error) {
    //       console.error(error);
    //     }
    //     const resRole = yield call(queryUserRole, user.ID);
    //     let roleList = getRoleList(resRole.data.Dep);
    //     console.log(roleList);

    //     yield put({
    //       type: 'saveCurrentUser',
    //       payload: {
    //         ...user,
    //         // Permission: {},
    //         Permission: permission,
    //         roleList: roleList,
    //       },
    //     });
    //   }
    // },

    // *queryDepRole({ payload }, { call, put }) {
    //   const { data } = yield call(queryUserDetail, payload);
    //   let depId = payload.DepId;
    //   let dep = data.Dep.find(item => item.ID == depId);
    //   yield put({
    //     type: 'saveDepRole',
    //     payload: dep.Role,
    //   });
    // },
    // *fetchUnreadNotification(_, { call, put }) {
    //   const response = yield call(queryUnreadNotification);
    //   if (response) {
    //     const { data } = response;
    //     yield put({
    //       type: 'savefetchUnreadNotification',
    //       payload: { message: data },
    //     });
    //   }
    //   // ShowUnreadNotification(list, put);
    // },

    // *readNotification({ payload }, { call }) {
    //   console.log(payload);
    //   yield call(SetNotificationRead, payload);
    // },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveDepRole(state, action) {
      return {
        ...state,
        depRole: action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {
          Permission: {},
        },
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
    savefetchUnreadNotification(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    userListHandler(state, { payload }) {
      return {
        ...state,
        userList: payload,
      };
    },
    saveState(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/home') {
          // setInterval(function(){
          //   dispatch({
          //     type: 'fetchUnreadNotification',
          //   });
          // }(),1000*20);
        }
      });
    },
  },
};
