import { useClientRequest } from '@/utils/request';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { UserInfoOptional, CompanyInfoData } from '../type/infoType';
import type { StorageLike } from 'pinia-plugin-persistedstate';
// 为 UniApp 创建适配的 storage（与 store/index.ts 保持一致）
const uniStorage: StorageLike = {
    getItem: (key: string): string | null => {
        try {
            return uni.getStorageSync(key);
        } catch (error) {
            console.error('读取存储失败:', error);
            return null;
        }
    },
    setItem: (key: string, value: string): void => {
        try {
            uni.setStorageSync(key, value);
        } catch (error) {
            console.error('写入存储失败:', error);
        }
    },
};
//判断当前是测试版还是正式版
const accountInfo = uni.getAccountInfoSync();
const prefixMap = {
    release: 'prod_', // production的缩写
    trial: 'beta_', // beta测试版
    develop: 'dev_', // development的缩写
};
// Token存储键和默认过期时间（24小时）
const TOKEN_STORAGE_KEY = `${prefixMap[accountInfo?.miniProgram?.envVersion]}_token`;
const INFOSTORE_KEY = `${prefixMap[accountInfo?.miniProgram?.envVersion]}info_store`;
const DEFAULT_TOKEN_EXPIRE = 24 * 60 * 60 * 1000; // 24小时（毫秒）
export const useInfoStore = defineStore(
    'infoStore',
    () => {
        // token
        const token = ref('');
        //从存储中读取token并检查是否过期
        const getTokenFromStorage = (): string => {
            try {
                const stored = uni.getStorageSync(TOKEN_STORAGE_KEY);
                console.log(stored, 'stored');
                if (!stored) return '';
                const tokenData = JSON.parse(stored);
                const { value, timestamp, expire } = tokenData;
                // 检查是否过期
                if (expire && Date.now() - timestamp > expire) {
                    uni.removeStorageSync(TOKEN_STORAGE_KEY);
                    return '';
                }
                return value;
            } catch (error) {
                console.error('读取token失败:', error);
                return '';
            }
        };
        /**
         * 设置token，可指定过期时间（毫秒）
         * @param value token值
         * @param expireMs 过期时间（毫秒），默认24小时
         */
        const setToken = (value: string, expireMs: number = DEFAULT_TOKEN_EXPIRE) => {
            token.value = value;
            // 存储带过期时间的token
            const tokenData = {
                value,
                timestamp: Date.now(),
                expire: expireMs,
            };
            uni.setStorageSync(TOKEN_STORAGE_KEY, JSON.stringify(tokenData));
        };
        //移除token
        const removeToken = () => {
            token.value = '';
            uni.removeStorageSync(TOKEN_STORAGE_KEY);
            // 移除token，并删除其他缓存数据
            uni.removeStorageSync(INFOSTORE_KEY);
        };
        // 检查token是否过期
        const isTokenExpired = (): boolean => {
            try {
                const stored = uni.getStorageSync(TOKEN_STORAGE_KEY);
                if (!stored) return true;
                const tokenData = JSON.parse(stored);
                const { timestamp, expire } = tokenData;
                // 如果没有设置过期时间，则永不过期
                if (!expire) return false;
                return Date.now() - timestamp > expire;
            } catch {
                return true;
            }
        };

        // 获取token剩余有效时间（毫秒）
        const getTokenRemainingTime = (): number => {
            try {
                const stored = uni.getStorageSync(TOKEN_STORAGE_KEY);
                if (!stored) return 0;

                const tokenData = JSON.parse(stored);
                const { timestamp, expire } = tokenData;

                if (!expire) return Infinity;

                const elapsed = Date.now() - timestamp;
                const remaining = expire - elapsed;

                return remaining > 0 ? remaining : 0;
            } catch {
                return 0;
            }
        };
        // 初始化时从存储读取token
        token.value = getTokenFromStorage();
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // 用户信息
        const userInfo = ref<UserInfoOptional | null>(null);
        // 获取用户信息
        const getUserInfo = async (): Promise<UserInfoOptional | null> => {
            try {
                if (!token.value) return null;
                const { data } = await useClientRequest.get('/app/auth/getUserInfo');
                userInfo.value = data;
                return data;
            } catch (error) {
                console.error('获取用户信息失败:', error);
                return null;
            }
        };
        // 清除用户信息
        const clearUserInfo = (): void => {
            userInfo.value = null;
        };
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        //公司信息
        const companyInfo = ref<CompanyInfoData | null>(null);
        // 获取公司信息
        const getCompanyInfo = async (): Promise<CompanyInfoData | null> => {
            try {
                const { data } = await useClientRequest.get(`/app/company/currentCpyDetail`);
                companyInfo.value = data;
                return data;
            } catch (error) {
                console.error('获取公司信息失败:', error);
                return null;
            }
        };
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        // 微信小程序登录获取的code

        const wxLogin = async (data: unknown) => {
            const res = await useClientRequest.post(`/plt-api/auth/login`, data, false);
            setToken(res.data?.access_token);
        };
        return {
            token,
            setToken,
            removeToken,
            isTokenExpired,
            getTokenRemainingTime,
            userInfo,
            getUserInfo,
            clearUserInfo,
            companyInfo,
            getCompanyInfo,
            wxLogin,
        };
    },
    {
        // 启用持久化，但只持久化 userInfo，其中token使用自定义的带过期时间的存储逻辑
        persist: {
            key: INFOSTORE_KEY,
            storage: uniStorage,
            pick: ['userInfo', 'companyInfo'],
        },
    }
);
