import { getToken, setToken, removeToken, setName, removeName } from '@/utils/auth'
import { login, getUserMenuTree, getUserPermissions } from '@/api/user'

import { resetRouter } from '@/router'
import md5 from 'js-md5'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    userName: '',
    userId: '',
    avatar: '',
    permissions: [],
    tree: [],
    /* eslint-disable */
    TotalNeedSignSystemDocCount: eval(process.env.VUE_APP_WORD_FOR_PERMISSION) ? null : 0,
    TotalNeedSignTrialDocCount: eval(process.env.VUE_APP_WORD_FOR_PERMISSION) ? null : 0,
    TrialStatusStr: null,
    isTestUser: false
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    zzSessionStorage.setItem('TokenKey', token)
    // document.cookie = 'access_token=' + token + ';path=/'
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERNAME: (state, name) => {
    state.userName = name
  },
  SET_TREE: (state, tree) => {
    state.tree = tree
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERID: (state, id) => {
    state.userId = id
  },
  SET_ISTESTUSER: (state, isTestUser) => {
    state.isTestUser = eval(isTestUser)
  },
  SET_NEED_SIGN_SYSTEM_DOC_COUNT: (state, TotalNeedSignSystemDocCount) => {
    /* eslint-disable */
    if (eval(process.env.VUE_APP_WORD_FOR_PERMISSION) && !state.isTestUser) {
      zzSessionStorage.setItem('TotalNeedSignSystemDocCount', TotalNeedSignSystemDocCount)
      state.TotalNeedSignSystemDocCount = TotalNeedSignSystemDocCount
    } else {
      zzSessionStorage.setItem('TotalNeedSignSystemDocCount', 0)
      state.TotalNeedSignSystemDocCount = 0
    }
  },
  SET_NEED_SIGN_TRIALS_DOC_COUNT: (state, TotalNeedSignTrialDocCount) => {
    if (eval(process.env.VUE_APP_WORD_FOR_PERMISSION) && !state.isTestUser) {
      zzSessionStorage.setItem('TotalNeedSignTrialDocCount', TotalNeedSignTrialDocCount)
      state.TotalNeedSignTrialDocCount = TotalNeedSignTrialDocCount
    } else {
      zzSessionStorage.setItem('TotalNeedSignTrialDocCount', 0)
      state.TotalNeedSignTrialDocCount = 0
    }
  },
  SET_TRIAL_STATUS_STR: (state, TrialStatusStr) => {
    zzSessionStorage.setItem('TrialStatusStr', TrialStatusStr)
    state.TrialStatusStr = TrialStatusStr
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ UserName: username.trim(), Password: md5(password) }).then(async response => {
        if (response.IsSuccess) {
          zzSessionStorage.removeItem('lastWorkbench')
          zzSessionStorage.setItem('my_username', username.trim())
          zzSessionStorage.setItem('my_password', md5(password))
          const data = response.Result
          if (data.BasicInfo.IsFirstAdd) {
            try {
              zzSessionStorage.setItem('userId', data.BasicInfo.Id)
              commit('SET_TOKEN', data.JWTStr)
              setToken(data.JWTStr)
              resolve(false)
            } catch (e) {
              console.log(e)
            }
          } else {
            try {
              zzSessionStorage.setItem('IsAdmin', data.BasicInfo.IsAdmin)
              zzSessionStorage.setItem('IsReviewer', data.BasicInfo.IsReviewer)
              zzSessionStorage.setItem('userName', data.BasicInfo.UserName)
              commit('SET_TOKEN', data.JWTStr)
              commit('SET_NAME', data.BasicInfo.RealName)
              zzSessionStorage.setItem('isTestUser', data.BasicInfo.IsTestUser)
              commit('SET_ISTESTUSER', data.BasicInfo.IsTestUser)
              commit('SET_USERNAME', data.BasicInfo.UserName)
              commit('SET_USERID', data.BasicInfo.Id)
              setToken(data.JWTStr)
              setName(data.BasicInfo.RealName)
              const userString = decodeURIComponent(escape(window.atob(data.JWTStr.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))))
              const user = JSON.parse(userString)
              zzSessionStorage.setItem('userTypeShortName', user.userTypeShortName)
              zzSessionStorage.setItem('userId', user.id)
              zzSessionStorage.setItem('userTypeEnumInt', user.userTypeEnumInt)
              var permissions = await getUserPermissions()
              var menuTree = await getUserMenuTree()
              commit('SET_TREE', menuTree.Result)
              commit('SET_PERMISSIONS', permissions.Result)
              zzSessionStorage.setItem('newTree', JSON.stringify(menuTree.Result))
              zzSessionStorage.setItem('permissions', JSON.stringify(permissions.Result))
            } catch (e) {
              console.log(e)
            }
            resolve(response.Result)
          }
        } else {
          reject(response.ErrorMessage)
        }
      }).catch(() => {
        reject()
      })
    })
  },
  setTree({ commit }, tree) {
    commit('SET_TREE', tree)
  },
  setPermissions({ commit }, permissions) {
    commit('SET_PERMISSIONS', permissions)
  },
  setTotalNeedSignSystemDocCount({ commit }, TotalNeedSignSystemDocCount) {
    commit('SET_NEED_SIGN_SYSTEM_DOC_COUNT', TotalNeedSignSystemDocCount)
  },
  setTotalNeedSignTrialDocCount({ commit }, TotalNeedSignTrialDocCount) {
    commit('SET_NEED_SIGN_TRIALS_DOC_COUNT', TotalNeedSignTrialDocCount)
  },
  setTrialStatusStr({ commit }, TrialStatusStr) {
    commit('SET_TRIAL_STATUS_STR', TrialStatusStr)
  },
  // get user info
  getInfo({ commit, state }) {
    const token = state.token
    // 解析jwt
    const userString = decodeURIComponent(escape(window.atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))))
    commit('SET_TREE', JSON.parse(zzSessionStorage.getItem('newTree')))
    commit('SET_PERMISSIONS', JSON.parse(zzSessionStorage.getItem('permissions')))
    commit('SET_ISTESTUSER', zzSessionStorage.getItem('isTestUser'))
    const user = JSON.parse(userString)
    commit('SET_NAME', user.realName)
    commit('SET_USERID', user.id)
    commit('SET_USERNAME', zzSessionStorage.getItem('userName'))
    commit('SET_NEED_SIGN_SYSTEM_DOC_COUNT', parseInt(zzSessionStorage.getItem('TotalNeedSignSystemDocCount')))
    commit('SET_NEED_SIGN_TRIALS_DOC_COUNT', parseInt(zzSessionStorage.getItem('TotalNeedSignTrialDocCount')))
    console.log( zzSessionStorage.getItem('TotalNeedSignSystemDocCount'))
    console.log( zzSessionStorage.getItem('TotalNeedSignTrialDocCount'))
    zzSessionStorage.setItem('userName', user.name)
    zzSessionStorage.setItem('userId', user.id)
    zzSessionStorage.setItem('userTypeShortName', user.userTypeShortName)
    zzSessionStorage.setItem('userTypeEnumInt', user.userTypeEnumInt)
    return user
  },
  updateInfo({ commit, state }) {
    commit('SET_NAME', zzSessionStorage.getItem('realName'))
  },
  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    removeName()
    zzSessionStorage.clear()
    commit('RESET_STATE')
  },
  setToken({ commit }, token) {
    commit('SET_TOKEN', token)
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      document.cookie = ''
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

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

