import * as API from 'api/base/auth';

const state = {
  apps_info: {
    theme: 'themeOne', // themeOne themeTwo
    show_navs: true // 是否显示滚动菜单
  },

  left_menu: { // 左侧菜单
    list: [], // 菜单数据
    active_name: '', // 菜单高亮
    open_names: [] // 菜单展开项
  },

  top_menu: { // 顶部菜单
    active_name: '' // 菜单高亮
  },

  permissions_array: [], // 所有菜单权限(层级，不包含禁用菜单)
  permissions_object: {}, // 所有菜单权限(单级，不包含禁用菜单)
  account: null, // 用户信息
  page_nodes: [], // 用户节点(操作菜单)
  breadcrumb: [] // 面包屑
};

const getters = {
  apps_info: state => state.apps_info,
  left_menu: state => state.left_menu,
  top_menu: state => state.top_menu,
  permissions_array: state => state.permissions_array,
  permissions_object: state => state.permissions_object,
  account: state => state.account,
  page_nodes: state => state.page_nodes,
  breadcrumb: state => state.breadcrumb
};

const mutations = {
  // 设置所有菜单权限
  SET_PERMISSIONS_ARRAY(state, data) {
    state.permissions_array = data;
  },

  // 设置所有菜单权限
  SET_PERMISSIONS_OBJECT(state, data) {
    state.permissions_object = data;
  },

  // 设置用户信息
  SET_ACCOUNT(state, data) {
    localStorage.setItem('account', JSON.stringify(data));
    state.account = data;
  },

  // 设置当前页面节点(操作按钮)
  SET_PAGE_NODES(state, data) {
    state.page_nodes = data;
  },

  // 设置菜单高亮和展开项
  SET_ACTIVES(state, data) {
    // console.log(data);
    if (data && data.length) {
      if (state.apps_info.theme == 'themeOne') { // 主题1
        state.left_menu.active_name = data[data.length - 1];
        state.left_menu.open_names = data.slice(0, data.length - 1);
      } else {
        state.top_menu.active_name = data[0];
        state.left_menu.active_name = data[data.length - 1];
        state.left_menu.open_names = data.slice(1, data.length - 1);

        // 设置左侧菜单
        const mid = data[0];
        let left_menus = [];
        if (state.permissions_object[mid]) {
          if (state.permissions_object[mid].menus && state.permissions_object[mid].menus.length) {
            left_menus = state.permissions_object[mid].menus;
          }
        }
        state.left_menu.list = left_menus;
      }
    } else {
      state.left_menu.active_name = '';
      state.left_menu.open_names = [];
      state.top_menu.active_name = '';

      if (state.apps_info.theme == 'themeTwo') {
        state.left_menu.list = [];
      }
    }
  },

  // 设置左侧菜单
  SET_LEFT_MENU(state, data) {
    state.left_menu.list = data;
  },

  // 设置面包屑
  SET_BREADCRUMB(state, data) {
    state.breadcrumb = data;
  }
};

const actions = {
  /**
    * [getSiteInfo 获取站点初始化信息]
    * @param  {[type]} options.commit [description]
    * @return {[type]}                [description]
    */
  getSiteInfo({ state, commit, dispatch }) {
    return new Promise((resolve, reject) => {
      API.siteInfo().then(res => {
        if (res.code === 0) {
          let result = res.data.account;
          let temp_obj = {};
          let account = {};

          for (let k in result) {
            if (k != 'permissions') {
              account[k] = result[k];
            }
          }

          const array = handleData(result.permissions, {}, obj => {
            temp_obj = obj;
          });

          commit('SET_ACCOUNT', account);
          commit('SET_PERMISSIONS_ARRAY', array);
          commit('SET_PERMISSIONS_OBJECT', temp_obj);

          if (state.apps_info.theme == 'themeOne') {
            commit('SET_LEFT_MENU', array);
          }
        }
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  },

  /**
    * [getCurrentNodes 获取当前页面操作按钮数组]
    * @param  {[type]} options.state  [description]
    * @param  {[type]} options.commit [description]
    * @return {[type]}                [description]
    */
  getCurrentNodes({ state, commit }) {
    let nodes = [];
    const mid = vm.$route.query.mid;

    if (mid !== undefined) {
      const obj = state.permissions_object;
      if (obj && obj[mid]) {
        nodes = obj[mid].nodes.map(item => item.description);
      }
    }

    // 设置节点
    commit('SET_PAGE_NODES', nodes);
  },

  // 获取面包屑
  getBreadcrumb({ state, commit }) {
    let bread = [];
    handleBreadcrumb(vm.$route.query.mid, state.permissions_object, obj => {
      bread.push(obj);
    });
    commit('SET_BREADCRUMB', bread);
  }
};

/**
 * [handleData 权限数据处理]
 * @param  {[type]}   data            [权限]
 * @param  {[type]}   permissions_obj [权限对象]
 * @param  {Function} cb              [回调函数]
 * @return {[type]}                   [description]
 */
function handleData(data, permissions_obj, cb) {
  let permissions_ary = [];
  data.forEach((item, i) => {
    if (item.status) { // 启用状态
      let obj = {
        id: item.id,
        title: item.title,
        path: item.path,
        icon: item.icon,
        parent_id: item.parent_id,
        description: item.description,
        open: item.open,
        width: item.width,
        height: item.height,
        nodes: [], // 操作按钮
        menus: [] // 菜单
      };

      // 菜单类型
      if (item.type == 0) {
        permissions_obj[item.id] = obj;
      }

      if (item.children && item.children.length) {
        obj.nodes = handleData(item.children.filter(child => child.type == 1), permissions_obj, cb);
        obj.menus = handleData(item.children.filter(child => child.type == 0), permissions_obj, cb);
      } else {
        cb(permissions_obj);
      }
      permissions_ary.push(obj);
    }
  });
  return permissions_ary;
}

/**
 * [handleBreadcrumb 处理面包屑数据]
 * @param  {[type]} mid         [所有权限对象的某个key]
 * @param  {[type]} permissions [所有权限对象]
 * @return {[type]}             [description]
 */
function handleBreadcrumb(mid, permissions, cb) {
  let obj = {};
  const route = vm.$route;
  if (mid !== undefined && permissions) {
    let cur_permission = permissions[mid];
    if (cur_permission) {
      obj = {
        title: cur_permission.title,
        path: cur_permission.path,
        id: cur_permission.id
      };

      if (cur_permission.parent_id != 0) {
        handleBreadcrumb(cur_permission.parent_id, permissions, cb);
      }
    }
  } else {
    obj = {
      title: route.meta.title,
      path: route.path
    };
  }
  cb(obj);
}

export default{
  state,
  getters,
  mutations,
  actions
};
