import { toRaw } from 'vue'
import Request from '@/utils/request'

const state = {
  userInfo: {},
  language: {},
  cdn: {},
  isShowBatchEditVuex:false,
  isShowEditSpuVuex:false,
  isShowEditskuVuex:false
}

const getters = {
  // 获取用户菜单权限
  getUserAuthList: state => {
    if (state.userInfo.length <= 0) {
      return []
    }
    if (typeof state.userInfo.auth_list === 'undefined') {
      return []
    }
    return toRaw(state.userInfo.auth_list)
  }
}

const mutations = {
  SET_USER_INFO: (state, user) => {
    state.userInfo = user
  },
  SET_LANGUAGE: (state, language) => {
    state.language = language
  },
  SET_CDN: (state, cdn) => {
    state.cdn = cdn
  },
  SET_BATCHVUEX: (state, isShowBatchEditVuex) => {
    state.isShowBatchEditVuex = isShowBatchEditVuex
  },
  SET_SPUVUEX: (state, isShowEditSpuVuex) => {
    state.isShowEditSpuVuex = isShowEditSpuVuex
  },
  SET_SKUVUEX: (state, isShowEditskuVuex) => {
    state.isShowEditskuVuex = isShowEditskuVuex
  }
}

const actions = {
  setBatchVuex(context, isShowBatchEditVuex) {
    context.commit('SET_BATCHVUEX', isShowBatchEditVuex)
  },
  setSpuVuex(context, isShowEditSpuVuex) {
    context.commit('SET_SPUVUEX', isShowEditSpuVuex)
  },
  setSkuVuex(context, isShowEditskuVuex) {
    context.commit('SET_SKUVUEX', isShowEditskuVuex)
  },
  setCdn(context, cdn) {
    context.commit('SET_CDN', cdn)
  },
  setLanguage(context, language) {
    context.commit('SET_LANGUAGE', language)
  },
  // 设置用户信息
  setUserInfo (context, user) {
    context.commit('SET_USER_INFO', user)
  },

  // 获取用户信息
  getUserInfo (context) {
    return new Promise((resolve, reject) => {
      if (context.state.userInfo.length <= 0 || typeof context.state.userInfo.auth_list === 'undefined') {
        // 服务器获取用户信息
        return (new Request()).get('login/getOssInfo')
        .then(r => {
          const { errno, data, errmsg } = r
          if (errno !== 0) {
            if (errno == 500){
              alert(errmsg)
              setTimeout(() => window.location.href="/login")
            }else{
              reject(errmsg)
            }
            
          }
          context.commit('SET_USER_INFO', data)
          resolve(data)
        })
        .catch(e => {
          reject(e)
        })
      }
      resolve(toRaw(context.state.userInfo))
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
