<template>
    <z-paging ref="paging" v-model="list" :auto="false" :height="safeScrollHeight" auto-show-system-loading
              @query="handleQuery">
        <template #top>
            <slot name="top"/>
            <mx-condition-dropdown ref="dropdown" x layout="fx-row items-center gap-20 w-max"/>
        </template>
        <voluntary-search @search="handleSearch"/>
        <view class="fx-col p-20 gap-20">
            <voluntary-item v-for="item in list" :item="item" @major="openMajorPopup(item)" @notify="showNotify"/>
            <vip-guide-more v-if="isNotVip"/>
        </view>
        <template #bottom>
            <voluntary-bottom @modify="$refs.modifyPopup.open()" @cart="$refs.cartPopup.open()"/>
        </template>
    </z-paging>
    <!--  这里渲染的弹窗不会被back-to-top遮挡  -->
    <score-batch-popup ref="modifyPopup"/>
    <voluntary-cart-popup ref="cartPopup"/>
    <major-popup ref="majorPopup" @notify="showNotify"/>
    <uv-notify ref="notifier"/>
</template>

<script setup>
import {computed, ref, watch} from 'vue';
import {toValue} from "@vueuse/core";
import {createPropDefine} from "@/utils";
import {sleep} from "@/uni_modules/uv-ui-tools/libs/function";
import {getRecommendVoluntary, getVoluntaryMarjors} from "@/api/webApi/volunteer";
import {useUserStore} from "@/hooks/useUserStore";
import {useInjectVoluntaryForm} from "@/pages/voluntary/hooks/useVoluntaryFormInjection";
import {useInjectVoluntaryAssistant} from "@/pages/voluntary/hooks/useVoluntaryAssistantInjection";
import {useInjectVoluntaryStep} from "@/pages/voluntary/hooks/useVoluntaryStepInjection";
import {useInjectVoluntaryHeader} from "@/pages/voluntary/hooks/useVoluntaryHeaderInjection";
import {useVoluntaryMajorGroupIdentifier} from "@/pages/voluntary/hooks/useVoluntaryMajorGroupIdentifier";
import {useInjectVoluntaryCart} from "@/pages/voluntary/hooks/useVoluntaryCartInjection";
import VoluntaryItem from "@/pages/voluntary/index/components/voluntary-item.vue";
import VoluntaryBottom from "@/pages/voluntary/index/components/voluntary-bottom.vue";
import MajorPopup from "@/pages/voluntary/index/components/major-popup.vue";
import ScoreBatchPopup from "@/pages/voluntary/index/components/score-batch-popup.vue";
import VoluntaryCartPopup from "@/pages/voluntary/index/components/voluntary-cart-popup.vue";
import VoluntarySearch from "@/pages/voluntary/index/components/voluntary-search.vue";
import {useProvideVoluntarySearch} from "@/pages/voluntary/hooks/useVoluntarySearchInjection";

const props = defineProps({
    editMode: createPropDefine(false, Boolean)
})

const paging = ref(null)
const notifier = ref(null)
const majorPopup = ref(null)
const cartPopup = ref(null)
const dropdown = ref(null)
const {currentUser, GetInfo, isBind} = useUserStore()
const {model, batch, mode} = useInjectVoluntaryForm()
const {currentStep} = useInjectVoluntaryStep()
const {
    resetCart, total, list, selectedList,
    syncMajorGroupToSelected, syncMajorsToSelectedGroup
} = useInjectVoluntaryCart()
const {scrollHeight, onBeforeBack, save} = useInjectVoluntaryAssistant() // 填报页下面有原生tabs，必须手动设置高度
const {isMock, ensureHistoryYears} = useInjectVoluntaryHeader()

const {formatQueryParams, onSearch, reset: resetCondition} = useProvideVoluntarySearch()

const safeScrollHeight = computed(() => scrollHeight ? toValue(scrollHeight) + 'px' : undefined)
const isNotVip = computed(() => {
    return !toValue(isBind) && toValue(total) > 1
})

const showNotify = (message) => {
    const msg = message || '未发布详细的征集信息'
    notifier.value.show({
        message: msg,
        type: 'warning',
        top: 1
    })
}

