<template>
  <view>
    <z-paging ref="paging" v-model="results" bg-color="white" :fixed="false" :use-page-scroll="true" :auto="false"
      :refresher-enabled="false" @query="handleQuery">
      <view class="flex items-center gap-20 px-30 py-20">
        <ie-picker v-model="queryParams.year" :list="years" width="w-fit" icon="arrow-down" placeholder="年份"
          custom-class="px-30 py-10 bg-primary-100 rounded" @change="handleYearChange" />
        <ie-picker v-model="queryParams.level" :list="levels" width="w-fit" icon="arrow-down" placeholder="级别"
          custom-class="px-30 py-10 bg-primary-100 rounded" @change="handleLevelChange" />
        <ie-picker v-model="queryParams.group" :list="groups" width="w-fit" icon="arrow-down" placeholder="专业组"
          custom-class="px-30 py-10 bg-primary-100 rounded" @change="handleGroupChange" />
      </view>
      <view v-for="([label, values], idx) in groupedResults" :key="label" class="px-30">
        <uv-divider v-if="idx > 0" />
        <view class="flex flex-col gap-20">
          <view v-for="(item, i) in values" :key="i" class="bg-back-light p-24 rounded-xl">
            <view class="text-fore-title">
              <text class="font-bold text-30">{{ item.majorName }}</text>
              <text v-if="item.specialProject" class="text-24">({{ item.specialProject }})</text>
            </view>
            <view v-if="item.marjorDirection" class="text-primary text-24">
              {{ item.marjorDirection }}
            </view>
            <view v-if="mode == 'plan'" class="mt-12 text-22 flex gap-30">
              <view v-if="item.majorGroup" class="font-bold">{{ item.majorGroup }}</view>
              <view>
                学费
                <text class="font-bold">{{ item.fee || '-' }}</text>
                /年
              </view>
              <view>
                学制
                <text class="font-bold">{{ item.xueZhi || '-' }}</text>
                年
              </view>
            </view>
            <view v-if="mode == 'enroll' && item.majorGroup" class="mt-12 text-22 flex gap-30">
              <view v-if="item.majorGroup" class="font-bold">{{ item.majorGroup }}</view>
            </view>
            <view class="mt-20 grid gap-20" :class="`grid-cols-` + descriptors.length">
              <plan-enroll-descriptor v-for="d in descriptors" :key="d.title" :title="d.title" :value="item[d.prop as keyof typeof item]"
                :title-only="d.titleOnly" @click="handleRuleClick(d, item)" />
            </view>
            <view v-if="mode == 'plan' && isLatestYear" class="mt-20 flex justify-between items-center gap-30">
              <view class="h-80 flex-1 border border-solid border-primary rounded-full text-primary
                            text-30 flex justify-center items-center" @click="handleAddVoluntary(item)">
                加入志愿表
              </view>
              <view class="h-80 flex-1 bg-gradient-to-r from-primary-500 to-primary rounded-full text-white
                            text-30 flex justify-center items-center" @click="handleRateVoluntary(item)">
                测录取概率
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import _ from 'lodash';
import { HistoryMode, IPlanEnrollDescriptor, IPlanEnrollHistory, University, UniversityDetail } from "@/types/university";
import PlanEnrollDescriptor from "@/pagesOther/pages/university/detail/components/plus/plan-enroll-descriptor.vue";
import { UNIVERSITY_DETAIL } from "@/types/injectionSymbols";
import { addVoluntary } from "@/api/modules/voluntary";
import { SelectedUniversityMajor } from "@/types/voluntary";
import { useTransferPage } from "@/hooks/useTransferPage";
import { routes } from "@/common/routes";


const props = withDefaults(defineProps<{
  mode: HistoryMode;
  list: IPlanEnrollHistory[];
}>(), {
  mode: 'plan',
  list: () => []
})

