<template>
    <z-paging ref="paging" v-model="list" :auto="false" @query="handleQuery" @on-refresh="handleRefresh">
        <view class="my-30">
            <uv-cell v-for="m in list" :title="m.name" :label="getParents(m)" is-link class="bg-white"
                     @click="goMajorDetail(m)"/>
        </view>
    </z-paging>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {useCacheStore} from "@/hooks/useCacheStore";
import {cacheActions} from "@/hooks/defineCacheActions";
import {useTransfer} from "@/hooks/useTransfer";
import {concernedMajors} from "@/api/webApi/career-other";
import {findTreeNode} from "@/utils/tree-helper";

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

const getParents = (major) => {
    const majorNode = findTreeNode(majorTree.value, n => n.code == major.code)
    const parents = []
    let node = majorNode
    while (node.parent) {
        parents.push(node.parent.name)
        node = node.parent
    }
    return parents.reverse().join(' | ')
}

const handleRefresh = () => {
    removeCache(concernedMajors)
}

const handleQuery = (pageNum, pageSize) => {
    const payload = {pageNum, pageSize}
    dispatchCache(concernedMajors, payload)
        .then(res => paging.value.completeByTotal(res.rows, res.total))
        .catch(e => paging.value.complete(false))
}

const goMajorDetail = (major) => {
    transferTo('/pagesOther/pages/major-library/detail/detail', ['code'], major)
}

onMounted(async () => {
    majorTree.value = await dispatchCache(cacheActions.getMajorTree)
    paging.value.reload()
})
</script>

<style scoped>

</style>