<template>
    <z-paging ref="paging" v-model="list" @query="handleQuery" @on-refresh="handleRefresh">
        <template #top>
            <mx-nav-bar title="专业库"/>
            <view class="px-20 py-10 bg-white">
                <mx-search v-model="name" placeholder="输入专业名称" @search="handleSearch" @clear="handleSearch"/>
            </view>
            <uv-line/>
        </template>
        <view v-if="isCultural" class="h-[50px] fx-row fx-cen-cen">
            <mx-subsection v-model="current" :list="types" @change="handleSearch" width="65vw"/>
        </view>
        <view v-for="(levelOne,idx) in list">
            <view class="bg-white" :class="{'mt-20':isCultural?idx>0:true}" v-if="levelOne.level == 1">
                <view class="text-lg py-20 pl-30 font-bold">{{ levelOne.name }}</view>
                <uv-cell v-for="item in levelOne.children" class="f-333" :border="levelOne.childCount > 1" isLink
                         :title="item.name" :value="`${item.childCount}个专业`" @click="goDetail(item)">
                </uv-cell>
            </view>
            <uv-cell v-else :value="levelOne.childCount ?  `${levelOne.childCount}个专业` : ''" isLink
                     :title="levelOne.name" class="bg-white" :class="{'mt-20':idx==0&&!isCultural}"
                     @click="goDetail(levelOne)">
            </uv-cell>
        </view>
    </z-paging>
</template>

<script setup>
import {ref, computed} from 'vue';
import {useUserStore} from "@/hooks/useUserStore";
import {useCacheStore} from "@/hooks/useCacheStore";
import {cacheActions} from "@/hooks/defineCacheActions";
import {useTransfer} from "@/hooks/useTransfer";

const paging = ref(null)
const list = ref([])
const {isCultural} = useUserStore()
const {dispatchCache, removeCache} = useCacheStore()
const {transferTo} = useTransfer()

const name = ref('')
const current = ref(0)
const types = ref(['本科', '专科', '职教本科'])
const type = computed(() => types.value[current.value])

const handleSearch = () => {
    paging.value.reload()
}

const handleRefresh = () => {
    removeCache(cacheActions.getMajorTree)
}

const handleQuery = () => {
    // payload这样申明是为了在无条件时构建通用缓存，减少请求次数，
    // 与其它地方dispatchCache(cacheActions.getMajorTree)调用重合
    let payload = undefined
    if (name.value) {
        payload = payload || {}
        payload.name = name.value
        payload.level = 1
    }
    if (isCultural.value) {
        payload = payload || {}
        payload.type = type.value
    }
    dispatchCache(cacheActions.getMajorTree, payload)
        .then(tree => paging.value.completeByNoMore(tree, true))
        .catch(e => paging.value.complete(false))
}

const goDetail = (item) => {
    const paths = [, , 'level-two/level-two', 'detail/detail']
    const path = paths[item.level]
    if (!path) return
    transferTo('/pages/major-library/' + path, ['code'], item)
}
</script>

<style lang="scss">

</style>
