import Vue from 'vue'
import { login, logout, phoneLogin } from "@/api/login"
import { ACCESS_TOKEN, USER_NAME,USER_INFO,USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"
import { welcome } from "@/utils/util"
import { getMenus } from '@/api/system'


function toMeta(data){
  let list = new Array();
  for(let i=0;i<data.length;i++){
      let item = data[i];
      if(!item["meta"]){
        let text = item.url.split("/")[1].replace("#","")
        item["meta"] = { title: item.name, permission: [ text ] }
      }
      if(item["children"]&&item["children"] != null){
        item["children"] = toMeta(item["children"]);
      }
      list.push(item);
  }

  return list;
}

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_CODE:(state, obj) => {
      function getArray(data,obj){
        for (var i in data) {
            var parentNum=0;
            var child = data[i].children;
            if (data[i].path == obj[0].url) {
                data[i].meta.num=obj[0].num;
                break;
            } else {
                getArray(child, obj);
                if( child == undefined || child == ''){

                }else {
                    for (var j=0;j<child.length;j++){
                        if(child[j].meta.num =='' ||  child[j].meta.num==undefined){
                            child[j].meta.num=0;
                        }
                        parentNum += child[j].meta.num
                    }
                    data[i].meta.num = parentNum;
                }
            }
        }
      }
      getArray(state.permissionList,obj)

    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if(response.code =='200'){
            //const result = response.result
            //const userInfo = result.userInfo
            /**
             * 暂时定义
             */
            Vue.ls.set(ACCESS_TOKEN, response.sessionId, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_NAME, response.account, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(USER_INFO, response, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', response.sessionId)
            commit('SET_INFO', response)
            commit('SET_NAME', { username: response.account,realname: response.account, welcome: welcome() })
            //commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    //手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
          phoneLogin(userInfo).then(response => {
          if(response.code =='200'){
        const result = response.result
        const userInfo = result.userInfo
        Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
        Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
        commit('SET_TOKEN', result.token)
        commit('SET_INFO', userInfo)
        commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
        commit('SET_AVATAR', userInfo.avatar)
        resolve(response)
      }else{
        reject(response)
      }
    }).catch(error => {
        reject(error)
      })
    })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        let v_token = Vue.ls.get(ACCESS_TOKEN);
        let params = {token:v_token};
        getMenus(params).then(response => {
          if(response.length != 0){
            response = toMeta(response);
          }
          const menuData = response;
          const authData = response;
          const allAuthData = response;
          //Vue.ls.set(USER_AUTH,authData);
          sessionStorage.setItem(USER_AUTH,JSON.stringify(authData));
          sessionStorage.setItem(SYS_BUTTON_AUTH,JSON.stringify(allAuthData));
          if (menuData && menuData.length > 0) {
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token;
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        //console.log('logoutToken: '+ logoutToken)
        logout(logoutToken).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },

  }
}

export default user
