<template>
  <z-paging ref="paging" :auto="false" v-model="list" :safe-area-inset-bottom="true" :hide-no-more-by-limit="10" @query="handleQuery">
    <uv-cell-group :border="false">
      <uv-cell v-for="item in list" :key="item.id" :title="item.name" :label="item.code" @click="handleClick(item)">
        <template #title>
          <text class="text-30 text-fore-title">{{ item.name }}</text>
        </template>
        <template #label>
          <text class="text-26 text-fore-light mt-10">{{ getParentName(item.ancestors) }}</text>
        </template>
        <template #value>
          <uv-icon name="arrow-right" size="18" color="var(--fore-light)" />
        </template>
      </uv-cell>
    </uv-cell-group>
  </z-paging>
</template>
<script lang="ts" setup>
import type { Major } from '@/types';
import { getMajorTree, getCollectedMajors } from '@/api/modules/major';
import { useTransferPage } from '@/hooks/useTransferPage';

const { transferTo, routes } = useTransferPage();

const list = ref<Major.CollectedMajor[]>([]);
const paging = ref<ZPagingInstance>();
const tree = ref<Major.MajorItem[]>([]);

/**
 * 从树中获取指定code的对象,深度优先
 * @param ancestors 
 */
const getDataByCode = (code: string, tree: Major.MajorItem[]): Major.MajorItem | null => {
  for (const item of tree) {
    if (item.code === code) {
      return item;
    }
    if (item.children) {
      const data = getDataByCode(code, item.children);
      if (data) {
        return data;
      }
    }
  }
  return null;
}

const getParentName = (ancestors: string) => {
  const codes = ancestors.split(',');
  return codes.filter(code => code !== '0').map(code => {
    const item = getDataByCode(code, tree.value);
    return item?.name;
  }).join(' > ');
}

const handleClick = (item: Major.CollectedMajor) => {
  transferTo(routes.majorDetail, {
    data: { code: item.code }
  });
}

const handleQuery = (page: number, size: number) => {
  getCollectedMajors({ pageNum: page, pageSize: size }).then(res => {
    paging.value?.completeByTotal(res.rows, res.total);
  }).catch(() => paging.value?.complete(false));
}
onLoad(() => {
  getMajorTree({}).then(res => {
    tree.value = res.data;
    paging.value?.reload();
  });
});
</script>
<style lang="scss" scoped></style>