/**
 * @description 公共数据
 * */
import { deptTreeSelect, getUser } from "@/api/system/user";


function handleStateData(state, keys, callback) {
  if (keys.length === 1) {
    if (state[keys[0]].length > 0) {
      return Promise.resolve(state[keys[0]]);
    } else {
      return callback();
    }
  } else {
    const result = {};
    for (let key of keys) {
      if (state[key].length > 0) {
        result[key] = state[key];
      } else {
        return callback();
      }
    }
    return Promise.resolve({ ...result });
  }
}


const commonData = {
  state: {
    // 部门数据
    depts: [],
    // 岗位
    posts: [],
    // 角色
    roles: []
  },
  mutations: {
    ['SET_DEPTS']: (state, depts) => {
      state.depts = depts;
    },
    ['SET_POSTS']: (state, posts) => {
      state.posts = posts;
    },
    ['SET_ROLES']: (state, roles) => {
      state.roles = roles;
    }
  },

  actions: {
    /** 查询部门下拉树结构 */
    getDeptTree({ state, commit }) {
      return handleStateData(state, ['depts'], () => {
        return new Promise((resolve, reject) => {
          deptTreeSelect().then(response => {
            commit('SET_DEPTS', response.data);
            resolve(response.data);
          }).catch(error => {
            reject(error);
          })
        })
      });
    },

    /** 获取角色列表,岗位列表 */
    getPostList({ state, commit }) {
      return handleStateData(state, ['posts', 'roles'], () => {
        return new Promise((resolve, reject) => {
          getUser().then(response => {
            commit('SET_ROLES', response.roles);
            commit('SET_POSTS', response.posts);
            resolve({ roles: response.roles, posts: response.posts });
          }).catch(error => {
            reject(error);
          })
        })
      })
    }
  }
}

export default commonData
