import { login,supplierLogin, logout, getInfo, refreshToken,phoneLogin } from '@/api/basicsModules/index'
import { systemNoticeGetNoticeCount } from "@/api/commonality/permission";
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'
import { judgmentNetworkReturnOutAddress } from "@/utils/ruoyi";
import store from '@/store'
import router from '@/router'
import md5 from 'js-md5';

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

  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
    },
    SET_MESSAGE_NUM: (state, num) => {
      state.messageNum = num
    },
    SET_APPROVAL_NUM: (state, num) => {
      state.approvalNum = num
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const account = userInfo.username.trim()
      const password = md5(userInfo.password);
      const code = userInfo.code
      const uuid = userInfo.uuid
      const userType = userInfo.userType
      return new Promise((resolve, reject) => {
        login(account, password, code, uuid, userType).then(res => {
          if(res.code == 530 || res.code == 503 || res.code == 303){
            resolve(res)
            return
          }
          let data = res.data
          let avatar = data.avatar == "" ? require("@/assets/ZDimages/basicsModules/tx_cion.png") : data.avatar;
          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', avatar)
          localStorage.setItem('userId',data.userId);
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          setExpiresIn(data.expiresIn)
          commit('SET_EXPIRES_IN', data.expiresIn)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    supplierLogin({ commit }, userInfo) {
      const account = userInfo.username.trim()
      const password = md5(userInfo.password);
      const code = userInfo.code
      const uuid = userInfo.uuid
      const userType = userInfo.userType
      return new Promise((resolve, reject) => {
        supplierLogin(account, password, code, uuid, userType).then(res => {
          if(res.code == 530 || res.code == 503 || res.code == 303){
            resolve(res)
            return
          }
          let data = res.data
          let avatar = data.avatar == "" ? require("@/assets/ZDimages/basicsModules/tx_cion.png") : data.avatar;
          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', avatar)
          localStorage.setItem('userId',data.userId);
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          setExpiresIn(data.expiresIn)
          commit('SET_EXPIRES_IN', data.expiresIn)
          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
          }
          let data = res.data
          let avatar = user.avatar == "" ? require("@/assets/ZDimages/basicsModules/tx_cion.png") : data.avatar;
          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', avatar)
          localStorage.setItem('userId',data.userId);
          setToken(data.token)
          commit('SET_TOKEN', data.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.data.userInfo
            let avatar = user.avatar == "" ? require("@/assets/ZDimages/basicsModules/tx_cion.png") : user.avatar;
            //操作权限存储
            localStorage.setItem('controlsRestrict',res.data.roleKeys?res.data.roleKeys:[])
            commit('SET_NAME', user.userName)
            commit('SET_AVATAR', avatar)
            localStorage.setItem('userId',user.userId);
            localStorage.setItem('deptId',user.deptId);
            localStorage.setItem('deptName',user.deptName);
            localStorage.setItem('user',JSON.stringify(user));
            localStorage.setItem('userType',user.userType==0?'5':user.userType)
            //判定校院级管理员身份
            if(user.postCode == 'school_level_admin'){
              //校级管理员
              localStorage.setItem('adminIdentity','school');
            }else if(user.postCode == 'college_admin'){
              //院级管理员
              localStorage.setItem('adminIdentity','college');
            }else{
              //非管理员身份
              localStorage.removeItem('adminIdentity');
            }
            commit('SET_ROLES', ['placeholder'])
            if(res.data.data[0] == "*:*:*"){
              commit('SET_PERMISSIONS', res.data.data)
            }
            resolve(res)
          }else{
            store.dispatch('LogOut').then(() => {
              localStorage.removeItem('serviceType');
              if(localStorage.getItem('userType') == '5'){
                this.$router.push({ path: '/supplierLogIn' });
              }else{
                if(process.env.VUE_APP_LOGIN_TYPE === 'skip'){
                  window.location.href = judgmentNetworkReturnOutAddress();
                }else{
                  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) => {
        if(getToken()){
          logout(state.token).then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        }else{
          resolve()
        }
      })
    },
    //不调用退出接口直接清除token
    LogOutNoData({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      })
    },

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

    //清除登录数据
    delToken({ commit, state }){
      localStorage.clear();
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
    },

    //获取小铃铛消息数据
    getMessageNum({ commit }){
      return new Promise((resolve, reject) => {
        systemNoticeGetNoticeCount().then(response => {
          commit('SET_MESSAGE_NUM', response.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user
