<template>
    <view class="page-content h-screen">
        <cart-step ref="cart" edit-mode>
            <template #top>
                <mx-nav-bar :title="title" :sub-title="name" :left-click-block="confirmBackChange"
                            style="z-index: 20000"/>
            </template>
        </cart-step>
    </view>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {zytbBatches} from '@/api/webApi/volunteer'
import MxConst from "@/common/MxConst";
import {useProvideTransfer} from "@/hooks/useTransfer";
import {useVoluntaryPageDataFormat} from "@/pages/voluntary/hooks/useVoluntaryPageDataFormat";
import {useProvideVoluntaryMajorHighlight} from "@/pages/voluntary/hooks/useVoluntaryMajorHighlightInjection";
import {useProvideVoluntaryStep} from "@/pages/voluntary/hooks/useVoluntaryStepInjection";
import {useProvideVoluntaryHeader} from "@/pages/voluntary/hooks/useVoluntaryHeaderInjection";
import {useProvideVoluntaryData} from "@/hooks/useVoluntaryDataInjection";
import {useProvideVoluntaryCart} from "@/pages/voluntary/hooks/useVoluntaryCartInjection";
import {useProvideVoluntaryForm} from "@/pages/voluntary/hooks/useVoluntaryFormInjection";
import {useProvideVoluntaryAssistant} from "@/pages/voluntary/hooks/useVoluntaryAssistantInjection";
import {useVoluntaryMajorGroupIdentifier} from "@/pages/voluntary/hooks/useVoluntaryMajorGroupIdentifier";
import CartStep from "@/pages/voluntary/index/components/cart-step.vue";

const cart = ref(null)
const {prevData, transferBack, callbackEventData} = useProvideTransfer()
const year = computed(() => prevData.value?.detail?.year)
const {isMock} = useProvideVoluntaryHeader()
const stepSvc = useProvideVoluntaryStep('志愿编辑')
const dataSvc = useProvideVoluntaryData(year)
const formSvc = useProvideVoluntaryForm()
const cartSvc = useProvideVoluntaryCart()
const highlightSvc = useProvideVoluntaryMajorHighlight()
const {save, onComplete} = useProvideVoluntaryAssistant(stepSvc, dataSvc, formSvc, cartSvc, highlightSvc)

const {title, currentStep} = stepSvc
const {model, batch, mode} = formSvc
const {id, name, selectedList, defaultSort} = cartSvc
const {resolveFormedMajorsFromSavedData} = highlightSvc

const tryFixScoreMissing = async () => {
    const {score1, score2} = batch.value
    if (score1 && score2) return
    const {year} = prevData.value.detail
    const {score} = model.value
    // NOTE: try to fix score range in edit mode, because old versions `scorel` defined in the API model.
    const res = await zytbBatches({year, score, mode: toValue(mode)})
    const match = res.rows.find(r => r.batch == this.batch.batch)
    if (match) {
        batch.value.score1 = match.score1
        batch.value.score2 = match.score2
    }
}
const reloadScoreAndMode = () => {
    // 编辑模式下应该使用prevData中的数据
    const {mode, score, detail: {seatInput}} = prevData.value
    const modeParams = mode?.split(',') || []
    model.value.score = score
    model.value.firstSubject = modeParams[0]
    model.value.lastSubject = modeParams.slice(1) || []
    model.value.seatInput = seatInput || 0
}
const reloadBatch = () => {
    const {batch: batchId, batchName, detail} = prevData.value
    batch.value = {
        batch: batchId,
        batchName,
        name: batchName,
        score1: detail.batch.score1 || detail.batch.scorel,
        score2: detail.batch.score2,
        year: detail.year
    }
}
const reloadSelectedList = () => {
    const detail = prevData.value.detail
    const wishes = detail.batch.wishes
    // 反向转化选中专业，参照index的保存逻辑
    const restoredWishes = wishes.map(group => ({
        uniqueCode: group.uniqueCode,
        pickType: group.pickType,
        enrollRatio: group.enrollRatio,
        enrollRatioText: group.enrollRatioText,
        jCode: group.jCode,
        university: {
            id: group.universityId,
            name: group.name,
            code: group.code,
            ranking: group.ranking,
            rankingOfEdu: group.rankingOfEdu
        },
        history: {
            seat: group.seat
        },
        recruitPlan: {
            collegeCode: group.collegeCode
        },
        // marjors is a write error of history issue
        majors: group.marjors.map((m, index) => ({
            selected: true,
            localPriority: index + 1,
            id: m.id,
            marjorBelongs: m.code,
            marjorName: m.name,
            enrollRatio: m.enrollRatio,
            enrollRatioText: m.enrollRatioText,
            enrollFluctuate: m.enrollFluctuate,
            history: {
                submitMajorId: m.submitMajorId
            }
        }))
    }))
    restoredWishes.forEach(useVoluntaryMajorGroupIdentifier)
    selectedList.value = restoredWishes
    defaultSort.value = selectedList.value.map(g => g.uniqueCode)
}

