<script lang="ts" setup>
import MxRadioGroup from '@/pages-sub/components/radio/index.vue?async'
import MxSearch from '@/pages-sub/components/search/index.vue?async'
import { getAreaList, getHistoryYearList, getSchoolHistoricalScores, getSchoolNature } from '@/service'
import { systemInfo } from '@/utils/systemInfo'

// #ifdef MP-WEIXIN
definePage({
  style: {
    navigationStyle: 'custom',
  },
  excludeLoginPath: false,
})
// #endif

// #ifndef MP-WEIXIN
definePage({
  style: {
    navigationStyle: 'custom',
    transparentTitle: 'always',
    navigationBarTitleText: '',
  },
  excludeLoginPath: false,
})
// #endif

function handleBack() {
  uni.navigateBack({ delta: 1 })
}

const areaList = ref<any[]>([])
const natureList = ref<any[]>()

const searchParams = ref({
  keyword: '',
  region: null,
  nature: null,
  natureLabel: '',
  year: null,
})

const visibleFlag1 = ref(false)
const visibleFlag2 = ref(false)
const visibleFlag3 = ref(false)

interface HistoricalScore {
  schoolName?: string
  region?: string
  schoolNature?: string
  tags?: string
  ranking?: number | string | null
  admissionScore?: number | string | null
}

interface PagingRef {
  reload: () => void
  complete: (data: HistoricalScore[] | false) => void
}

const paging = ref<PagingRef | null>(null)
const partialData = ref<HistoricalScore[]>([])
const yearList = ref<any[]>([])

function handleChange() {
  visibleFlag1.value = false
  visibleFlag2.value = false
  visibleFlag3.value = false
  paging.value?.reload()
}

function queryList(page: number, _pageSize: number) {
  if (page > 1) {
    paging.value?.complete([])
    return
  }

  getSchoolHistoricalScores({
    query: {
      SchoolName: searchParams.value.keyword,
      Region: searchParams.value.region,
      SchoolType: searchParams.value.nature,
      Year: searchParams.value.year,
    },
  }).then((resp) => {
    if (resp.code === 200) {
      paging.value?.complete(Array.isArray(resp.result) ? resp.result : [])
    }
    else {
      paging.value?.complete(false)
    }
  }).catch(() => {
    paging.value?.complete(false)
  })
}

function virtualListChange(_vList: HistoricalScore[]) {
  partialData.value = _vList
}

function getTagList(tags?: string) {
  return (tags || '').split(/[\s,，、]+/).filter(Boolean).slice(0, 2)
}

onShow(() => {
  Promise.all([
    getAreaList().then((resp) => {
      if (resp.code === 200) {
        areaList.value = [{ value: '', label: '不限' }, ...resp.result]
      }
    }),
    getSchoolNature().then((resp) => {
      if (resp.code === 200) {
        natureList.value = [{ value: '', label: '不限' }, ...resp.result]
      }
    }),
    getHistoryYearList().then((resp) => {
      if (resp.code === 200) {
        yearList.value = [...resp.result]
        searchParams.value.year = yearList.value[yearList.value.length - 1]?.value
      }
    }),
  ]).then(() => {
    handleChange()
  })
})
</script>

