import Vue from 'vue'
import Vuex from 'vuex'
import {
  setCookie,
  getCookie,
  formatDate,
  dgTree
} from '@/utils/util.js';
import {
  stDev,
  stProd,
  proPath
} from '@/config/config.js';
import axios from '@/config/axios.js';

import index from './index/index.js';
import system from './system/index.js';

// import { ctx } from '@/config/config.js';
Vue.use(Vuex);
const state = {
  // ctx: process.env.NODE_ENV === 'production' ? ('/' + ctx) : '',
  // 请求地址
  ajaxCtx: '',
  // 图片基础路径
  imgBaseUrl: '',
  // 文件基础路径
  fileBaseUrl: '',
  // 上传文件路径
  fileUploadUrl: '',
  // 下载文件路径
  fileDownloadUrl: '',
  // ====================================
  // 面包屑
  breadcrumb: [{
    menuId: 1,
    meta: {
      'title': '首页'
    }
  }],
  //  登录日期，用于操作时的提交日期 单位毫秒
  loginTime: new Date().getTime(),
  //  路由表
  routes: [],
  //  用户信息 有就不用再取菜单
  userInfo: null,
  loginInfo: null,
  //  表格数据
  tableParams: {
    form: {
      // //  筛选条件
      // params: {

      // },
      // //  排序
      // sort: {

      // },
      orgCode: '',
      orgName: '',
      pageNum: 1,
      pageSize: 20
    },
    //  返回分页数据
    page: {
      total: 0
    }
  },
  // 所有权限信息
  allPrivilege: [],
  // 拥有权限信息
  ownPrivilege: [],
  token: '',
  ticketRes: ''

};

const getters = {
  ctx() {
    if (process.env.NODE_ENV === 'development') {
      return window.location.origin + '/views/';
    } else {
      return window.location.origin + '/views/';
    }
  },
  API() {
    if (process.env.NODE_ENV === 'development') {
      return stDev;
    } else {
      return stProd;
    }
  },
  //   平台数据权限项目路径名
  proPath() {
    return proPath;
  }
}

const mutations = {
  // //  更新路由表
  addRouters(state, routes) {
    state.routes = routes
  },
  // 更新权限信息
  refreshAllPrivilege(state, allPrivilege) {
    state.allPrivilege = allPrivilege
  },
  // 更新权限信息
  refreshOwnPrivilege(state, ownPrivilege) {
    state.ownPrivilege = ownPrivilege
  },
  //  用户详情
  userInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
  loginInfo(state, loginInfo) {
    state.loginInfo = loginInfo;
  },
  //  更新
  pageSize(state, pageSize) {
    state.table.page.pageSize = pageSize;
    state.table.form.pageSize = pageSize;
  },
  pageIndex(state, pageIndex) {
    state.table.form.pageIndex = pageIndex;
  },
  total(state, total) {
    state.table.page.total = total;
  },
  breadcrumb(state, breadcrumb) {
    state.breadcrumb = breadcrumb;
  },
  setToken(state, options) {
    state.token = options.token;
  }

}

