<template>
    <view class="page-content relative">
        <large-header mode="light" :full-height="80" :title="title" :scroll-top="scrollTop"/>
        <view class="mx-20 py-20 bg-white mx-card overflow-hidden">
            <college-item :item="detail.baseInfo" reverse @tag="handleDoublePopup"/>
            <uv-line margin="5px 0 10px 0"/>
            <college-detail-summary :college="detail.baseInfo" @star="handleStarPopup"/>
        </view>
        <view class="m-20 p-20 bg-white mx-card overflow-hidden">
            <index-title-wrap title="测算结果" bold>
                <template #more>
                    <uv-tags shape="circle" plain plain-fill :text="result.majorName"/>
                </template>
            </index-title-wrap>
            <view v-if="result.majorGroup" class="text-sm text-main mt-10">
                专业组：
                <text class="text-primary-light">{{ result.majorGroup }}</text>
            </view>
            <view v-if="result.majorDirection" class="text-sm text-main mt-10">
                专业方向：
                <text class="text-primary-light">{{ result.majorDirection }}</text>
            </view>
            <view class="mt-30 p-30 fx-row fx-bet-cen gap-30 text-main text-xs rounded-lg bg-sky-50">
                <view class="leading-6">
                    根据
                    <text class="text-success font-bold">{{ safeYear }}</text>
                    年该校录取情况，
                    预估考取本专业需要职业技能分：
                </view>
                <view class="fx-row keep-all items-baseline">
                    <view class="text-4xl font-bold text-primary mr-5">
                        <template v-if="safeImprove.valid">{{ safeImprove.value }}</template>
                        <uv-icon v-else size="24" name="question-circle" color="primary" @click="handleFailed"/>
                    </view>
                    分
                </view>
            </view>
            <view class="mt-30 text-main text-xs">
                <view class="mb-15">录取公式：</view>
                <view class="bg-slate-100 rounded-lg p-30 text-primary">
                    <template v-for="(r,i) in enrollRules">
                        <view>{{ r.content }}</view>
                        <uv-line v-if="i<enrollRules.length-1" dashed margin="8px 0 8px 0"/>
                    </template>
                    <text v-if="!enrollRules.length">无</text>
                </view>
            </view>
            <view v-if="otherRules.length" class="mt-30 text-main text-xs">
                <view class="mb-15">院校要求：</view>
                <view class="bg-slate-100 rounded-lg p-30 text-primary">
                    <template v-for="(r, i) in otherRules">
                        <view class="rule-item">{{ r.content }}</view>
                        <uv-line v-if="i<otherRules.length-1" dashed margin="8px 0 8px 0"/>
                    </template>
                </view>
            </view>
        </view>
        <view class="m-30 fx-row fx-bet-cen gap-30">
            <uv-button :icon="collected?'heart-fill':'heart'" icon-color="primary" size="large"
                       shape="circle" type="primary" plain class="!flex-2" text="收藏" @click="handleToggle"/>
            <uv-button icon="eye" icon-color="white" size="large" shape="circle" type="primary" class="!flex-3"
                       text="查看院校详情" @click="goCollegeDetail"/>
        </view>
        <mx-popup-template ref="popup" v-bind="popupBinding"/>
    </view>
</template>

<script>
import {ref, computed} from 'vue';
import _ from 'lodash';
import {useTransfer} from "@/hooks/useTransfer";
import {useCacheStore} from "@/hooks/useCacheStore";
import {useProvidePageScroll} from "@/hooks/usePageScrollInjection";
import {findTreeNode} from "@/utils/tree-helper";
import {postCalculateResult} from "@/api/webApi/ie-voluntary";
import {cacheActions} from "@/hooks/defineCacheActions";
import {universityDetail} from "@/api/webApi/collegemajor";
import LargeHeader from "@/pages/ie/components/large-header.vue";
import CollegeItem from "@/pages/college-library/components/college-item.vue";
import CollegeDetailSummary from "@/pages/college-library/components/college-detail-summary.vue";
import {useCollegeCollectionService} from "@/pages/college-library/components/useCollegeCollectionService";
import mxConfig from "@/common/mxConfig";
import {object} from "@/uni_modules/uv-ui-tools/libs/function/test";
import IndexTitleWrap from "@/pages/index/components/index-title-wrap.vue";
import MxConst from "@/common/mxConst";
import {alertAsync} from "@/utils/uni-helper";

export default {
    components: {IndexTitleWrap, CollegeDetailSummary, CollegeItem, LargeHeader},
    data() {
        return {
            loading: false,
            title: '测职业技能分',
            majorTree: [],
            result: {}
        };
    },
    setup() {
        const {prevData, transferTo} = useTransfer()
        const {dispatchCache} = useCacheStore()
        const scrollTop = useProvidePageScroll()

        const detail = ref({})
        const collegeRef = computed(() => detail.value?.baseInfo || {})
        const {collected, handleToggle} = useCollegeCollectionService(collegeRef)

        const popup = ref(null)
        const popupType = ref('')
        const popupConfig = mxConfig.collegeDetailPopups
        const popupBinding = computed(() => {
            let cfg = popupConfig[popupType.value]
            if (!cfg && object(popupType.value)) cfg = popupType.value
            return {
                ...cfg,
                left: '',
                right: '我知道了',
                onRight: () => popup.value.close()
            }
        })

        const handleDoublePopup = () => {
            popupType.value = 'double'
            popup.value.open()
        }
        const handleStarPopup = () => {
            popupType.value = 'star'
            popup.value.open()
        }

        const goCollegeDetail = () => {
            const {code} = collegeRef.value
            transferTo('/pages/college-library/detail/detail', {code})
        }

        return {
            prevData,
            scrollTop,
            dispatchCache,
            detail,
            collected,
            handleToggle,
            popup,
            popupBinding,
            handleDoublePopup,
            handleStarPopup,
            goCollegeDetail
        }
    },
    computed: {
        major() {
            return findTreeNode(this.majorTree, m => m.code == this.prevData.majorCode) || {}
        },
        enrollRules() {
            return this.result?.improves?.filter(r => r.type == MxConst.enum.ai.ruleType.scoreTotal) || []
        },
        otherRules() {
            return this.result?.rules?.filter(r => r.type != MxConst.enum.ai.ruleType.scoreTotal) || []
        },
        safeImprove() {
            return _.first(this.enrollRules) || {}
        },
        safeYear() {
            return this.safeImprove.year || _.first(this.result.histories)?.year
        }
    },
    provide() {
        return {
            getPrevData: () => this.prevData,
            getDetail: () => this.detail,
            getMajorTree: () => this.majorTree,
            getMajor: () => this.major,
            getResult: () => this.result
        }
    },
    async mounted() {
        // wait for transfer mixin work completed.
        this.loading = true
        try {
            await this.loadReport();
            await this.loadData();
        } finally {
            this.loading = false
        }
    },
    methods: {
        async loadReport() {
            const res = await postCalculateResult(this.prevData)
            this.result = res.data
        },
        async loadData() {
            this.majorTree = await this.dispatchCache(cacheActions.getMajorTree)

            const payload = {code: this.prevData.universityCode}
            const res = await this.dispatchCache(universityDetail, payload)
            this.detail = res.data
        },
        handleFailed() {
            alertAsync(this.safeImprove.failedMessage || '无法计算')
        }
    }
}
</script>

<style lang="scss" scoped>
.page-content {
    background-image: url("~@/static/ie/entry/bg-calculate-full.png");
    background-repeat: no-repeat;
    background-size: contain;
}
</style>