const { transferTo } = useTransferPage()
const detail = inject(UNIVERSITY_DETAIL, ref({} as UniversityDetail))
const baseInfo = computed<University>(() => detail.value.baseInfo)
const paging = ref<ZPagingInstance>()
const isCultural = ref(false) // 河南文化类遗留结构
const tag = computed(() => isCultural.value && '') // examMajorName 河南文化类遗留结构
const descriptors = computed<IPlanEnrollDescriptor[]>(() => {
  const enrollShared = [{ title: '录取', prop: 'realNum' }, { title: '最低分', prop: 'minScore' }]
  const cols: IPlanEnrollDescriptor[] = props.mode == 'plan'
    ? [{ title: '计划', prop: 'planNum' }, { title: '招录比', prop: 'acceptanceRate' }]
    : isCultural.value
      ? [...enrollShared, { title: '最低位', prop: 'minSeat' }]
      : [...enrollShared]
  if (!isCultural.value) cols.push({ title: '录取规则', prop: '', titleOnly: true })
  return cols
})

const results = ref<IPlanEnrollHistory[]>([])
const groupedResults = computed(() => Object.entries(_.groupBy(results.value, i => i.majorGroup)))
const queryParams = ref({ year: '', level: '', group: '' })
const years = computed(() => _.orderBy(_.uniq(_.map(props.list, i => i.year)), [], ['desc'])
  .map(i => ({ label: i, value: i })))
const levels = computed(() => _.uniq(_.map(props.list.filter(i => i.year == queryParams.value.year), i => i.level))
  .map(i => ({ label: i, value: i })))
const groups = computed(() => [{
  label: '不限',
  value: ''
}, ..._.uniq(_.map(props.list.filter(i => i.year == queryParams.value.year && i.level == queryParams.value.level), i => i.majorGroup))
  .map(g => ({ label: g, value: g }))])
const isLatestYear = computed(() => queryParams.value.year == years.value[0]?.value)

const listOfYear = computed(() => queryParams.value.year ? props.list.filter(i => i.year == queryParams.value.year) : [])
const listOfLevel = computed(() => queryParams.value.level ? listOfYear.value.filter(i => i.level == queryParams.value.level) : [])
const listOfGroup = computed(() => !queryParams.value.group ? listOfLevel.value : listOfLevel.value.filter(i => i.majorGroup == queryParams.value.group))

const handleYearChange = () => {
  paging.value?.reload()
}

const handleLevelChange = () => {
  paging.value?.reload()
}

const handleGroupChange = () => {
  paging.value?.reload()
}

const handleQuery = () => {
  // console.log('plan enroll list: query', props.mode, queryParams.value)
  // 到这里时listOfLevel应该已经动态计算完毕了
  // onSearch, results结构都是多余的，这里只是为了实验z-paging的虚拟列表
  paging.value?.completeByNoMore(listOfGroup.value, true)
}

const handleRuleClick = (descriptor: IPlanEnrollDescriptor, history: IPlanEnrollHistory) => {
    if (descriptor.titleOnly) {
        uni.$ie.showConfirm({
            title: '录取规则',
            content: history.totalRule || '暂无录取规则',
            showCancel: false
        })
    }
}

const handleAddVoluntary = async (item: IPlanEnrollHistory) => {
  const { code } = baseInfo.value
  await addVoluntary({ universityId: code, majorId: item.id + '' })
  uni.$ie.showSuccess('保存成功')
}

const handleRateVoluntary = (item: IPlanEnrollHistory) => {
  const selected: SelectedUniversityMajor = {
    universityId: baseInfo.value.code,
    universityLogo: baseInfo.value.logo,
    universityName: baseInfo.value.name,
    majorId: item.id + '',
    majorName: item.majorName,
    majorGroup: item.majorGroup,
    majorAncestors: '', // 测算部分这个字段不重要
    info: baseInfo.value
  }
  transferTo(routes.voluntaryIndex, { bigData: { selected } })
}

onMounted(() => {
  watch(() => props.list, async (list) => {
    // console.log('plan enroll list: watch', props.mode, list)
    if (list.length) {
      queryParams.value.year = years.value[0].value
      queryParams.value.level = levels.value[0].value
    }
    paging.value?.reload();
  }, { immediate: true })
})

onPageScroll((e: any) => {
  paging.value?.updatePageScrollTop(e.scrollTop)
});
</script>

<style scoped lang="scss">
::v-deep .uv-button-wrapper {
  flex: 1
}
</style>