const actions = {
  //  取用户信息
  getUserInfo({
    commit,
    state
  }) {
    let res = axios.get(proPath + 'v1/sysusers/user/token');
    res.then(res => {
      //   放入东西
      commit('userInfo', res.data);
    });
    return res;
  },
  //  取用户信息
  getLoginInfo({
    commit,
    state
  }) {
    let res = axios.post(proPath + 'auth/remoteauthentication/token');
    res.then(res => {
      //   放入东西
      commit('loginInfo', res.data);
    });
    return res;
  },
  getAllMenuUrl({
    commit,
    state
  }, obj) {
    let firstOne = window.top.localStorage.getItem('companys') ? JSON.parse(window.top.localStorage.getItem('companys'))[0].id : '';
    let companyId = window.top.localStorage.getItem('companyId') ? window.top.localStorage.getItem('companyId') : firstOne;
    let res = (obj && obj.companyId) ? axios.get(proPath + 'v1/sysmenus/findFunctionMenus?companyId=' + obj.companyId) : axios.get(proPath + 'v1/sysmenus/findFunctionMenus?companyId=' + companyId);
    res.then(res => {
      // window.top.localStorage.setItem('allPrivilege', res.data ? JSON.stringify(res.data.list) : '');
      //   放入东西
      commit('refreshAllPrivilege', res.data ? res.data.list : []);
    });
    return res;
  },
  getOwnMenuUrl({
    commit,
    state
  }, obj) {
    obj = JSON.parse(JSON.stringify(obj));
    let firstOne = window.top.localStorage.getItem('companys') ? JSON.parse(window.top.localStorage.getItem('companys'))[0].id : '';
    let companyId = window.top.localStorage.getItem('companyId') ? window.top.localStorage.getItem('companyId') : firstOne;
    let res = (obj && obj.companyId) ? axios.get(proPath + 'v1/sysmenus/findFunctionMenusByUserId?companyId=' + obj.companyId) : axios.get(proPath + 'v1/sysmenus/findFunctionMenusByUserId?companyId=' + obj.companyId);
    // let res = (obj && obj.userId && obj.menuId) ? axios.get(proPath + 'v1/sysmenus/findFuncByUAndM?userId=' + obj.userId + '&menuId=' + obj.menuId) : axios.get(proPath + 'v1/sysmenus/findFuncByUAndM?userId=' + obj.userId + '&menuId=' + obj.menuId);
    res.then(res => {
      window.top.localStorage.setItem('ownPrivilege', JSON.stringify(res.data));
      //   放入东西
      commit('refreshOwnPrivilege', res.data);
    });
    return res;
  },
  //  取菜单权限信息
  generateRoutes({
    commit,
    state
  }, obj) {
    let companyId = window.top.localStorage.getItem('companyId') ? window.top.localStorage.getItem('companyId') : JSON.parse(window.top.localStorage.getItem('companys'))[0].id;
    // let asyncRouterMap = [{ path: '*', redirect: '/404', hidden: true }];
    let asyncRouterMap = [];
    let res = (obj && obj.companyId && obj.appId) ? axios.get(proPath + 'v1/sysmenus/findMenusByUserId?companyId=' + obj.companyId + '&appId=' + obj.appId) : axios.get(proPath + 'v1/sysmenus/findMenusByUserId?companyId=' + companyId + '&appId=' + obj.userInfo.appId);
    res.then(res => {
      //   处理路由
      if (res.code === '0') {
        asyncRouterMap = asyncRouterMap.concat(res.data, asyncRouterMap);
        let menuLeave = getCookie('menuLeave');
        if (menuLeave) {
          let temp = [];
          for (let i = 0; i < asyncRouterMap.length; i++) {
            if (asyncRouterMap[i].menuLabel.indexOf(menuLeave) > -1) {
              temp.push(asyncRouterMap[i])
            }
          }
          asyncRouterMap = JSON.parse(JSON.stringify(temp));
        }
        dgTree(asyncRouterMap, 'children', item => {
          item.name = item.menuLabel;
          item.url = item.menuUrl;
        });
      } else {
        //  查询失败
        // asyncRouterMap = ;
      }
      //   更新state
      commit('addRouters', asyncRouterMap);
    });
    return res;
  },
  //  退出/注销
  loginOut({
    commit,
    state
  }) {
    //  清除cookie数据
    let res = axios.get(proPath + 'logout');
    res.then(res => {
      setCookie('userInfo', '', -1, '/');
      setCookie('userLogin', '', -1, '/');
      setCookie('accessToken', '', -1, '/');
      setCookie('refreshToken', '', -1, '/');
      setCookie('workDate', '', -1);
      setCookie('appId', '', -1, '/');
      setCookie('ticket', '', -1, '/');
    });
    return res;
  },
  // 获取apollo用户列表
  apolloUser({
    commit,
    state
  }) {
    let res = axios.get(proPath + 'user');
    res.then(res => {
      //   处理路由
      commit('addUser', res);
    });
  },
  // 获取部门列表
  apolloOrg({
    commit,
    state
  }) {
    let res = axios.get(proPath + 'organizations');
    res.then(res => {
      // 处理路由
      commit('addOrg', res);
    });
  },
  ticketPush({
    commit,
    state
  }) {
    let res = axios.get(proPath + 'organizations');
    res.then(res => {
      // 处理路由
      commit('ticketRes', res);
    });
  }
}

export default new Vuex.Store({
  state,
  modules: {
    index: index,
    system: system
  },
  actions,
  getters,
  mutations
});
