import { login, logout, getInfo, refreshToken } from '@/api/login'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import router, { resetRouter } from '@/router'
import Router from '@/router'

const user = {
  state: {
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    userType: '',
    roles: [],
    permissions: [],
    proItems:[],
    sysIds:[],
    thisIds:{},
    dept:{},
    userData: {},
    toDoNum: 0,
    noticeNum: 0,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USERTYPE: (state, userType) => {
      state.userType = userType
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_PRO_ITEMS: (state, proItems) => {
      state.proItems = proItems
    },
    SET_SYS_IDS: (state, sysIds) => {
      state.sysIds = sysIds
    },
    SET_THIS_IDS: (state, thisIds) => {
      state.thisIds = thisIds
    },
    SET_DEPT: (state, dept) => {
      state.dept = dept
    },
    SET_USERDATA: (state, userData) => {
      state.userData = userData
    },
    SET_TO_DO_NUM: (state, toDoNum) => {
      state.toDoNum = toDoNum
    },
    SET_NOTICE_NUM: (state, noticeNum) => {
      state.noticeNum = noticeNum
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          let data = res.data
          if(data.code && data.code===500){
            Message.error(data.msg)
            reject(data);
          }else {
            setToken(data.access_token)
            commit('SET_TOKEN', data.access_token)
            setExpiresIn(data.expires_in)
            commit('SET_EXPIRES_IN', data.expires_in)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
     GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        let retryCount = 0;
        const maxRetries = 3; // 设置最大重试次数
          function fetchInfo() {
            getInfo().then(res => {
              const user = res.user
              const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/photo.png") : user.avatar;
              if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                commit('SET_ROLES', res.roles)
                commit('SET_PERMISSIONS', res.permissions)
              } else {
                commit('SET_ROLES', ['ROLE_DEFAULT'])
              }
              commit('SET_ID', user.userId)
              commit('SET_NAME', user.userName)
              commit('SET_AVATAR', avatar)
              commit('SET_USERTYPE', user.userType)
              commit('SET_DEPT', user.dept)
              commit('SET_USERDATA', user)
              // console.log("user:"+JSON.stringify(user))
              // console.log(res.sysIds)
              if (res.sysIds === undefined && retryCount < maxRetries) {
                // 如果sysIds为undefined并且重试次数未达到上限，则递增重试计数并重新请求
                retryCount++;
                setTimeout(fetchInfo, 1000); // 1秒后重试，避免立即重试导致的网络拥塞
                return;
              }
              // console.log(res.sysIds)
              if (res.sysIds && res.sysIds.length > 0) {
                // 准备一次性更新localStorage的数据
                let localStorageData = {}
                let proItems = []
                if (res.sysIds.length === 0) {
                  commit('SET_THIS_IDS', [])
                }
                let num = 0;
                for (let item of res.sysIds) {
                  proItems.push({ value: item.proId, label: item.proName })
                  if (localStorage.getItem('oldProId') === undefined || localStorage.getItem('oldProId') === null || localStorage.getItem('oldProId') === '') {
                    num++
                    commit('SET_THIS_IDS', res.sysIds[0])
                  }else if (localStorage.getItem('oldProId') == item.proId ){
                    num++
                    commit('SET_THIS_IDS', item)
                  }
                }
                if (num === 0) {
                  commit('SET_THIS_IDS', res.sysIds[0])
                }
                // 最后设置项目项和系统ID
                commit('SET_PRO_ITEMS', proItems)
                commit('SET_SYS_IDS', res.sysIds)
                commit('SET_TO_DO_NUM', 0)
                commit('SET_NOTICE_NUM', 0)
              }
              resolve(res)
            }).catch(error => {
              console.error("获取信息失败：", error.message)
              reject(error)
            })
          }
        fetchInfo(); // 初始化请求
      })
    },

    // 动态修改权限(菜单跟按钮权限更新)
    changeRoles({ commit, dispatch }, role) {
      return new Promise(async resolve => {
        const token = getToken()
        commit('SET_TOKEN', token)
        // 获取最新的用户信息
        const { roles } = await dispatch('GetInfo')

        resetRouter()
        // 基于角色生成可访问的路由映射
        const accessRoutes = await dispatch('GenerateRoutes', roles, { root: true })

        // 动态添加可访问的路由
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      })
    },

    // 刷新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
