<template>
    <z-paging ref="paging" v-model="results" :auto="false" bg-color="white" :refresher-enabled="false"
              @query="handleQuery">
        <template #top>
            <view class="fx-row items-center gap-40 px-40" :style="{height: tag?'60px': '44px'}">
                <uv-tags v-if="tag" :text="tag" plain plain-fill/>
                <uv-form ref="form" :model="queryParams" :rules="rules" error-type="toast">
                    <mx-condition/>
                </uv-form>
            </view>
        </template>
        <view v-for="([label, values], idx) in groupedResults" class="fx-col px-20">
            <view v-if="label" class="text-primary font-bold mb-20">{{ label }}</view>
            <view v-for="(item,i) in values" class="px-20 fx-col">
                <view class="font-bold text-main">
                    {{ item.majorName }}
                    <template v-if="item.groupName">({{ item.groupName }})</template>
                    <template v-if="item.specialProject">({{ item.specialProject }})</template>
                </view>
                <view v-if="item.marjorDirection" class="font-[PingFang] text-2xs text-content">
                    {{ item.marjorDirection }}
                </view>
                <view class="mt-10 grid gap-20" :class="`grid-cols-`+descriptors.length">
                    <plan-enroll-descriptor v-for="d in descriptors" :title="d.title" :value="item[d.key]"
                                            :title-only="d.titleOnly" @click="handleRuleClick(d, item)"/>
                </view>
                <uv-divider v-if="i<values.length-1" dashed/>
            </view>
            <uv-divider v-if="idx<groupedResults.length-1"/>
        </view>
    </z-paging>
</template>

<script setup>
import {computed, ref} from 'vue';
import _ from 'lodash';
import {createPropDefine} from "@/utils";
import {useUserStore} from "@/hooks/useUserStore";
import {conditionSharedConfig} from "@/components/mx-condition/modules/conditionSharedConfig";
import {useProvideSearchModel} from "@/components/mx-condition/useSearchModelInjection";
import PlanEnrollDescriptor from "@/pages/college-library/components/plan-enroll-descriptor.vue";

const props = defineProps({
    list: createPropDefine([], Array),
    mode: createPropDefine('plan', String, v => ['plan', 'enroll'].includes(v))
})
const emits = defineEmits(['rule'])

const paging = ref(null)
const {currentUser, isCultural} = useUserStore()
const tag = computed(() => isCultural.value && currentUser.value.examMajorName)
const descriptors = computed(() => {
    const enrollShared = [{title: '录取', key: 'realNum'}, {title: '最低分', key: 'minScore'}]
    const cols = props.mode == 'plan'
        ? [{title: '计划', key: 'planNum'}, {title: '学制', key: 'xueZhi'}, {title: '学费', key: 'fee'}]
        : isCultural.value
            ? [...enrollShared, {title: '最低位', key: 'minSeat'}]
            : [...enrollShared]
    if (!isCultural.value) cols.push({title: '录取规则', key: '', titleOnly: true})
    return cols
})

const results = ref([])
const groupedResults = computed(() => Object.entries(_.groupBy(results.value, i => i.majorGroup)))
const queryParams = ref({year: '', level: '', group: ''})
const years = computed(() => _.orderBy(_.uniq(_.map(props.list, i => i.year)), [], ['desc']))
const conditionYear = {
    ...conditionSharedConfig,
    key: 'year',
    handler: () => years.value,// 这个页面能渲染，即说明有数据源，可以直接取值
    required: true
}
const conditionLevel = {
    ...conditionSharedConfig,
    key: 'level',
    dependentKeys: ['year'],
    handler: ({year}) => _.uniq(_.map(props.list.filter(i => i.year == year), i => i.level)),
    required: true
}
const conditionGroup = {
    ...conditionSharedConfig,
    key: 'group',
    title: '专业组',
    dependentKeys: ['level'],
    independentKeys: ['year'],
    handler: (payload) => _.uniq(_.map(props.list.filter(i => i.year == payload.year && i.level == payload.level), i => i.majorGroup))
        .map(g => ({name: g, value: g})), // 构建name/value是为了兼容`不限选项`
    keyName: 'name',
    keyValue: 'value',
    hidden: isCultural.value
}
const form = ref(null)
const {onSearch, rules} = useProvideSearchModel([conditionYear, conditionLevel, conditionGroup], queryParams, form)

const listOfYear = computed(() => queryParams.value.year ? props.list.filter(i => i.year == queryParams.value.year) : [])
const listOfLevel = computed(() => queryParams.value.level ? listOfYear.value.filter(i => i.level == queryParams.value.level) : [])
const listOfGroup = computed(() => !queryParams.value.group ? listOfLevel.value : listOfLevel.value.filter(i => i.majorGroup == queryParams.value.group))
onSearch(() => paging.value.reload())

const handleQuery = () => {
    // 到这里时listOfLevel应该已经动态计算完毕了
    // onSearch, results结构都是多余的，这里只是为了实验z-paging的虚拟列表
    paging.value.completeByNoMore(listOfGroup.value, true)
}

const handleRuleClick = (descriptor, history) => {
    if (descriptor.titleOnly) emits('rule', history.totalRule)
}
</script>

<style scoped>

</style>