<template>
  <z-paging
    ref="paging" use-virtual-list :force-close-inner-list="true" cell-height-mode="dynamic"
    :auto="false" :auto-show-system-loading="false" :safe-area-inset-bottom="true" :paging-style="{ backgroundColor: '#f8f8f8' }"
    @virtual-list-change="virtualListChange" @query="queryList"
  >
    <template #top>
      <view class="gradient-custom" :style="{ 'padding-top': `${systemInfo?.statusBarHeight}px` }">
        <sar-navbar
          title="历年分数" :show-back="true" :root-style="{ '--sar-navbar-bg': `rgba(255, 255, 255, 0)`, '--sar-navbar-item-color': 'black', '--sar-navbar-title-max-width': '100%' }"
          @back="handleBack"
        >
          <template #title>
            <view class="ml-[90rpx] w-[448rpx]">
              <mx-search v-model:search-text="searchParams.keyword" root-class="py-[20rpx] pl-[30rpx]" @complete="handleChange" />
            </view>
          </template>
        </sar-navbar>

        <sar-dropdown
          root-style="--sar-dropdown-placeholder-color:#666;--sar-dropdown-value-font-size:28rpx;--sar-dropdown-option-active-color:#1580FF;--sar-dropdown-box-shadow:0rpx 6rpx 8rpx 0rpx rgba(0,0,0,0.04);"
        >
          <sar-dropdown-item v-model:visible="visibleFlag1" :title="searchParams.region || '区域'">
            <mx-radio-group
              v-model:value="searchParams.region" :options="areaList" label-key="label" value-key="value"
              custom-root-class="px-[32rpx] pt-[30rpx] pb-[40rpx]"
              active-item-class="bg-white text-[#1580FF] border-1 border-solid border-[#1580FF]!"
              default-item-class="bg-[#F3F4F8] border-[#F3F4F8]"
              custom-item-class="w-full py-[16rpx] text-center border-[1rpx] border-solid" @change="handleChange"
            />
          </sar-dropdown-item>
          <sar-dropdown-item v-model:visible="visibleFlag2" :title="searchParams.natureLabel || '办学性质'">
            <mx-radio-group
              v-model:value="searchParams.nature" v-model:label="searchParams.natureLabel"
              :options="natureList" label-key="label" value-key="value" custom-root-class="px-[32rpx] pt-[30rpx] pb-[40rpx]"
              active-item-class="bg-white text-[#1580FF] border-1 border-solid border-[#1580FF]!"
              default-item-class="bg-[#F3F4F8] border-[#F3F4F8]"
              custom-item-class="w-full py-[16rpx] text-center border-[1rpx] border-solid" @change="handleChange"
            />
          </sar-dropdown-item>
          <sar-dropdown-item v-model:visible="visibleFlag3" v-model="searchParams.year" :title="searchParams.year || '年份'">
            <mx-radio-group
              v-model:value="searchParams.year" :options="yearList" label-key="label" value-key="value"
              custom-root-class="px-[32rpx] pt-[30rpx] pb-[40rpx]"
              custom-item-class="w-full py-[16rpx] text-center border-[1rpx] border-solid"
              active-item-class="bg-white text-[#1580FF] border-1 border-solid border-[#1580FF]!"
              default-item-class="bg-[#F3F4F8] border-[#F3F4F8]" @change="handleChange"
            />
          </sar-dropdown-item>
        </sar-dropdown>
      </view>
    </template>

    <view class="p-[30rpx]">
      <view
        v-for="(val, index) in partialData"
        :key="index" class="mb-[20rpx] flex justify-between gap-[40rpx] rounded-[16rpx] bg-white p-[30rpx]"
      >
        <view class="">
          <view class="max-w-[408rpx] text-wrap text-[30rpx]">
            {{ val.schoolName }}
          </view>
          <view class="mt-[10rpx] flex flex-wrap gap-[10rpx]">
            <view class="w-max px-[10rpx] py-[4rpx] text-[24rpx] text-[#666]">
              {{
                val.region }}·{{ val.schoolNature }}
            </view>
            <view
              v-for="feature in getTagList(val.tags)"
              :key="feature" class="rounded-[8rpx] bg-[#F8F8F8] px-[10rpx] py-[4rpx] text-[24rpx] text-[#666]"
            >
              {{ feature }}
            </view>
          </view>
        </view>
        <view class="flex items-center gap-[30rpx]">
          <view class="flex flex-col items-end text-[#1E40AF]">
            <view class="text-[40rpx] font-[DinBold]">
              {{ val.ranking ?? '--' }}
            </view>
            <view class="mt-[10rpx] w-max text-[24rpx]">
              位次
            </view>
          </view>
          <view class="flex flex-col items-end text-[#1E40AF]">
            <view class="text-[40rpx] font-[DinBold]">
              {{ val.admissionScore ?? '--' }}
            </view>
            <view class="mt-[10rpx] w-max text-[24rpx]">
              分数
            </view>
          </view>
        </view>
      </view>
    </view>
  </z-paging>
</template>

<style lang="scss" scoped>
@import url('@/style/index.scss');
</style>
