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

import { resetRouter } from '@/router'
import md5 from 'js-md5'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    userTypeShortName: "",
    userName: '',
    userId: '',
    identityUserId: '',
    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,
    IsFirstSysDocNeedSign: false,
    TrialStatusStr: null,
    isTestUser: false,
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  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_USERTYPESHORTNAME: (state, userTypeShortName) => {
    state.userTypeShortName = userTypeShortName
  },
  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_IDENTITYUSERID: (state, id) => {
    state.identityUserId = id
  },
  SET_ISTESTUSER: (state, isTestUser) => {
    state.isTestUser = eval(isTestUser)
  },
  SET_IS_FIRST_SYSTEM_DOC_SIGN: (state, IsFirstSysDocNeedSign) => {
    zzSessionStorage.setItem('IsFirstSysDocNeedSign', IsFirstSysDocNeedSign)
    state.IsFirstSysDocNeedSign = IsFirstSysDocNeedSign
  },
  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 = {
  setRoles({ commit }, roles) {
    commit('SET_ROLES', roles)
  },
  changeUserName({ commit }, userName) {
    commit('SET_USERNAME', userName)
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password, UserId } = userInfo
    return new Promise((resolve, reject) => {
      let data = {
        UserName: username.trim(), Password: md5(password)
      }
      if (UserId) {
        data.UserId = UserId;
      }
      getUserLoginRoleList(data).then(async response => {
        if (response.IsSuccess) {
          zzSessionStorage.removeItem('lastWorkbench')
          zzSessionStorage.setItem('my_username', username.trim())
          zzSessionStorage.setItem('my_password', md5(password))
          zzSessionStorage.setItem('my_EMail', response.Result.BasicInfo.EMail)
          localStorage.setItem('CompanyInfo', JSON.stringify(response.Result.CompanyInfo))
          const data = response.Result
          commit('SET_ROLES', data.BasicInfo.AccountList)
          if (data.BasicInfo.IsFirstAdd || data.BasicInfo.LoginState === 1 || data.BasicInfo.IsNeedResetPwd) {
            try {
              zzSessionStorage.setItem('userId', data.BasicInfo.Id)
              commit('SET_TOKEN', data.JWTStr)
              setToken(data.JWTStr)
              resolve(response.Result)
            } 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.UserName)
              zzSessionStorage.setItem('isTestUser', data.BasicInfo.IsTestUser)
              commit('SET_ISTESTUSER', data.BasicInfo.IsTestUser)
              commit('SET_USERNAME', data.BasicInfo.UserName)
              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('userId', user.identityUserId)
              // commit('SET_IDENTITYUSERID', user.identityUserId)
              // zzSessionStorage.setItem('identityUserId', user.identityUserId)
              // 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()
      })
    })
  },
  loginByRole({ commit }, userInfo) {
    const { userRoleId } = userInfo
    let params = {
      userRoleId
    }
    return new Promise((resolve, reject) => {

      loginSelectUserRole(params).then(async response => {
        if (response.IsSuccess) {
          const data = response.Result

          try {
            commit('SET_TOKEN', data)
            setToken(data)
            commit('SET_USERID', userRoleId)
            zzSessionStorage.setItem('userId', userRoleId)
            const userString = decodeURIComponent(escape(window.atob(data.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))))
            const user = JSON.parse(userString)
            zzSessionStorage.setItem('userTypeShortName', user.userTypeShortName)
            commit('SET_USERTYPESHORTNAME', user.userTypeShortName)
            commit('SET_NAME', user.fullName)
            setName(user.fullName)
            commit('SET_IDENTITYUSERID', user.identityUserId)
            zzSessionStorage.setItem('identityUserId', user.identityUserId)
            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))
            zzSessionStorage.removeItem('lastWorkbench')
          } 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)
  },
  setIsFirstSysDocNeedSign({ commit }, IsFirstSysDocNeedSign) {
    commit('SET_IS_FIRST_SYSTEM_DOC_SIGN', IsFirstSysDocNeedSign)
  },
  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', zzSessionStorage.getItem('Name'))
    commit('SET_USERTYPESHORTNAME', user.userTypeShortName)
    commit('SET_IDENTITYUSERID', user.identityUserId)
    commit('SET_USERID', user.userRoleId)
    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')))
    commit('SET_IS_FIRST_SYSTEM_DOC_SIGN', zzSessionStorage.getItem('IsFirstSysDocNeedSign'))
    // console.log(zzSessionStorage.getItem('TotalNeedSignSystemDocCount'))
    // console.log(zzSessionStorage.getItem('TotalNeedSignTrialDocCount'))
    zzSessionStorage.setItem('userName', user.name)
    zzSessionStorage.setItem('userId', user.userRoleId)
    zzSessionStorage.setItem('identityUserId', user.identityUserId)
    zzSessionStorage.setItem('userTypeShortName', user.userTypeShortName)
    zzSessionStorage.setItem('userTypeEnumInt', user.userTypeEnumInt)
    return user
  },
  updateInfo({ commit, state }) {
    commit('SET_NAME', zzSessionStorage.getItem('Name'))
  },
  // 获取用户信息
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUser().then(res => {
        if (res.Result) {
          commit('SET_ROLES', res.Result.AccountList)
        }
        resolve(res.Result)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // user logout
  async logout({ commit, state }) {
    try {
      removeToken() // must remove  token  first
      let data = {
        IdentityUserId: zzSessionStorage.getItem('identityUserId')
      }
      if (zzSessionStorage.getItem('userId') && zzSessionStorage.getItem('userId') !== 'undefined') {
        data.UserRoleId = zzSessionStorage.getItem('userId')
      } else {
        data.UserRoleId = null
      }
      await loginOut({
        UserRoleId: zzSessionStorage.getItem('userId'),
        IdentityUserId: zzSessionStorage.getItem('identityUserId'),
      })
      resetRouter()
      removeName()
      let lang = zzSessionStorage.getItem('lang')
      zzSessionStorage.clear()
      zzSessionStorage.setItem('lang', lang)
      commit('RESET_STATE')
    } catch (e) {
      console.log(e)
    }
  },
  async resetData({ commit, state }) {
    try {
      removeToken() // must remove  token  first
      // await loginOut({
      //   UserRoleId: zzSessionStorage.getItem('userId'),
      //   IdentityUserId: zzSessionStorage.getItem('identityUserId'),
      // })
      resetRouter()
      removeName()
      let lang = zzSessionStorage.getItem('lang')
      zzSessionStorage.clear()
      zzSessionStorage.setItem('lang', lang)
      commit('RESET_STATE')
    } catch (e) {
      console.log(e)
    }
  },
  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
}