const isSelectedListChanged = () => {
    const old = prevData.value.detail.batch.wishes.map(g => ({
        uniqueCode: g.uniqueCode,
        majors: [...g.marjors].sort(MxConst.recommendMajorSortFn).map(m => m.id)
    }))
    const current = selectedList.value.map(g => ({
        uniqueCode: g.uniqueCode,
        majors: [...g.majors].filter(m => m.selected).sort(MxConst.recommendMajorSortFn).map(m => m.id)
    }))
    console.log('aop compare selected old and current', old, current)
    // validate the sequence and unique code/id of major group and major item
    return JSON.stringify(old) != JSON.stringify(current)
}

const confirmBackChange = async () => {
    await cart.value.checkPopupBlock()
    if (isSelectedListChanged()) {
        await cart.value.confirmSave()
    }
}

onMounted(() => {
    useVoluntaryPageDataFormat(prevData)
    resolveFormedMajorsFromSavedData(prevData.value)
    id.value = prevData.value.id
    name.value = prevData.value.name
    isMock.value = prevData.value.detail.isMock
    reloadScoreAndMode()
    reloadBatch()
    reloadSelectedList()
    tryFixScoreMissing()
    //
    currentStep.value = 2
})
onComplete(() => {
    callbackEventData.value = true
    transferBack()
})
// export default {
//     extends: VoluntaryIndex,
//     mixins: [mxTransferPageMixins],
//     data() {
//         return {
//             currentStep: 2,
//             resetCalled: false // reset only need to call once in edit mode
//         }
//     },
//     computed: {
//         voluntaryDataCalculate() {
//             // NOTE: overriding by history voluntary data in edit mode
//             const param = this.voluntaryData || {}
//             const defaultLimit = {groups: 9999, profession: 9999}
//             // noinspection JSUnresolvedVariable
//             const historyParam = {
//                 sort: this.prevData.detail.batch?.sort || '',
//                 firedLimit: ext.arrayFirst(this.prevData.detail.batch?.paramBatches) || defaultLimit
//             }
//             return {
//                 ...param,
//                 ...historyParam
//             }
//         },
//         batchScoreRangeCalculate() {
//             // NOTE: overriding by history batch score range in edit mode
//             const min = this.batchMinScore
//             const max = this.prevData.detail?.batch?.scoreBatchLimit || this.voluntaryData?.maxScore
//             return [min, max]
//         },
//         batchMinScore() {
//             return this.batch.score2 || this.batch.score1 || this.batch.scorel
//         }
//     },
//     watch: {
//         'filter': function () {
//             // 这里与index作区分，因为filter数据可能还没有准备好
//             if (this.batchMinScore && !this.resetCalled) {
//                 this.resetCalled = true
//                 this.reset()
//             }
//         },
//         'batchMinScore': function () {
//             // if filter is ready first, call reset here.
//             if (!this.resetCalled && Object.keys(this.filter).length) {
//                 this.resetCalled = true
//                 this.reset()
//             }
//         }
//     },
//     async mounted() {
//         this.title = '志愿编辑'
//         this.subTitle = this.prevData.name
//         this.id = this.prevData.id
//         // super中会调用 reloadScoreAndMode
//         this.reloadBatch()
//         this.reloadSelectedList()
//         this.simulateFormedMajors()
//         await this.tryFixScoreMissing()
//     },
//     methods: {
//         prepareData() {
//             // important: string to json
//             if (typeof this.prevData.userSnapshot === 'string') {
//                 this.prevData.userSnapshot = JSON.parse(this.prevData.userSnapshot)
//             }
//             if (typeof this.prevData.detail === 'string') {
//                 const parsedData = JSON.parse(this.prevData.detail)
//                 parsedData.batch?.wishes?.forEach(this.ensureMajorGroupIdentifier)
//                 this.prevData.detail = parsedData
//             }
//             this.isMockHeader = this.prevData.detail.isMock || false
//         },
//         prevStep() {
//             const next = () => {
//                 const pages = getCurrentPages()
//                 return pages.length > 1 ? uni.navigateBack() : this.transferToIndex()
//             }
//             this.confirmSave(next)
//         },
//         async tryFixScoreMissing() {
//             if (this.batchMinScore) return
//             // NOTE: try to fix score range in edit mode, because old versions `scorel` defined in the API model.
//             const res = await zytbBatches({
//                 year: this.prevData.detail.year,
//                 score: this.scoreProps.score,
//                 mode: this.form.mode
//             })
//             const match = res.rows.find(r => r.batch == this.batch.batch)
//             if (match) {
//                 this.batch.score1 = match.score1
//                 this.batch.score2 = match.score2
//             }
//         },
//         async reloadScoreAndMode() {
//             // 编辑模式下应该使用prevData中的数据
//             const {
//                 mode,
//                 score,
//                 detail: {seatInput}
//             } = this.prevData
//             const modeParams = mode?.split(',') || []
//             this.scoreProps.score = score
//             this.scoreProps.firstSubject = modeParams[0]
//             this.scoreProps.lastSubject = modeParams.slice(1) || []
//             this.scoreProps.seatInput = seatInput || 0
//
//             await sleep(50)
//             this.scoreProps.init = true // begin seat monitor after init
//         },
//         reloadBatch() {
//             const {
//                 batch,
//                 batchName
//             } = this.prevData
//             this.batch = {
//                 batch,
//                 batchName,
//                 name: batchName,
//                 score1: this.prevData.detail.batch.score1 || this.prevData.detail.batch.scorel,
//                 score2: this.prevData.detail.batch.score2,
//                 year: this.prevData.detail.year
//             }
//             this.form = {
//                 batch: this.batch.batch,
//                 mode: this.mode
//             }
//         },
//         reloadSelectedList() {
//             const detail = this.prevData.detail
//             const wishes = detail.batch.wishes
//             // 反向转化选中专业，参照index的保存逻辑
//             const restoredWishes = wishes.map(group => ({
//                 uniqueCode: group.uniqueCode,
//                 pickType: group.pickType,
//                 enrollRatio: group.enrollRatio,
//                 enrollRatioText: group.enrollRatioText,
//                 jCode: group.jCode,
//                 university: {
//                     id: group.universityId,
//                     name: group.name,
//                     code: group.code,
//                     ranking: group.ranking,
//                     rankingOfEdu: group.rankingOfEdu
//                 },
//                 history: {
//                     seat: group.seat
//                 },
//                 recruitPlan: {
//                     collegeCode: group.collegeCode
//                 },
//                 // marjors is a write error of history issue
//                 majors: group.marjors.map((m, index) => ({
//                     selected: true,
//                     localPriority: index + 1,
//                     id: m.id,
//                     marjorBelongs: m.code,
//                     marjorName: m.name,
//                     enrollRatio: m.enrollRatio,
//                     enrollRatioText: m.enrollRatioText,
//                     enrollFluctuate: m.enrollFluctuate,
//                     history: {
//                         submitMajorId: m.submitMajorId
//                     }
//                 }))
//             }))
//             restoredWishes.forEach(this.ensureMajorGroupIdentifier)
//             this.selectedList = restoredWishes
//             this.defaultSort = this.selectedList.map(g => g.uniqueCode)
//         },
//         // simulate formed majors for highlight major
//         simulateFormedMajors() {
//             this.formedMajors = this.resolveFormedMajorsFromSavedData(this.prevData)
//         },
//         // override the NewSimulatedVolunteer
//         isSelectedListChanged() {
//             const old = this.prevData.detail.batch.wishes.map(g => ({
//                 jCode: g.jCode,
//                 majors: [...g.marjors].sort(MxConst.recommendMajorSortFn).map(m => m.id)
//             }))
//             const current = this.selectedList.map(g => ({
//                 jCode: g.jCode,
//                 majors: [...g.majors].filter(m => m.selected).sort(MxConst.recommendMajorSortFn).map(m => m.id)
//             }))
//             console.log('aop compare selected old and current', old, current)
//             // validate the sequence and unique code/id of major group and major item
//             return JSON.stringify(old) != JSON.stringify(current)
//         }
//     }
// }
</script>

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