<template>
  <ie-page>
    <z-paging ref="paging" v-model="list" :auto="false" :safe-area-inset-bottom="true" :hide-no-more-by-limit="10"
      @query="handleQuery">
      <template #top>
        <ie-navbar title="一分一段" />
        <view class="px-30 pt-30 flex items-center gap-40">
          <view
            class="text-[15px] text-primary px-30 py-8 bg-primary-100 rounded-full whitespace-nowrap border border-solid border-primary flex items-center gap-10">
            <uv-icon name="lock" size="20" color="var(--primary-color)" />
            <text>{{ userStore.examMajorName }}</text>
          </view>
          <view class="w-fit">
            <ie-picker v-model="queryParams.location" :list="locations" icon="arrow-down" icon-color="#666666" />
          </view>
          <view class="w-fit">
            <ie-picker v-model="queryParams.year" :list="years" icon="arrow-down" icon-color="#666666" />
          </view>
        </view>
        <view class="px-10 mt-10">
          <ie-search v-model="queryParams.score" placeholder="请输入分数" inputType="number" :showAction="true"
            :border="false" @search="queryScore(true)" />
        </view>
      </template>
      <view>
        <view class="flex items-center py-20">
          <view class="flex-1 text-center">
            <view class="text-24 text-fore-tip">分数</view>
            <view class="mt-10 text-30 text-fore-title font-bold">{{ scoreStat?.score || '-' }}</view>
          </view>
          <view class="flex-1 text-center">
            <view class="text-24 text-fore-tip">同分人数</view>
            <view class="mt-10 text-30 text-fore-title font-bold">{{ scoreStat?.num || '-' }}</view>
          </view>
          <view class="flex-1 text-center">
            <view class="text-24 text-fore-tip">位次区间</view>
            <view class="mt-10 text-30 text-fore-title font-bold">
              {{ scoreRange }}
            </view>
          </view>
        </view>
        <template v-if="scoreStat">
          <view class="h-20 bg-back-light"></view>
          <view>
            <view class="p-30">历年等效分</view>
            <view class="px-30">
              <ie-table :table-columns="scoresTableColumns" :data="scoresTableData" />
              <view class="my-20 flex items-center gap-10">
                <uv-icon name="info-circle" size="16" color="var(--danger)" />
                <text
                  class="text-24 text-fore-tip">因高考人数及招生计划每年都存在一定的增减，分数和位次也会有相应浮动，我们根据历年省控线变化幅度等比计算出历年等效位次和等效分。</text>
              </view>
            </view>
          </view>
        </template>
        <view class="h-20 bg-back-light"></view>
        <view class="p-30">一分一段表</view>
        <view class="px-30">
          <ie-table :table-columns="scoresSegmentColumns" :data="list" />
        </view>
      </view>
    </z-paging>
  </ie-page>
</template>
<script lang="ts" setup>
import { useUserStore } from '@/store/userStore';
import { getYfydLocations, getYfydYears, getYfydRankingList, getYfydRankingScore } from '@/api/modules/vhs';
import type { PickerItem, Career } from '@/types';

type EquivalentScore = {
  score: number;
  num: number;
  lowestRank: number;
  highestRank: number;
};

const userStore = useUserStore();
const { getLocation, userInfo } = userStore;

const locations = ref<PickerItem[]>([]);
const years = ref<PickerItem[]>([]);
const queryParams = ref<Partial<Career.RankingSegmentScoreQueryDTO>>({
  location: getLocation || '',
  mode: userInfo.examMajor
});
const list = ref<Career.RankingSegmentItem[]>([]);
const scoreStat = ref<EquivalentScore | null>(null);
const scores = ref<Career.RankingSegmentScore[]>([]);

watch(() => [queryParams.value.location, queryParams.value.year], () => {
  queryScore();
  paging.value?.reload();
});
const scoreRange = computed(() => {
  if (!scoreStat.value) {
    return '-';
  }
  return `${scoreStat.value.lowestRank}~${scoreStat.value.highestRank}`;
});

const scoresTableColumns = computed(() => {
  if (scores.value.length === 0) {
    return [];
  }
  return [
    {
      prop: 'name',
      label: '类型/年份',
      flex: 1.6,
    },
    ...scores.value.map(item => {
      return {
        prop: item.year,
        label: item.year,
        flex: 1,
      }
    }),
  ];
});
const scoresSegmentColumns = computed(() => {
  return [
    {
      prop: 'score',
      label: '分数',
      flex: 1,
    },
    {
      prop: 'seat',
      label: '位次区间',
      flex: 1,
    },
    {
      prop: 'num',
      label: '同分人数',
      flex: 1,
    },
  ];
});
const scoresTableData = computed(() => {
  if (scores.value.length === 0) {
    return [];
  }
  return [
    {
      name: '等效分',
      [scores.value[0].year]: scores.value[0].score,
      [scores.value[1].year]: scores.value[1].score,
      [scores.value[2].year]: scores.value[2].score,
    },
    {
      name: '等效位',
      [scores.value[0].year]: scores.value[0].seat,
      [scores.value[1].year]: scores.value[1].seat,
      [scores.value[2].year]: scores.value[2].seat,
    },
  ];
});
const paging = ref<ZPagingInstance>();

const queryScore = (showTip = false) => {
  if (!queryParams.value.score) {
    if (showTip) {
      uni.$ie.showToast('请输入分数');
    }
    return;
  }
  if (isNaN(queryParams.value.score) || queryParams.value.score < 0) {
    if (showTip) {
      uni.$ie.showToast('请输入合法的分数');
    }
    return;
  }
  getYfydRankingScore({ ...queryParams.value, score: queryParams.value.score || 0 }).then(res => {
    console.log(res)
    if (res.match) {
      scoreStat.value = {
        score: res.match.score,
        num: res.match.num,
        lowestRank: res.match.lowestRank,
        highestRank: res.match.highestRank,
      }
    } else {
      scoreStat.value = null;
    }
    if (res.scores) {
      scores.value = res.scores;
    } else {
      scores.value = [];
    }
  });
}
const handleQuery = (page: number, size: number) => {
  getYfydRankingList({ ...queryParams.value, pageNum: page, pageSize: size }).then(res => {
    paging.value?.completeByTotal(res.rows.map(item => {
      return {
        ...item,
        seat: `${item.lowestRank}~${item.highestRank}`,
      }
    }), res.total);
  }).catch(() => paging.value?.complete(false));
}
const loadData = () => {
  getYfydLocations().then(res => {
    locations.value = res.rows.map(item => {
      return {
        label: item,
        value: item,
      }
    });
  });
  getYfydYears(queryParams.value.location || '').then(res => {
    queryParams.value.year = res.rows[0];
    years.value = res.rows.map(item => {
      return {
        label: item.toString(),
        value: item,
      }
    });
  });
}

onLoad(() => {
  loadData();
});
</script>
<style lang="scss" scoped></style>