import { computed, ref, watch, inject } from 'vue';
import { defineStore, storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import { getProfessions, getRecommend, getSkillTags } from '@/apiRc/service/careerRecommendation';


export const useCareerRecommendationStore = defineStore('career-recommendation', () => {
    const { navTo } = inject('globalFunction');
    const { userInfo: ui } = storeToRefs(useUserStore());
    const userInfo = ref({
        userName: '',
        professions: [],
        skills: []
    });

    watch(() => ui.value, () => {
        if (!ui.value) {
            return;
        }
        try {
            const { jobTitle, appSkillsList } = ui.value;

            userInfo.value.professions = jobTitle.map((d) => {
                return {
                    label: d,
                    value: d
                };
            });
            userInfo.value.skills = appSkillsList.map((d) => {
                return {
                    label: d.name,
                    value: d.name
                };
            });
        } catch (e) {
            console.warn(e);
        }
    }, {
        immediate: true,
        deep: true
    });

    const professionIndex = ref(0);
    const profession = ref('');
    const professionLabel = ref('');
    const professions = ref([]);
    const professionsRef = computed(() => {
        if (!userInfo.value || !userInfo.value.professions || userInfo.value.professions.length === 0) {
            return professions.value;
        }
        const userProfessionsLabels = userInfo.value.professions.map((d) => d.label);
        let professionsA = [];
        let professionsB = [];
        professions.value.filter((d) => userProfessionsLabels.includes(d.label));
        for (const d of professions.value) {
            if (userProfessionsLabels.includes(d.label)) {
                professionsA.push(d);
            } else {
                professionsB.push(d);
            }
        }
        if (professionsA.length === 0) {
            professionsA = userInfo.value.professions;
            professionsB = professions.value;
        }
        return [ ...professionsA, ...professionsB ];
    });

    const skills = ref([]);
    const skillTags = computed(() => {
        if (userInfo.value.professions[ 0 ] && professionLabel.value === userInfo.value.professions[ 0 ].value) {
            return userInfo.value.skills.map((d) => d.label);
        }
        return skills.value;
    });

    const result = ref([]);

    const fetchData = async () => {
        try {
            const { code, msg, data } = await getProfessions();
            if (code !== 200) {
                uni.showToast({
                    title: msg,
                    icon: 'none'
                });
                return;
            }
            if (!data) {
                return;
            }
            professions.value = data.map((d) => {
                return {
                    label: d.name,
                    value: d.name
                };
            });
        } catch (e) {
            console.warn(e);
        }
    };

    const fetchSkillTags = async () => {
        const params = {
            jobName: professionLabel.value
        };
        try {
            const { code, msg, data } = await getSkillTags(params);
            if (code !== 200) {
                uni.showToast({
                    title: msg,
                    icon: 'none'
                });
                return;
            }
            if (typeof data !== 'undefined' && Array.isArray(data) && data.length > 0 && data[ 0 ]) {
                skills.value = data[ 0 ].skillDetList.map((d) => d.skillName);
            }
        } catch (e) {
            console.warn(e);
        }
    };

    const fetchRecommend = async () => {
        const params = {
            jobName: professionLabel.value
        };
        try {
            const { code, msg, data } = await getRecommend(params);
            if (code !== 200) {
                uni.showToast({
                    title: msg,
                    icon: 'none'
                });
                return;
            }
            if (!data) {
                return;
            }
            result.value = data.map((d) => {
                return {
                    title: d.jobName,
                    tags: d.skillList.map((d) => d.skillName),
                    percentage: d.similarityScore ?? 0
                };
            });
        } catch (e) {
            console.warn(e);
        }
    };

    const eventSearch = () => {
        void fetchRecommend();
    };

    const eventProfession = (e) => {
        professionIndex.value = Number(e.detail.value);
        const item = professionsRef.value[ e.detail.value ];
        profession.value = item.value;
        professionLabel.value = item.label;
    };

    void fetchData();

    const eventJobSearch = (job) => {
        console.log(job);
        navTo('/pages/search/search?job=' + job.title);
    };

    watch(
        () => profession.value,
        () => {
            if (profession.value) {
                void fetchSkillTags();
                result.value = [];
            }
        },
        {
            immediate: true
        }
    );

    watch(
        () => professionsRef.value,
        () => {
            if (professionsRef.value[ 0 ]) {
                profession.value = professionsRef.value[ 0 ].value;
                professionLabel.value = professionsRef.value[ 0 ].label;
            }
        }
    );

    return {
        professionIndex,
        profession,
        professionLabel,
        professionsRef,
        skillTags,
        result,
        eventProfession,
        eventSearch,
        eventJobSearch
    };
});
