<template>
  <view class="h-full">
    <z-paging ref="paging" v-model="list" @query="handleQuery">
      <template #top>
        <slot name="top" />
        <college-conditions-picker v-if="filterOptions" :options="filterOptions" :absolute="absolute" @change="handleSearch" />
        <ie-search v-model="queryParams.name" placeholder="输入院校名称" @search="handleSearch" @clear="handleSearch" />
      </template>
      <view class="p-20 flex flex-col gap-20">
        <college-item v-for="i in list" :key="i.code" :item="i" @click="handleDetail(i)" />
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { useTransferPage } from "@/hooks/useTransferPage";
import { getUniversityFilters, universityList } from "@/api/modules/university";
import type { University, UniversityQueryDto, UniversityFilter } from "@/types/university";
import { UNIVERSITY_FILTER } from "@/types/injectionSymbols";
import CollegeConditionsPicker from "@/pagesOther/pages/university/index/components/plus/college-conditions-picker.vue";
import CollegeItem from "@/pagesOther/pages/university/index/components/plus/college-item.vue";
import { routes } from "@/common/routes";

const props = withDefaults(defineProps<{
  customItemClick?: boolean;
  extraFilter?: Record<string, any>;
  absolute?: boolean;
}>(), {
  customItemClick: false,
  extraFilter: () => ({})
})
const emits = defineEmits(['item-click'])

const { prevData, transferTo } = useTransferPage()
const paging = ref<ZPagingInstance>()
const list = ref<University[]>([])
const filterOptions = ref<UniversityFilter | null>(null)
const queryParams = ref<UniversityQueryDto>({
  name: '',
  features: [],
  type: [],
  natureTypeCN: [],
  location: [],
  level: [],
  tiers: []
})

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

const handleQuery = (pageNum: number, pageSize: number) => {
  const filterParams: Record<string, string> = {};
  Object.keys(queryParams.value).forEach(item => {
    const value = queryParams.value[item as keyof UniversityQueryDto]
    filterParams[item] = Array.isArray(value) ? value.join(',') : value
  });
  const query = { pageNum, pageSize, ...props.extraFilter, ...filterParams }
  universityList(query)
    .then(res => paging.value?.completeByTotal(res.rows, res.total))
    .catch(e => paging.value?.complete(false))
}

const handleDetail = (u: University) => {
  if (props.customItemClick) {
    return emits('item-click', u)
  }
  const { id, code, name } = u
  transferTo(routes.universityDetail, { data: { id, code, name } })
}

provide(UNIVERSITY_FILTER, queryParams)

onMounted(async () => {
  const { data } = await getUniversityFilters()
  filterOptions.value = data
  // accept default query parameters
  if (prevData.value.tier) {
    queryParams.value.tiers = [prevData.value.tier]
  }
});

</script>

<style scoped></style>