<template>
    <z-paging ref="paging" v-model="list" :auto="false" auto-show-system-loading @query="handleQuery">
        <template #top>
            <mx-nav-bar :title="prevData.name"/>
        </template>
        <view class="fx-col gap-20 p-20">
            <voluntary-item v-for="item in list" :item="item" @major="openMajorPopup(item)" @notify="showNotify"/>
        </view>
        <major-popup ref="majorPopup" readonly @notify="showNotify"/>
        <uv-notify ref="notifier"/>
        <template #bottom>
            <mx-bottom-buttons left="编辑" left-type="primary" right="下载" class="h-[60px] px-30 bg-white mx-shadow-up"
                               left-icon="edit-pen" right-icon="download" @left="handleEdit" @right="handleDownload"/>
        </template>
    </z-paging>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {
    downloadRecommendReport,
    getDownloadRecommendReportOptionsForWap2App,
    getRecommendVoluntary,
    getVoluntaryMarjors,
    getZhiyuanDetail,
} from '@/api/webApi/volunteer.js'
import MxConst from '@/common/MxConst'
import MajorPopup from '../index/components/major-popup.vue'
import VoluntaryItem from "../index/components/voluntary-item.vue";
import {useProvideTransfer} from "@/hooks/useTransfer";
import {useVoluntaryMajorGroupIdentifier} from "@/pages/voluntary/hooks/useVoluntaryMajorGroupIdentifier";
import {useProvideVoluntaryMajorHighlight} from "@/pages/voluntary/hooks/useVoluntaryMajorHighlightInjection";
import {useProvideVoluntaryHeader} from "@/pages/voluntary/hooks/useVoluntaryHeaderInjection";
import {useProvideVoluntaryCart} from "@/pages/voluntary/hooks/useVoluntaryCartInjection";
import {useVoluntaryPageDataFormat} from "@/pages/voluntary/hooks/useVoluntaryPageDataFormat";
import {useUserStore} from "@/hooks/useUserStore";
import {alertAsync} from "@/utils/uni-helper";
import {useEnvStore} from "@/hooks/useEnvStore";
import {useDownload} from "@/hooks/useDownload";

const {isWap2App, isH5} = useEnvStore()
const {currentUser, isScoreLocked} = useUserStore()
const {prevData, transferTo, onPageCallback} = useProvideTransfer()
const {downloadBlobFileForWap2app, downloadBlobFile} = useDownload()
const paging = ref(null)
const notifier = ref(null)
const majorPopup = ref(null)

const {resolveFormedMajorsFromSavedData} = useProvideVoluntaryMajorHighlight(true)
const {ensureHistoryYearsFromPageData} = useProvideVoluntaryHeader(true)
const {id, name, total, list} = useProvideVoluntaryCart()

const loadDataById = async (id) => {
    const res = await getZhiyuanDetail(id)
    prevData.value = res.data
    await loadDataByCache()
}

const loadDataByCache = async () => {
    useVoluntaryPageDataFormat(prevData)
    resolveFormedMajorsFromSavedData(prevData.value)
    await ensureHistoryYearsFromPageData(prevData.value)

    // ready for reload voluntary detail data
    paging.value.reload()
}

const handleQuery = (pageNum, pageSize) => {
    const {id, mode, score, batchName} = prevData.value
    const data = {wishResId: id, mode, score, batchName}
    getRecommendVoluntary(data, {pageNum, pageSize}).then(res => {
        const rows = res.rows.map(item => {
            item.isExpand = false
            item.majors = []
            item.selectedCount = 0
            item.recruitPlan = item.recruitPlan || {planCount: '-'}
            useVoluntaryMajorGroupIdentifier(item)
            return item
        })
        paging.value.completeByTotal(rows, res.total)
    }).catch(e => paging.value.complete(false))
}

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()
    const {batchName, mode, id} = prevData.value
    getVoluntaryMarjors({
        batchName: batchName,
        mode: mode,
        wishResId: id,
        collegeCode: item.recruitPlan.collegeCode,
        jCode: item.jCode
    }).then(res => {
        item.majors = res.data.map(item => {
            item.selected = false
            return item
        })
        openMajorPopup(item)
    }).finally(() => uni.hideLoading())
}

const handleEdit = async () => {
    if (isScoreLocked.value) {
        const {score, mode} = currentUser.value
        if (prevData.value.score != score || prevData.value.mode != mode) {
            return alertAsync('现在是志愿填报高峰期，此志愿表与您的考试分数不符，为保证系统稳定性，填报期间您不能修改这张志愿表')
        }
    }
    if (prevData.value.obsoleted) {
        return alertAsync('此志愿表已经过期，不能使用修改功能')
    }
    const next = {...prevData.value, callback: MxConst.globalEvents.voluntaryChanged}
    transferTo('/pages/voluntary/edit/edit', next, null, true)
}

const handleDownload = async () => {
    const {name, score, batchName, id} = prevData.value
    const fileName = `${name}-${score}-${batchName}`
    const params = {wishResId: id}
    if (isWap2App.value) {
        const opt = getDownloadRecommendReportOptionsForWap2App(params)
        downloadBlobFileForWap2app(opt, fileName)
    } else if (isH5.value) {
        const rep = await downloadRecommendReport(params)
        downloadBlobFile(rep, fileName)
    } else {
        console.error('unexpected env, neither wap2app nor h5')
    }
}

onMounted(() => {
    if (prevData.value.id) {
        // This is transferred from creation
        loadDataById(prevData.value.id)
    } else {
        loadDataByCache()
    }
})
onPageCallback((change) => {
    if (change) loadDataById(prevData.value.id)
})
</script>

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