import {
    defineStore
} from 'pinia';
import {
    ref
} from 'vue'
import {
    createRequest
} from '@/utils/request';
import similarityJobs from '@/utils/similarity_Job.js';
import {
    UUID
} from "@/lib/uuid-min.js";
import {
    useReadMsg
} from '@/stores/useReadMsg';

// 简历完成度计算
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 resume = ref({})
    const Completion = ref('0%')
    const seesionId = ref(uni.getStorageSync('seesionId') || '')

    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 = ''
        resume.value = {}
        userInfo.value = {}
        role.value = {}
        uni.removeStorageSync('userInfo')
        uni.removeStorageSync('token')
        
        // 如果需要显示登录弹窗，则通过事件通知页面显示微信登录弹窗
        if (showLoginModal) {
            // 通过 uni.$emit 发送全局事件，通知页面显示登录弹窗
            uni.$emit('showLoginModal');
        }
    }

    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(() => reject());
        })
    }

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

    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');
        if (cachedUserInfo && cachedToken) {
            userInfo.value = cachedUserInfo;
            resume.value = cachedUserInfo;
            token.value = cachedToken;
            hasLogin.value = true;
            Completion.value = getResumeCompletionPercentage(cachedUserInfo);
            return true;
        }
        return false;
    }

    // 导入
    return {
        hasLogin,
        userInfo,
        token,
        resume,
        login,
        logOut,
        loginSetToken,
        getUserResume,
        initSeesionId,
        seesionId,
        Completion,
        restoreUserInfo
    }
})

export default useUserStore;