import { computed, ref, watch } from 'vue';
import { defineStore, storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import { getCurrentPosition, getPath } from '@/apiRc/service/careerPath';
import { getCareerPath, getSkillResult } from '@/apiRc/service/skillDevelopment';


export const useSkillDevelopmentStore = defineStore('skill-development', () => {
    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 targetCareerIndex = ref(0);
    const targetCareer = ref('');
    const targetCareerLabel = ref('');
    const paths = ref([]);
    const pathsRef = computed(() => {
        return paths.value.filter((d) => {
            const [startJobId] = d.value.split('-');
            return startJobId === profession.value;
        });
    });

    const careerPaths = ref([]);
    const currentCareer = ref(null);
    const currentCareerIndex = ref(0);
    const currentCareerLabel = computed(() => {
        if (!currentCareer.value) {
            return '';
        }
        return currentCareer.value.label;
    });

    const result = ref([]);

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

    const fetchDataPath = async () => {
        try {
            const { code, msg, data } = await getPath();
            if (code !== 200) {
                uni.showToast({
                    title: msg,
                    icon: 'none'
                });
                return;
            }
            if (!data) {
                return;
            }
            paths.value = data.map((d) => {
                return {
                    label: d.endJob,
                    value: `${d.startJobId}-${d.endJobId}`

                };
            });
        } catch (e) {
            console.warn(e);
        }
    };

    const fetchCareerPaths = async () => {
        if (!targetCareer.value) {
            return;
        }
        const [startJobId, endJobId] = targetCareer.value.split('-');
        const params = {
            startJobId,
            endJobId
        };
        try {
            const { code, msg, data } = await getCareerPath(params);
            if (code !== 200) {
                uni.showToast({
                    title: msg,
                    icon: 'none'
                });
                return;
            }
            if (!data) {
                return;
            }
            careerPaths.value = data.map((d, i) => {
                let index = `${i}`;
                let fontSize = 26;
                if (i === 0) {
                    index = '起点';
                    fontSize = 18;
                }
                if (i === data.length - 1) {
                    index = '终点';
                    fontSize = 18;
                }
                return {
                    index,
                    label: d.name,
                    value: d.jobId,
                    fontSize
                };
            });
            if (careerPaths.value[0]) {
                void eventResult(0);
            }
        } catch (e) {
            console.warn(e);
            careerPaths.value = [];
        }
    };

    const eventResult = async (index) => {
        currentCareerIndex.value = index;
        currentCareer.value = careerPaths.value[index] ?? null;

        const params = {
            jobId: currentCareer.value?.value
        };
        try {
            const { code, msg, data } = await getSkillResult(params);
            if (code !== 200) {
                uni.showToast({
                    title: msg,
                    icon: 'none'
                });
                return;
            }
            if (!data) {
                return;
            }
            result.value = data.map((d) => {
                return {
                    label: d.secDimName,
                    value: d.secDimId,
                    children: d.skillDetList.map((d) => {
                        return {
                            label: d.skillName,
                            value: d.skillScore,
                            weight: d.skillWeight
                        };
                    })
                };
            });
        } catch (e) {
            console.warn(e);
        }
    };

    const eventSearch = () => {
        if (pathsRef.value.length === 0) {
            uni.showToast({
                title: '当前职业暂无发展路径，敬请期待！',
                icon: 'none'
            });
            return;
        }
        if (!profession.value) {
            uni.showToast({
                title: '请选择当前职位！',
                icon: 'none'
            });
            return;
        }
        if (!targetCareer.value) {
            uni.showToast({
                title: '请选择目标职业！',
                icon: 'none'
            });
            return;
        }
        void fetchCareerPaths();
    };

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

    const eventTargetCareer = (e) => {
        targetCareerIndex.value = Number(e.detail.value);
        const item = pathsRef.value[ e.detail.value ];
        targetCareer.value = item.value;
        targetCareerLabel.value = item.label;
        careerPaths.value = [];
        result.value = [];
    };

    void fetchData();
    void fetchDataPath();

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

    return {
        professionIndex,
        professionLabel,
        profession,
        professionsRef,
        targetCareerIndex,
        targetCareer,
        targetCareerLabel,
        pathsRef,
        careerPaths,
        currentCareer,
        currentCareerLabel,
        currentCareerIndex,
        result,
        eventProfession,
        eventTargetCareer,
        eventSearch,
        eventResult
    };
});
