import { login, logout, getInfo, refreshToken,phoneLogin } from '@/api/login'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'
import store from '@/store'
import router from '@/router'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const userType = userInfo.userType
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid, userType).then(res => {
          if(res.code == 530 || res.code == 503 || res.code == 303){
            resolve(res)
            return
          }
          // if(userType == '99' && res.data.type == '99'){
          //   // let token = res.data.access_token;
          //   // let loginUrl = window.location.href;
          //   // window.location.href = res.data.linkUrl + '?loginUrl=' + loginUrl + '&token=' + token;
          //   // window.location.href = 'http://localhost:8080/#/index?loginUrl=' + loginUrl + '&token=' + token;   //本机测试用
          //   // return
          //   resolve(res)
          // }
          let data = res.data
          localStorage.setItem('userId',data.user_id);
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    LoginPhone({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo).then(res => {
          if(res.code == 530 || res.code == 503 || res.code == 303){
            resolve(res)
            return
          }
          // if(userType == '99' && res.data.type == '99'){
          //   // let token = res.data.access_token;
          //   // let loginUrl = window.location.href;
          //   // window.location.href = res.data.linkUrl + '?loginUrl=' + loginUrl + '&token=' + token;
          //   // window.location.href = 'http://localhost:8080/#/index?loginUrl=' + loginUrl + '&token=' + token;   //本机测试用
          //   // return
          //   resolve(res)
          // }
          let data = res.data
          localStorage.setItem('userId',data.user_id);
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          setExpiresIn(data.expires_in)
          commit('SET_EXPIRES_IN', data.expires_in)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          if(res){
            let user = res.user
            let avatar = user.avatar == "" ? require("@/assets/ZDimages/tx_cion.png") : user.avatar;
            commit('SET_ROLES', ['placeholder'])
            commit('SET_PERMISSIONS', res.permissions)
            commit('SET_NAME', user.userName)
            commit('SET_AVATAR', avatar)
            localStorage.setItem('user',JSON.stringify(user));
            resolve(res)
          }else{
            store.dispatch('LogOut').then(() => {
              localStorage.removeItem('serviceType');
              router.replace({
                path: '/login'
              })
            })
            return
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token).then(res => {
          setExpiresIn(res.data)
          commit('SET_EXPIRES_IN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
