import { ApiResult } from '@/configs/axios';
import { CustomerRate, CustomerThemeConfig } from '@/configs/customer';
import UserService from '@/services/UserService';
import { defineStore } from 'pinia';
import { StorageLike } from 'pinia-plugin-persistedstate';
import SecureLS from 'secure-ls';
import {USER_DEFAULT_HEADER,ENTERPRISE_DEFAULT_HEADER } from '@/configs/customer'

const ls = new SecureLS({
    isCompression: false,
    encryptionSecret: '38c31684-d00d-30dc-82e0-fad9eec46d1d',
})
const st: StorageLike = {
    setItem(key: string, value: string) {
        ls.set(key, value);
    },
    getItem(key: string): string | null {
        return ls.get(key);
    },
}

export interface UserLoginResult {
    status:'ERROR'|'CHOSEN'|'SUCCESS',
    verify:boolean,
    data?:any[]
}
export interface AutoLoginResult{
    isSuccess:boolean,
    message:string
}

export const useUserStore = defineStore('user', {
    state:()=>({
        token:'' as string,
        userInfo:{} as any
    }),
    getters: {
        getUserToken: (state) => {
          return state.token;
        },
        getUser: (state) => {
          return state.userInfo;
        },
        getUserTheme: (state) => {
            let rate:CustomerRate = 'FREE'
            if(state.userInfo.it) rate = 'EN'
            else if(state.userInfo.iv) rate = 'VIP'
            else if(state.userInfo.isTemplate) rate = 'TME'
            const theme = CustomerThemeConfig.find(x=>x.name==rate)
            return theme
        },
    },
    actions:{
        async setUserAutoLoginAsync(tempToken:string):Promise<AutoLoginResult> {
            try {
                const response = await UserService.AutoLoginAsync(tempToken)
                if (response.data.resultCode == ApiResult.SUCCESS) {
                    const d = response.data.data
                    // d.nickname=d.emName
                    // d.photo = d.Icon
                    // d.company = d.GroupName
                    // d.logo = d.GroupPic
                    // d.isTemplate = d.IsEditTripTemplate
                    // d.ia = 0
                    // d.it = true
                    // d.expire = d.Expire
                    // d.ic = d.IsGroupCreate
                    // d.id = d.DisplayId
                    // d.iv = 0
                    this.token = d.token
                    this.userInfo = d.userinfo
                    if(!this.userInfo.photo || (!this.userInfo.photo.includes('http://')&& !this.userInfo.photo.includes('https://'))){
                        this.userInfo.photo = USER_DEFAULT_HEADER
                    }
                    if(!this.userInfo.logo || (!this.userInfo.logo.includes('http://')&& !this.userInfo.logo.includes('https://'))){
                        this.userInfo.logo = ENTERPRISE_DEFAULT_HEADER
                    }
                    return { isSuccess:true, message:''}
                }else{
                    return { isSuccess:false, message:response.data.message}
                }
            } catch (error) {
                return { isSuccess:false, message:'登录异常，请刷新页面重试'}
            }
            
        },
        async setUserLoginOut(){
            await UserService.UserSignOutAsync()
            this.token=''
            this.userInfo={}
            window.location.href='/login'
        },
        setNewUserInfo(user:any){
            this.token = user.token
            this.userInfo = user.userinfo
            if(!this.userInfo.photo || (!this.userInfo.photo.includes('http://')&& !this.userInfo.photo.includes('https://'))){
                this.userInfo.photo = USER_DEFAULT_HEADER
            }
            if(!this.userInfo.logo || (!this.userInfo.logo.includes('http://')&& !this.userInfo.logo.includes('https://'))){
                this.userInfo.logo = ENTERPRISE_DEFAULT_HEADER
            }
        },
        setOnlyUserInfo(userinfo:any){
            this.userInfo = userinfo
            if(!this.userInfo.photo || (!this.userInfo.photo.includes('http://')&& !this.userInfo.photo.includes('https://'))){
                this.userInfo.photo = USER_DEFAULT_HEADER
            }
            if(!this.userInfo.logo || (!this.userInfo.logo.includes('http://')&& !this.userInfo.logo.includes('https://'))){
                this.userInfo.logo = ENTERPRISE_DEFAULT_HEADER
            }
        },
        async setUserPasswordLoginAsync(account:string,pwd:string,vtoken:string,tid:string='') {
            try {
                let response = await UserService.PasswordLoginAsync(account,pwd,vtoken,tid)
                if (response.data.resultCode == ApiResult.SUCCESS) {
                    if(!Array.isArray(response.data.data)) {
                        this.token = response.data.data.token
                        this.userInfo = response.data.data.userinfo
                        if(!this.userInfo.photo || !this.userInfo.photo.includes('http://')|| !this.userInfo.photo.includes('https://')){
                            this.userInfo.photo = USER_DEFAULT_HEADER
                        }
                        if(!this.userInfo.logo || !this.userInfo.logo.includes('http://')|| !this.userInfo.logo.includes('https://')){
                            this.userInfo.logo = ENTERPRISE_DEFAULT_HEADER
                        }
                        return { status:'SUCCESS',verify:false  } as UserLoginResult
                    } else {
                        return { status:'CHOSEN', data:response.data.data,verify:false } as UserLoginResult
                    }
                    
                } else return { status:'ERROR',verify:response.data.data==1 } as UserLoginResult
            } catch (error) {}
            return { status:'ERROR',verify:true } as UserLoginResult
        },
        setOldSaPermission(ia:boolean){
            this.userInfo.ia = ia
            this.userInfo.ic = false
        }
    },
    persist: {
        storage: st,
    }
});