<template>
  <ie-page>
    <z-paging ref="paging" v-model="list" :safe-area-inset-bottom="true" @query="handleQuery">
      <template #top>
        <ie-navbar title="专业库" />
        <ie-search v-model="keyword" placeholder="输入专业名称" @search="handleSearch" @clear="handleSearch" />
      </template>
      <template v-if="!showLevel2">
        <view v-for="item in list" :key="item.id">
          <view class="text-30 text-fore-title py-20 px-30 font-bold mt-20">{{ item.name }}</view>
          <uv-cell-group>
            <uv-cell v-for="child in item.children" :key="child.id" icon="" :title="child.name" :isLink="true"
              :value="`${child.children?.length}个专业`" arrow-direction="right" @click="handleClick(child)"></uv-cell>
          </uv-cell-group>
        </view>
      </template>
      <template v-else>
        <uv-cell-group :border="false">
          <uv-cell v-for="item in list" :key="item.id" icon="" :title="item.name" :isLink="true"
            :value="item?.children?.length ? `${item?.children?.length}个专业` : ''" arrow-direction="right"
            @click="handleClick(item)"></uv-cell>
        </uv-cell-group>
      </template>
    </z-paging>
  </ie-page>
</template>
<script lang="ts" setup>
import { getMajorTree, getMajorByName } from '@/api/modules/major';
import { Major } from '@/types';
import { useTransferPage } from '@/hooks/useTransferPage';
const { transferTo, routes } = useTransferPage();

const keyword = ref('');
const list = ref<Major.MajorItem[]>([]);
const paging = ref<ZPagingInstance>();
const showLevel2 = ref(false);
const handleQuery = (page: number, size: number) => {
  const params: Major.MajorTreeQueryDTO = {};
  uni.$ie.showLoading();
  if (keyword.value.trim()) {
    params.name = keyword.value.trim();
    params.level = 1;
    showLevel2.value = true;
    getMajorByName(params).then(res => {
      paging.value?.completeByNoMore(res.data, true);
    }).catch(() => paging.value?.complete(false))
      .finally(() => uni.$ie.hideLoading());
  } else {
    showLevel2.value = false;
    getMajorTree(params).then(res => {
      paging.value?.completeByNoMore(res.data, true);
    }).catch(() => paging.value?.complete(false))
      .finally(() => uni.$ie.hideLoading());
  }
}
const handleSearch = () => {
  paging.value?.reload();
}
const handleClick = (item: Major.MajorItem) => {
  if (item.children?.length > 0) {
    transferTo(routes.majorLevelTwo, {
      data: item
    });
  } else {
    transferTo(routes.majorDetail, {
      data: item
    });
  }
}
</script>
<style lang="scss" scoped></style>