import { defineStore } from 'pinia';
import { ElMessageBox, ElMessage } from "element-plus";
import { getToken, setToken, removeToken } from '@/utils/auth';
import { loginApi, logoutApi } from '@/api/auth';
import { getUserInfo,kickOutUser } from '@/api/user';
import { getMenuTreeByType,listRoutes } from '@/api/menu';
import Cookies from 'js-cookie';
import { resetRouter } from '@/router';
import { store } from '@/store';
import { LoginData } from '@/api/auth/types';
import { ref } from 'vue';
import { UserInfo } from '@/api/user/types';
import { Menu } from '@/api/menu/types';

export const useUserStore = defineStore('user', () => {
  // state
  const Token = ref<string>(getToken() || '');
  const nickname = ref<string>('');
  const avatar = ref<string>('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const menuArr = ref<Array<string>>([]); // 大屏菜单
  const badgeval = ref('')
  const stationId = ref('')
  const stationName = ref('')
  const stationData:any = ref([])
  const regionId:any = ref('')
  const regionName:any = ref('')
  const stationCode = ref('')
  const username = ref('')
  const userId = ref('')
  const userInfo:any= ref({})
  const videoList = ref('')
  const giveanalarmInfo:any = ref('')
  const trendsInfo:any = ref('')
  const alarmCount:any = ref()
  const isAdmin:any = ref(false)
  const isBusiness:any = ref(false)
  
  const isExpire:any = ref(false)
  const webApiMonitorUrl:any = process.env.NODE_ENV=='development'? import.meta.env.VITE_APP_BASE_URL:window.webConfig.webApiMonitorUrl
  const webApiBaseUrl:any = process.env.NODE_ENV=='development'? import.meta.env.VITE_APP_BASE_API:window.webConfig.webApiBaseUrl
  const wsApiBaseUrl:any = process.env.NODE_ENV=='development'? import.meta.env.VITE_APP_BASE_WS:window.webConfig.wsApiBaseUrl
  const answeringUrl:any = window.webConfig.answeringUrl
  const promptTitle:any = ref('')
  // actions

  // 登录
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response:any) => {
          
          if(response.msg.indexOf("updatePassword_") != -1){
            if(response.msg.split('_')[1]== "initial"){
              promptTitle.value = "您的密码为初始密码，存在安全风险，请立即修改初始密码!"              
            }else{
              promptTitle.value = "您的密码已到期（"+ response.msg.split('_')[1] +"天），请立即修改密码！"
            }
            isExpire.value = true
            const { token } = response.data;
            Token.value = token;
            setToken(token);
            resolve(response);
          }else if(response.code =='3'){
            ElMessageBox.confirm("当前账号已登录，是否踢出账号！", "提示信息", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                let params = {
                  userId: response.msg,

                };
                kickOutUser(params).then((res: any) => {
                  location.reload() 
          
                });
              })
            .catch(() => {
            });
          } else{
            const { token } = response.data;
            Token.value = token;
            setToken(token);
            resolve(response);
          }
          
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(({ data }) => {
          if (!data) {
            return reject('Verification failed, please Login again.');
          }
          if (!data.roles || data.roles.length <= 0) {
            reject('getUserInfo: roles must be a non-null array!');
          }
          userInfo.value = data.userInfo;
          nickname.value = data.userInfo.nickname;
          avatar.value = data.userInfo.avatar;
          roles.value = data.roles;
          perms.value = data.permissions;
          username.value = data.userInfo.username;
          userId.value = data.userInfo.id;
          videoList.value = data.userInfo.custom1;
          
          regionId.value = data.userInfo.poid;
          regionName.value = data.userInfo.porgname;
          stationData.value = data.codeList;
          const stationIds = Cookies.get('stationIds');
          if(data.codeList.length >1){
            for(let i =0; i < data.codeList.length; i++){
              if(data.codeList[i].stationId== stationIds){
                stationId.value = data.codeList[i].stationId;
                stationName.value = data.codeList[i].stationName;
                stationCode.value = data.codeList[i].stationCode;
              }
              if(stationIds == '' || stationIds == undefined){
                stationId.value = data.codeList[0].stationId;
                stationName.value = data.codeList[0].stationName;
                stationCode.value = data.codeList[0].stationCode;
              }
              
            }
          }else if(data.codeList.length == 1){
            stationId.value = data.codeList[0].stationId;
            stationName.value = data.codeList[0].stationName;
            stationCode.value = data.codeList[0].stationCode;
          }else{
            stationId.value = data.userInfo.oid;
            stationName.value = data.userInfo.orgname;
            stationCode.value = data.userInfo.orgcode;
          }
          
          // getMenu()
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  // 获取大屏菜单
  function getMenu() {
    return new Promise<Menu>((resolve, reject) => {
      const params = {
        sysetmCode:'2'
      }
      getMenuTreeByType(params)
        .then(( res:any ) => {
          listRoutes().then((response:any)=>{

            if(response.length == 0){
                isAdmin.value =  false
              }else{
                isAdmin.value=  true
              }
          })
          if(res.length == 0){
            isBusiness.value =  false
          }else{
            isBusiness.value=  true
          }
          menuArr.value = res
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetRouter();
          resetToken();
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  // 重置
  function resetToken() {
    removeToken();
    Token.value = '';
    nickname.value = '';
    userInfo.value = {};
    avatar.value = '';
    roles.value = [];
    perms.value = [];
    menuArr.value = [];
    alarmCount.value = 0;
    // isAdmin.value = false
    giveanalarmInfo.value = ''
    trendsInfo.value = ''
    stationId.value = '';
    stationName.value = '';
    stationData.value = [];
    stationCode.value = '';
    username.value = ''
    userId.value = ''
    videoList.value = ''
    regionId.value = '';
    regionName.value = '';
  }
  return {
    Token,
    nickname,
    userInfo,
    username,
    userId,
    videoList,
    avatar,
    stationId,
    stationName,
    stationData,
    stationCode,
    regionId,
    regionName,
    roles,
    menuArr,
    perms,
    alarmCount,
    isAdmin,
    isBusiness,
    giveanalarmInfo,
    trendsInfo,
    isExpire,
    promptTitle,
    login,
    getInfo,
    getMenu,
    logout,
    resetToken,
    badgeval,
    webApiMonitorUrl,
    webApiBaseUrl,
    wsApiBaseUrl,
    answeringUrl
  };
});

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