import {
    defineStore
} from 'pinia';
import {
    ref
} from 'vue'
import {
    createRequest,
    isEncryptNeeded,
    encryptRequestData,
    handleResponseData
} from '@/utils/request';
import similarityJobs from '@/utils/similarity_Job.js';
import {
    UUID
} from "@/lib/uuid-min.js";
import {
    useReadMsg
} from '@/stores/useReadMsg';
import { sm4Decrypt } from '@/utils/crypto';
import config from "@/config.js";

// 简历完成度计算
function getResumeCompletionPercentage(resume) {
    const requiredFields = [
        'name',
        'age',
        'sex',
        'birthDate',
        'education',
        'politicalAffiliation',
        'phone',
        'salaryMin',
        'salaryMax',
        'area',
        'status',
        'jobTitleId',
        'jobTitle',
    ];

    const totalFields = requiredFields.length;
    let filledFields = requiredFields.filter((field) => {
        const value = resume[field];
        return value !== null && value !== '' && !(Array.isArray(value) && value.length === 0);
    }).length;

    return ((filledFields / totalFields) * 100).toFixed(0) + '%';
}

const useUserStore = defineStore("user", () => {
    // 定义状态
    const hasLogin = ref(false)
    // const openId = ref('')
    const userInfo = ref({});
    const role = ref({});
    const token = ref('')
    const refreshToken = ref('')
    const loginTime = ref(0)
    const resume = ref({})
    const Completion = ref('0%')
    const seesionId = ref(uni.getStorageSync('seesionId') || '')
    const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000

    const login = (value) => {
        hasLogin.value = true;
        userInfo.value = value;
        openId.value = value.wxOpenId;
        token.value = value.token;
        uni.setStorage({
            key: 'token',
            data: value.token
        });
    }

    const logOut = (showLoginModal = true) => {
        hasLogin.value = false;
        token.value = ''
        refreshToken.value = ''
        loginTime.value = 0
        resume.value = {}
        userInfo.value = {}
        role.value = {}
        uni.removeStorageSync('userInfo')
        uni.removeStorageSync('token')
        uni.removeStorageSync('refreshToken')
        uni.removeStorageSync('loginTime')
        uni.removeStorageSync('Padmin-Token')
        // 如果需要显示登录弹窗，则通过事件通知页面显示微信登录弹窗
        // if (showLoginModal) {
        //     // 通过 uni.$emit 发送全局事件，通知页面显示登录弹窗
        //     uni.$emit('showLoginModal');
        // }
        //#ifdef H5
        // 跳转到首页
        window.location.href = 'https://www.xjksly.cn/mechine-single-vue/';
        //#endif
         uni.reLaunch({
            url: '/pages/index/index'
        });
    }

    const getUserInfo = () => {
        return new Promise((reslove, reject) => {
            createRequest('/getInfo', {}, 'get').then((userInfo) => {
                setUserInfo(userInfo);
                reslove(userInfo)
            });
        })
    }

    const getUserResume = () => {
        return new Promise((reslove, reject) => {
            createRequest('/app/user/resume', {}, 'get').then((resume) => {
                Completion.value = getResumeCompletionPercentage(resume.data)
                similarityJobs.setUserInfo(resume.data)
                setUserInfo(resume);
                reslove(resume)
            }).catch((error) => {
                // 对于企业用户，简历接口可能失败，但这不应该阻止登录流程
                // 记录错误但不reject，让登录流程继续
                console.warn('获取简历信息失败，可能是企业用户或无简历信息:', error);
                // 返回一个空的简历对象，让登录流程继续
                reslove({ data: {} });
            });
        })
    }

    const loginSetToken = async (value) => {
        token.value = value
        uni.setStorageSync('token', value);
        // 获取消息列表
        // useReadMsg().fetchMessages()
        // 获取用户信息
        return getUserResume()
    }

    const setRefreshToken = (refreshTokenVal) => {
        refreshToken.value = refreshTokenVal
        uni.setStorageSync('refreshToken', refreshTokenVal)
    }

    const setLoginTime = (time) => {
        loginTime.value = time
        uni.setStorageSync('loginTime', time.toString())
    }

    const isLoginExpired = () => {
        if (!loginTime.value) {
            const storedTime = uni.getStorageSync('loginTime')
            if (storedTime) {
                loginTime.value = parseInt(storedTime)
            }
        }
        if (!loginTime.value) return true
        return Date.now() - loginTime.value > SEVEN_DAYS
    }

    const refreshAccessToken = async () => {
        if (isLoginExpired()) {
            logOut(false)
            return Promise.reject(new Error('登录已过期'))
        }

        const storedRefreshToken = uni.getStorageSync('refreshToken') || refreshToken.value
        if (!storedRefreshToken) {
            logOut(false)
            return Promise.reject(new Error('没有刷新token'))
        }

        return new Promise((resolve, reject) => {
            // console.log('[refreshToken]  开始刷新 token, refreshToken:', storedRefreshToken)
            const requestUrl = config.baseUrl + '/refreshToken?refreshToken=' + encodeURIComponent(storedRefreshToken)
            // console.log('[refreshToken]  请求地址:', requestUrl)
            
            uni.request({
                url: requestUrl,
                method: 'GET',
                success: (resData) => {
                    console.log('[refreshToken]  原始响应:', JSON.stringify(resData))
                    if (resData.statusCode === 200) {
                        let responseData = handleResponseData(resData.data)
                        // console.log('[refreshToken]  解密后数据:', JSON.stringify(responseData))
                        const { code, msg, token: newToken } = responseData
                        if (code === 200 && newToken) {
                            token.value = newToken
                            uni.setStorageSync('token', newToken)
                            resolve(newToken)
                        } else if (code === 401) {
                            logOut(false)
                            reject(new Error(msg || '认证失败'))
                        } else {
                            logOut(false)
                            reject(new Error(msg || '刷新token失败'))
                        }
                    } else {
                        logOut(false)
                        reject(new Error('网络请求失败'))
                    }
                },
                fail: (err) => {
                    console.error('[refreshToken]  网络请求失败:', JSON.stringify(err))
                    logOut(false)
                    reject(err)
                }
            })
        })
    }

    const setUserInfo = (values) => {
        userInfo.value = values.data;
        resume.value = values.data; // 将用户信息同时存储到resume中
        // role.value = values.role;
        hasLogin.value = true;
        
        // 模拟添加用户类型字段，实际项目中应该从接口获取
        // if (!userInfo.value.userType) {
        //     userInfo.value.userType = 1; // 默认设置为求职者用户
        // }
        
        // 持久化存储用户信息到本地缓存
        uni.setStorageSync('userInfo', values.data);
    }


    const tokenlogin = (token) => {
        createRequest('/app/login', {
            token
        }).then((resData) => {
            onsole.log(resData)
        })
    }

    const initSeesionId = () => {
        const seesionIdVal = UUID.generate()
        uni.setStorageSync('seesionId', seesionIdVal);
        seesionId.value = seesionIdVal
    }

    // 从本地缓存恢复用户信息
    const restoreUserInfo = () => {
        const cachedUserInfo = uni.getStorageSync('userInfo');
        const cachedToken = uni.getStorageSync('token');
        const cachedRefreshToken = uni.getStorageSync('refreshToken');
        const cachedLoginTime = uni.getStorageSync('loginTime');
        if (cachedUserInfo && cachedToken) {
            userInfo.value = cachedUserInfo;
            resume.value = cachedUserInfo;
            token.value = cachedToken;
            refreshToken.value = cachedRefreshToken || '';
            loginTime.value = cachedLoginTime ? parseInt(cachedLoginTime) : 0;
            hasLogin.value = true;
            Completion.value = getResumeCompletionPercentage(cachedUserInfo);
            return true;
        }
        return false;
    }

    // 导入
    return {
        hasLogin,
        userInfo,
        token,
        refreshToken,
        loginTime,
        resume,
        login,
        logOut,
        loginSetToken,
        setRefreshToken,
        setLoginTime,
        isLoginExpired,
        refreshAccessToken,
        getUserResume,
        initSeesionId,
        seesionId,
        Completion,
        restoreUserInfo
    }
})

export default useUserStore;