<template>
    <num-common-card :num="num">
        <template #header>
            <view v-if="model.university.code" class="fx-row flex-1">
                <college-item :item="model.university" hidden-logo hidden-address class="flex-1"/>
                <horizontal-button :id="collegePickerId" icon="share-square" text="修改" @click="openCollegePicker"/>
            </view>
            <view v-else class="p-20">
                <uv-button size="small" :id="collegePickerId" type="primary" plain text="添加院校" icon="plus"
                           icon-color="primary" @click="openCollegePicker"/>
            </view>
        </template>
        <view class="fx-col px-20 pb-30" :id="majorPickerId">
            <uv-cell v-for="idx in 4" :key="idx" :title="`专业 `+idx" is-link @click="openMajorPicker">
                <template #value>
                    <text v-if="!model.majors[idx-1]" class="text-light">请选择专业</text>
                    <view v-else class="text-primary fx-col items-end">
                        <text>{{ model.majors[idx - 1].name }}</text>
                        <text class="text-primary-light text-2xs">{{ model.majors[idx - 1].majorDirection }}</text>
                    </view>
                </template>
            </uv-cell>
        </view>
        <view class="px-20 pb-30">
            <ai-form ref="aiForm" :model="model" :id-prefix="model.num" :render-rules="renderRules"
                     :render-rule-loading="renderRuleLoading"/>
        </view>
        <major-picker ref="majorPicker" :university-code="model.university.code" :majors="model.majors"
                      :limit="majorLimit" :major-category="form.majorCategory" @confirm="confirmMajors"/>
    </num-common-card>
</template>

<script>
import {computed, ref, watch} from 'vue';
import _ from 'lodash';
import MajorPicker from "@/pagesOther/pages/ie/components/picker/major-picker.vue";
import NumCommonCard from "@/pagesOther/pages/ie/entry-analysis/components/num-common-card.vue";
import HorizontalButton from "@/pagesOther/pages/ie/components/horizontal-button.vue";
import CollegeItem from "@/pagesOther/pages/college-library/components/college-item.vue";
import AiForm from "@/pagesOther/pages/ie/components/ai-form/ai-form.vue";
import MxConst from "@/common/MxConst";
import {confirmAsync} from "@/utils/uni-helper";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {useAIRenderRules} from "@/pagesOther/pages/ie/hooks/useAIRenderRules";
import {useTransfer} from "@/hooks/useTransfer";
import {useInjectAnalysisDataService} from "@/pagesOther/pages/ie/entry-analysis/components/useAnalysisDataInjection";

export default {
    name: "college-major-picker",
    components: {CollegeItem, AiForm, HorizontalButton, NumCommonCard, MajorPicker},
    props: {
        num: {
            type: Number,
            default: 0
        },
        majorLimit: {
            type: Number,
            default: 4
        }
    },
    setup(props) {
        const {form} = useInjectAnalysisDataService()
        const lessMajorConfirmed = ref(false)
        const model = computed(() => form.value.universities[props.num])
        const majorCodes = computed(() => model.value.majors.map(m => m.code))
        const majorEnrollCodes = computed(() => model.value.majors.map(m => m.enrollCode))
        const aiForm = ref(null)
        const majorPicker = ref(null)

        const paramFactory = () => {
            const codes = majorCodes.value.sort()
            const enrollCodes = majorEnrollCodes.value.sort()
            if (!codes.length || !enrollCodes.length) return null
            return {
                renderType: MxConst.enum.ai.renderType.def,
                universityCode: model.value.university.code,
                majorCodes: codes,
                majorEnrollCodes: enrollCodes
            }
        }
        const {
            renderRules,
            renderRuleLoading,
            reloadRenderRules,
            validateRenderRule
        } = useAIRenderRules(paramFactory)
        const {transferTo, onPageCallback} = useTransfer()

        const pickerExcepts = computed(() => {
            return form.value.universities
                .filter(m => m != model.value)
                .map(m => m.university?.code)
                .filter(c => c)
        })
        const collegePickerId = computed(() => 'picker_college_' + props.num)
        const majorPickerId = computed(() => 'picker_major_' + props.num)

        const openCollegePicker = () => {
            if (!form.value.majorCategory) return toast('请先选择专业种类')
            const next = {
                majorCategory: form.value.majorCategory,
                excepts: pickerExcepts.value,
                callback: MxConst.globalEvents.collegeSelected
            }
            transferTo('/pagesOther/pages/college-library/picker/picker', next)
        }
        const openMajorPicker = () => {
            if (!model.value.university.code) return toast('请先添加院校')
            majorPicker.value.open()
        }

        const confirmMajors = (e) => {
            model.value.majors = e || []
        }

        const scrollToSelf = (id) => {
            const dom = document.getElementById(id)
            if (dom) dom.scrollIntoView(MxConst.scrollIntoOption)
        }

        const validate = async () => {
            if (!model.value.university?.code) {
                const err = `请给志愿${model.value.num + 1}添加院校`
                toast(err)
                scrollToSelf(collegePickerId.value)
                return Promise.reject(err)
            }
            if (!model.value.majors?.length) {
                const err = `请给志愿${model.value.num + 1}添加专业`
                toast(err)
                scrollToSelf(majorPickerId.value)
                return Promise.reject(err)
            }
            if (model.value.majors.length < props.majorLimit && !lessMajorConfirmed.value) {
                try {
                    await confirmAsync(`志愿${model.value.num + 1}选择的专业不足${props.majorLimit}个，是否继续？！`)
                    lessMajorConfirmed.value = true
                } catch (e) {
                    scrollToSelf(majorPickerId.value)
                    return Promise.reject(e)
                }
            }
            await validateRenderRule()
            return aiForm.value.validate()
        }

        onPageCallback((college) => {
            if (!college) return
            if (model.value.university?.code == college.code) return
            model.value.university = college
            model.value.majors = [] // reset majors
            renderRules.value = []
            lessMajorConfirmed.value = false
        })
        watch(() => form.value.majorCategory, () => {
            model.value.university = {}
            model.value.majors = []
            renderRules.value = []
        })
        watch(() => majorEnrollCodes.value.sort().toString(), () => {
            renderRules.value = []
            reloadRenderRules()
        })

        return {
            aiForm,
            majorPicker,
            form,
            model,
            lessMajorConfirmed,
            collegePickerId,
            majorPickerId,
            renderRules,
            renderRuleLoading,
            openCollegePicker,
            openMajorPicker,
            confirmMajors,
            validate
        }
    }
}
</script>

<style scoped lang="scss">
</style>