import {
  getToken,
  removeToken,
} from '@/utils/auth'

import user from '@/http/api/user'
import base from "@/http/common/base";

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  userName: '',//登录用户姓名
  schoolLogo:'',//学校logo

  roleId: '',
  buttons: [],
  userInfo:{},//用户详细信息
  userInfoLogin:{},
  // menuList: JSON.parse(localStorage.getItem('user_menuList')) || [],//从本地获取菜单信息  这个不能兼容旧的对象处理  旧的用户会白屏 除非清理历史缓存
  menuList: (() => {
    try {
      const stored = localStorage.getItem('user_menuList');
      
      // 处理空值或无效值
      if (!stored || stored === 'null' || stored === 'undefined' || stored === '[object Object]') {
        return [];
      }
      
      // 如果已经是数组或对象，直接返回（处理旧数据）
      if (stored.startsWith('[') || stored.startsWith('{')) {
        const parsed = JSON.parse(stored);
        // 确保返回的是数组
        return Array.isArray(parsed) ? parsed : [];
      }
      
      // 其他情况返回空数组
      return [];
    } catch (e) {
      // 如果解析失败，清除错误数据并返回默认值
      localStorage.removeItem('user_menuList');
      return [];
    }
  })(),
  permissions:localStorage.getItem('user_permissions') || [],//从本地获取权限信息
}

const mutations = {

  SET_MENULIST(state,menuList){
    
    console.log("store打印",menuList);
    state.menuList = menuList;
    localStorage.setItem('user_menuList', JSON.stringify(menuList));//菜单存储到本地
  },//设置菜单

  SET_PERMISSIONS(state,permissions)
  {
    state.permissions = permissions || [];
    localStorage.setItem('user_permissions', permissions);//权限存储到本地 
  },//设置权限

  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_NAME: (state, name) => {
    state.name = name
  },

  //设置学校logo
  SET_SCHOOL_LOGO: (state, schoolLogo) => { 
    state.schoolLogo = schoolLogo
  },
  //设置头像
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_userName: (state, userName) => {
    state.userName = userName
  },
  SET_USEAR_INFO:(state, userInfo)=>{
    state.userInfo = userInfo
  },
  SET_USEAR_INFOLOGIN:(state, userInfoLogin)=>{
    state.userInfoLogin = userInfoLogin
  },
  // roleId orderMgmt加权限
  SET_roleId: (state, roleId) => {
    state.roleId = roleId
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  //设置学校的webSiteId
  SET_SCHOOL_WEB_SITE_ID: (state, schoolWebSiteId) => {
    state.schoolWebSiteId = schoolWebSiteId;
    localStorage.setItem('user_schoolWebSiteId', schoolWebSiteId);//存储到本地
  },
}
let logoutInProgress = false;
const actions = {
  SET_TOKEN: ({
    commit
  }, token) => {
    commit('SET_TOKEN', token)
  },

  //设置学校logo
  SET_SCHOOL_LOGO: ({
    commit
  }, schoolLogo) => { 
    commit('SET_SCHOOL_LOGO', schoolLogo) 
  },

  //清除本地存储数据
  CLEAR_LOCAL_STORAGE:()=>{
    localStorage.removeItem('filterDataObject');//清空过滤条件
    localStorage.removeItem('examMarking_analysisMana_filtersData');//清空分析管理考试列表过滤条件
    localStorage.removeItem('analysisListData');//设置分析管理考试列表缓存数据
  },//清空本地数据  
  
  // user login
  login({
    commit
  }, userInfo) {
    console.log('action')
    const {
      username,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      console.log('action login')
      user.login({
        loginId: username.trim(),
        password: password
      }).then(response => {
        console.log('action login response')
        const {
          data
        } = response
        // console.log('data.accessToken' + data.accessToken)
        commit('SET_TOKEN', data.accessToken)
        // setToken(data.accessToken)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // //退出
  logout({commit}) {
    if (logoutInProgress) {
      return Promise.resolve();
    }
    logoutInProgress = true;
    return new Promise((resolve, reject) => {
      user.logout().then(response => {
        if(response.code==401){
          console.log('已掉线')
        }
        // window.open('/login')
        commit('SET_TOKEN', '')
        removeToken()
        localStorage.clear();//清楚本地所有缓存
        //学生退出地址 到考阅登录页
        let url=base.STUDENT_LOGIN+'/marking/#/';

        console.log("打印退出地址",url);
        // window.location.href = url;//跳转到教师端登录页面
        resolve()
       
      }).catch(error => {
        reject(error)
      }).finally(() => {
        logoutInProgress = false;
      });
    })
   
  },
  getInfo({commit}){
    return new Promise((resolve, reject) => {
      user.getUserInfo().then((res) => {
        if(res.code == 200){
          let {data} = res;
          state.userInfo = data
          commit('SET_USEAR_INFO',data)
          commit('SET_NAME', data.username)
          resolve()
        }
      },()=>{
        reject()
      })
    })
  },

  //根据token获取用户信息
  getUserInfoByToken({commit}){
    console.log('==========')
    return new Promise((resolve, reject) => {
      user.getUserInfoByToken().then((res) => {
        if(res.code == 200){
          let {data} = res;
          state.userInfo = data
          commit('SET_USEAR_INFO',data)
          commit('SET_NAME', data.userName)
          resolve()
        }
      },()=>{
        reject()
      })
    })
  },
  // remove token
  resetToken({commit}){
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },
  //设置学校的webSiteId
  SET_SCHOOL_WEB_SITE_ID:({
    commit
  }, schoolWebSiteId) => {
    commit('SET_SCHOOL_WEB_SITE_ID', schoolWebSiteId)
  },
}
const getters = {
  userInfoLogin: (state) => state.userInfoLogin
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
