import {
  Login,
  Register,
  GetAccountInfo,
  GetMyPermission
} from '@/api/account'
import router from '@/router'
import { GetSiteData } from '@/api/data'
import { setToken, getToken, localSave, localRead, get_JSON_parse, matchRouters } from '@/libs/util'
import { asynRouters } from '@/router/aysnRouters.js'
import Cookies from 'js-cookie'
export default {
  state: {
    token: getToken(),
    access: '',
    hasGetInfo: false,
    p_name: localRead('p_name'),
    p_logo: localRead('p_logo'),
    p_ico: localRead('p_ico'),
    is_dev_register: false,
    userProfile: get_JSON_parse(localRead('p_UserProfile')),
    permission: []
    // userProfile: localRead('p_UserProfile')
  },
  mutations: {
    // setAsynRouters (state, route) {
    //   state.asynRouters = route
    // },
    setPermission (state, route) {
      state.permission = route
    },
    set_p_name (state, name) {
      state.p_name = name
    },
    set_p_logo (state, logo) {
      state.p_logo = logo
    },
    set_p_ico (state, ico) {
      state.p_ico = ico
    },
    set_is_dev_register (state, value) {
      state.is_dev_register = value
    },
    setUserProfile (state, data) {
      state.userProfile = data
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    }
  },
  getters: {
    userMemberLevel: state => {
      let key = state.userProfile.member_level
      let level = ''
      switch (true) {
        case (key < 100):
          level = '普通会员'
          break
        case (key >= 100 && key < 200):
          level = '管理员'
          break
        case (key > 200):
          level = '超级管理员'
          break

        default: level = '未匹配到账户类型'
          break
      }
      return level
    }

  },
  actions: {
    // 获取用户权限
    getPermission ({ state, commit }) {
      let formdata = new FormData()
      formdata.append('access_token', state.token)

      return GetMyPermission(formdata).then(res => {
        var asyn_routes = []
        if (res.data.level > 200) {
          commit('setPermission', asynRouters)
          asyn_routes = asynRouters
          // router.addRoutes(asynRouters)
          // 从其他角色切换到超管时会出现路由子集为空，出现时强刷页面
          if (!asynRouters[0].children.length || asynRouters[0].children.length === 0) {
            window.location.reload()
          }
        } else {
          let permission = res.data.paths
          const routes = matchRouters(asynRouters, permission)
          commit('setPermission', routes)
          asyn_routes = routes
          // router.addRoutes(routes)
        }
        return asyn_routes
      })
    },
    // 注册
    handleRegister ({ commit }, params) {
      let formdata = new FormData()
      for (const key in params) {
        params[key] && formdata.append(key, params[key])
      }
      return new Promise((resolve, reject) => {
        Register(formdata).then(res => {
          const data = res.data
          commit('setToken', data.access_token)
          // Cookies.set('name', '');
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 登录
    handleLogin ({ commit }, { username, password, captcha, cookiesExp }) {
      username = username.trim()
      const formdata = new FormData()
      formdata.append('username', username)
      formdata.append('password', password)
      formdata.append('captcha', captcha)
      // formdata.append('is_admin_login', 1) // 管理员登录
      return new Promise((resolve, reject) => {
        Login(formdata).then(res => {
          const data = res.data
          setToken(data.access_token, cookiesExp)
          commit('setToken', data.access_token)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        commit('setAccess', [])
        Cookies.remove('p_token', { name: 'login' })
        Cookies.remove('p_UserProfile', { name: 'login' })
        resolve()
      })
    },
    // 获取平台相关信息
    GetPlatformData ({ commit }) {
      return new Promise((resolve, reject) => {
        GetSiteData().then(res => {
          let data = {}
          Object.assign(data, res.data)
          let is_dev_register = res.data.is_dev_register
          commit('set_is_dev_register', is_dev_register)
          delete data.dev_reg_level_list
          delete data.is_dev_register
          delete data.catpcha_switch
          data.language_list && delete data.language_list
          for (const key in data) {
            localSave(`p_${key}`, data[key])
            commit(`set_p_${key}`, localRead(`p_${key}`))
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户相关信息
    GetAccountData ({ commit, state }) {
      const formdata = new FormData()
      formdata.append('access_token', state.token)
      return new Promise((resolve, reject) => {
        GetAccountInfo(formdata).then(res => {
          if (res.data.profile) {
            localSave('p_UserProfile', JSON.stringify(res.data.profile))
            commit('setUserProfile', res.data.profile)
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
