import { defineStore } from "pinia";
import pinia from "@/framework/store";
import Cookies from 'js-cookie'
import { ref } from "vue";
import { useSettingsStore } from "@/framework/store/modules/settings";
import {currentRouter} from "@/framework/router";
import { getUsermessage } from '@/framework/api/acas/index'

const settingsStore = useSettingsStore(pinia);
const USER_KEY='abacus_user';
const TOKEN_KEY=settingsStore.tokenKey
const BUSINESS_DOMAIN_KEY='abacus_business_domain'

/**开发环境初始化 */
function devDataInit(){
  if (import.meta.env.MODE === 'development'){
    const expires = new Date(new Date() * 1 + 86400000);
    Cookies.set(TOKEN_KEY, JSON.stringify({"access_token":"666666","refresh_token":"666666","user_type":"employee","scope":"scope","token_type":"token_type","expires_dt":expires.getTime()}), { expires: expires });
    Cookies.set(USER_KEY, "0", { expires: expires });
  }
}

/**设置当前业务域 */
export function setCurrentBusinessDomain(businessDomain:Object){
  sessionStorage.setItem(BUSINESS_DOMAIN_KEY, JSON.stringify(businessDomain))
  return businessDomain
}
/**获取当前业务域 */
export function getCurrentBusinessDomain(){
  let obj=JSON.parse(sessionStorage.getItem(BUSINESS_DOMAIN_KEY))
  if(null===obj||undefined===obj) return {}
  return obj
}
/**获取令牌Header信息 */
export function getTokenHeader(){
  const obj = Cookies.get(TOKEN_KEY);
  if (obj) {
    return {'Authorization':'Bearer '+JSON.parse(obj).access_token}
  }
  return null
}


/**获取Header公共参数 */
function getHeaderCommonParam(){
  let commonParam={}
  /**获取菜单、模块名称 */
  const cr=currentRouter()
  if(undefined!==cr.value.matched){
    if(undefined!==cr.value.matched[0]){
      commonParam.menuName=encodeURI(cr.value.matched[0].meta.title)
    }
    if(undefined!==cr.value.matched[1]){
      commonParam.moduleName=encodeURI(cr.value.matched[1].meta.title)
    }
  }
  /**获取业务域 */
  const cbd=getCurrentBusinessDomain()
  if(undefined!==cbd.id){
    commonParam.businessDomain=cbd.id
  }
  if(undefined!==cbd.id){
    commonParam.businessDomainName=encodeURI(cbd.name)
  }

  return JSON.stringify(commonParam)
}

/**获取所有需要发送给后端的header信息 */
export function getAllHeader(){
  const header = getTokenHeader();
  header.commonParam=getHeaderCommonParam();
  return header
}

/**获取令牌 */
export function getToken(){
  let obj = Cookies.get(TOKEN_KEY);
  if (obj) {
    obj=JSON.parse(obj)
    if('string'===typeof obj){
      obj=JSON.parse(obj)
    }
    return obj
  }
  return null
}
/**删除令牌 */
export function removeToken(){
  Cookies.remove(TOKEN_KEY)
  Cookies.remove(USER_KEY)
}
/**设置令牌 */
export function setToken(token){
  const exp=token.expires_in*1-10;//提前10秒过期，保证前端存储token先于后台token过期
  const expires = new Date(new Date() * 1 + exp * 1000);
  token.expires_dt=expires.getTime()
  delete token.expires_in
  Cookies.set(TOKEN_KEY, JSON.stringify(token), { expires: expires })
  return token
}
/**用户变化检查 */
const userChangeCheck=setInterval(function(){
    let userId=Cookies.get(USER_KEY);
    let currentUserId=useUserStoreHook().userId;
    if(userId&&currentUserId!=userId){
      location.reload();
    }
},5000);

export const useUserStore = defineStore("user", () => {
  devDataInit()
  // state
  const tenantId = ref('');
  const tenantName = ref('');
  const userId = ref('');
  const userName = ref('');
  const dept = ref('');
  const deptName = ref('');
  const avatarUrl=ref('')
  const token = ref('');
  const refreshToken = ref('');
  const tokenExpiredTime = ref(0);

  function handleInfo(alr){
    let userInfo=null;
    if(undefined!==alr&&null!==alr&&undefined!==alr.user&&null!==alr.user){
      tenantId.value = alr.user.tenantId;
      tenantName.value = alr.user.tenantName;
      userId.value = alr.user.userId;
      userName.value = alr.user.userName;
      dept.value = alr.user.deptId;
      deptName.value = alr.user.deptName;
      avatarUrl.value=alr.user.avatarUrl;
      userInfo={userId:userId.value,userName:userName.value,dept:dept.value,deptName:deptName.value,avatarUrl:avatarUrl}
    }else{
      console.error("无登录用户信息")
      userInfo={userId:'',userName:'',dept:'',deptName:'',avatarUrl:''}
    }
    if(!userInfo.avatarUrl.value){
      userInfo.avatarUrl.value=settingsStore.headAddress
    }
  }

  // 获取登录用户信息
 async function getInfo() {
  let userInfo=null;
  await getUsermessage().then((data: any) => {
    userInfo=handleInfo(data);
  });
  return new Promise((resolve, reject) => {
    resolve(userInfo);
  });
}

// 注销
function logout() {
  if(settingsStore.logoutRemoveToken){
    removeToken();
  }
  resetToken();
  window.close();//先尝试关闭标签页
  //不能关闭标签页，跳转登录页面
  window.location.href = settingsStore.loginAddress
}

// 重置
function resetToken() {
  token.value = "";
  tenantId.value = "";
  tenantName.value = "";
  userId.value = "";
  userName.value = "";
  avatarUrl.value="";
  dept.value = '';
  token.value = '';
}
return {
  tenantId,
  tenantName,
  userId,
  userName,
  dept,
  deptName,
  avatarUrl,
  token,
  refreshToken,
  tokenExpiredTime,

  getInfo,
  logout,
  resetToken,
};
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(pinia);
}
