<script>
import _ from 'lodash';
import EntryAiReport from "@/pagesOther/pages/ie/entry-ai-report/entry-ai-report.vue";
import {getVoluntary} from "@/api/webApi/ie-voluntary";
import {useProvideTransfer} from "@/hooks/useTransfer";
import {useProvidePageScroll} from "@/hooks/usePageScrollInjection";
import {useCacheStore} from "@/hooks/useCacheStore";
import {useProvideMajorTreeService} from "@/pagesOther/pages/ie/hooks/useMajorTreeInjection";
import {universityDetail} from "@/api/webApi/collegemajor";

export default {
    extends: EntryAiReport,
    setup() {
        const {prevData, usingCacheTransfer} = useProvideTransfer()
        const scrollTop = useProvidePageScroll()
        const {dispatchCache} = useCacheStore()
        const {majorTree} = useProvideMajorTreeService()

        return {
            scrollTop,
            prevData,
            usingCacheTransfer,
            majorTree,
            dispatchCache
        }
    },
    methods: {
        async prevInit() {
            let reAssignData = this.prevData
            if (!this.usingCacheTransfer && this.prevData.id) {
                const {data} = await getVoluntary(this.prevData)
                reAssignData = data
            }
            await this.transferToAiStructure(reAssignData)
            this.prevData = {...reAssignData} // NOTE: This will trigger watcher in `EntryAiReport`. Important!
        },
        async transferToAiStructure(multipleData) {
            // transfer to ai report structure, only `details` part.
            const aiDetails = []
            const uGrouped = _.groupBy(multipleData.details, r => r.universityCode)
            const tasks = Object.entries(uGrouped).map(async ([code, majorDetails]) => {
                const u = await this.dispatchCache(universityDetail, {code})
                aiDetails.push({
                    university: u.data.baseInfo,
                    professions: u.data.professions,
                    majorDetails
                })
            })

            await Promise.all(tasks)
            multipleData.details = aiDetails
        }
    }
}
</script>

<style>

</style>