const openMajorPopup = (item) => {
    if (item.isExpand) {
        return majorPopup.value.open(item)
    } else {
        item.isExpand = true
        loadMajorDetails(item)
    }
}

const loadMajorDetails = (item) => {
    uni.showLoading()
    getVoluntaryMarjors({
        batchName: toValue(batch).name,
        collegeCode: item.recruitPlan.collegeCode,
        jCode: item.jCode,
        mode: toValue(mode),
        universityId: item.recruitPlan.universityId,
        year: item.recruitPlan.year,
        score: toValue(model).score
    }).then(res => {
        syncMajorsToSelectedGroup(res.data, item)
        item.majors = res.data
        majorPopup.value.open(item)
    }).finally(() => uni.hideLoading())
}


const syncUserScoreByNeed = (query) => {
    const {score, seatInput/*, mode*/} = toValue(currentUser)
    // if query score mode seatInput changed, re-call getInfo.
    if (query.score != score ||
        // query.mode != mode ||
        query.seatInput != seatInput) {
        GetInfo()
    }
}

const handleQuery = async (pageNum, pageSize) => {
    const batchVal = toValue(batch)
    const modelVal = toValue(model)
    const batchData = {
        batchName: batchVal.name,
        batch: batchVal.batch,
        batchMinScore: batchVal.score2 || batchVal.score1
    }
    const modelData = {
        mode: toValue(mode),
        score: modelVal.score,
        seatInput: modelVal.seatInput
    }
    const data = {
        ...batchData,
        ...modelData,
        ...formatQueryParams()
    }
    const res = await getRecommendVoluntary(data, {pageNum, pageSize})

    if (pageNum == 1) syncUserScoreByNeed(data)
    total.value = res.total
    // make reactive properties
    let rows = {}
    rows = res.rows.map(item => {
        item.isExpand = false
        item.majors = []
        return item
    })
    rows.forEach(useVoluntaryMajorGroupIdentifier)
    // 回显
    syncMajorGroupToSelected(rows)
    paging.value.completeByTotal(rows, total.value)
}

const checkPopupBlock = async () => {
    // major popup
    if (majorPopup.value.show) {
        majorPopup.value.close()
        return Promise.reject('popup close')
    }
    if (dropdown.value.getShow()) {
        dropdown.value.terminate()
        return Promise.reject('popup close')
    }
}

const confirmSave = async () => {
    return new Promise((resolve, reject) => {
        uni.showModal({
            content: '是否要保存当前志愿表',
            showCancel: true,
            cancelText: '放弃保存',
            confirmText: '保存志愿表',
            success: res => {
                if (res.confirm) {
                    reject() // to prevent back operation.
                    save(isMock.value)
                } else {
                    resolve() // to continue back operation.
                }
            }
        })
    })
}

const handleSearch = () => paging.value.reload() // 输入框触发
onSearch(() => paging.value.reload()) // 条件选择器触发
onBeforeBack(async () => {
    if (currentStep.value == 2) {
        // 先控制弹层元素 专业详情/条件筛选
        await checkPopupBlock()
        // 再判定志愿表
        if (selectedList.value.length) {
            await confirmSave()
        }
    }
})

const reloadWatches = [
    currentStep,
    () => model.value.score * 1,
    () => model.value.seatInput * 1,
    () => batch.value.batch * 1
]
watch(reloadWatches, async ([step, score, input, batch], arg2) => {
    if (step == 2) {
        if (!props.editMode) resetCart() // 编辑模式下保留cart数据
        cartPopup.value.close()
        majorPopup.value.close()
        dropdown.value.terminate()
        await sleep(400) // wait for animation complete
        resetCondition()
    }
})
watch(currentStep, async (step) => {
    if (step == 2) {
        const payload = {mode: toValue(mode), year: toValue(batch).year, isMock: toValue(isMock)}
        await ensureHistoryYears(payload)
    }
})

defineExpose({checkPopupBlock, confirmSave})
</script>

<style scoped lang="scss">
::v-deep .zp-page-bottom-container {
    z-index: 10;
}
</style>
