import storage from 'store'
import { login, getInfo, logout, tokenRenew } from '@/api/login'
import { ACCESS_TOKEN, ACCESS_EXPIRE,TOGGLE_LANAGUAGE } from '@/store/mutation-types'
//import { welcome } from '@/utils/util'
import { mockMenu } from "./mock";
import { loadLanguageAsync } from '@/locales'
import defaultSettings from '@/config/defaultSettings'
const user = {
  state: {
    token: '',
    name: '',
    enterpriseName:'',
    welcome: '',
    avatar: '',
    roles: [],
    info: null,
    homePage: '',
    menus: [], // 菜单路由
    custom: {},
    warehouse: {
      warehouseCode: '',
      warehouseId: '',
      warehouseName: ''
    } // 默认仓库 // 个性化配置
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_MENU: (state, menus) => {
      state.menus = menus
    },
    SET_WAREHOUSE: (state, warehouse) => {
      state.warehouse = warehouse
    },
    SET_HOME_PAGE: (state, homePage) => {
      state.homePage = homePage
    },
    SET_CUSTOM: (state, custom) => {
      state.custom = custom
    },
    SET_ENTERPRISE_NAME: (state, enterpriseName) => {
      state.enterpriseName = enterpriseName
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            const { success, data } = response
            if (success) {
              storage.set(ACCESS_TOKEN, data.token)
              sessionStorage.setItem(ACCESS_TOKEN,data.token)
              storage.set(ACCESS_EXPIRE, data.expir)
              sessionStorage.removeItem('warehouse')
              commit('SET_TOKEN', data.token)
              //加载语言
              let lang = storage.get(TOGGLE_LANAGUAGE, defaultSettings.lang)
              loadLanguageAsync(lang)
            }
            resolve(response)
          })
          .catch(error => {
            console.log({ error })
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(response => {
            const { menus, operations, pageElements, homePage, custom, nickname,enterpriseName,warehouseList = []
            } = response.data
            menus.push(...mockMenu)
            // 字段转化
            const newMenus = menus.map(o => {
              const item = {
                ...o,
                path: o.url
              }
              delete item.url
              return item
            })

            commit('SET_MENU', newMenus)
            commit('SET_NAME', nickname)
            commit('SET_INFO', response.data)
            commit('SET_OPERATIONS', operations)
            commit('SET_PAGE_ELEMENTS', pageElements)
            commit('SET_CUSTOM', custom)
            commit('SET_HOME_PAGE', homePage ? homePage : '/')
            commit('SET_ENTERPRISE_NAME', enterpriseName ? enterpriseName : '')
            if(sessionStorage.getItem('warehouse')) {
              let warehouse = JSON.parse(sessionStorage.getItem('warehouse'))
              commit('SET_WAREHOUSE', warehouse)
            } else {
              if (warehouseList && warehouseList[0]) {
                commit('SET_WAREHOUSE', warehouseList[0])
              }
            }
           

            resolve(response.data)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        /* 模拟执行退出，后端提供退出接口时此代码片段删除 -start- */
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_MENU', [])
        commit('SET_INFO', null)
        storage.remove(ACCESS_TOKEN)
        sessionStorage.removeItem(ACCESS_TOKEN)
        resolve(true)
      })
    },
    // token 续订
    Renew({ commit }) {
      if(!defaultSettings.renew.open){
        return
      }
      let token = storage.get(ACCESS_TOKEN)
      let expire = storage.get(ACCESS_EXPIRE)
      const isExpired = (Number(expire) - Date.now()) <= defaultSettings.renew.blank
      if(!token || isExpired){
        tokenRenew()
        .then(res => {
          const { success, data } = res
          if (success) {
            storage.set(ACCESS_TOKEN, data.token)
            sessionStorage.setItem(ACCESS_TOKEN,data.token)
            storage.set(ACCESS_EXPIRE, data.expir)
            commit('SET_TOKEN', data.token)
          }
        })
        .catch(error => {
          console.log('token续订失败',{ error })
        })
      }
    }
  }
}

export default user
