<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
    transparentTitle: 'always',
    navigationBarTitleText: '',
  },
}
</route>

<template>
  <z-paging
    ref="paging"
    use-virtual-list
    :force-close-inner-list="true"
    cell-height-mode="dynamic"
    @virtualListChange="virtualListChange"
    @query="queryList"
    :auto-show-system-loading="true"
  >
    <template #top>
      <Navbar
        safeAreaInsetTop
        bg-color="transparent"
        :bordered="false"
        left-arrow
        :title="`我的志愿表`"
        @click-left="navigatorBack"
      />
      <HeaderTip :user-info="userStore.userInfo" />
      <view class="flex justify-between items-center px-[32rpx] py-[16rpx]">
        <view class="flex items-center gap-[20rpx] text-[#303030]">
          <view
            @click="handleShow(1)"
            class="flex justify-between items-center text-[28rpx] line-height-none text-nowrap"
          >
            <view class="text-nowrap w-[56rpx]">院校</view>
            <view class="i-carbon-caret-down"></view>
          </view>

          <view
            @click="handleShow(2)"
            class="flex justify-between items-center text-[28rpx] line-height-none text-nowrap"
          >
            <view class="text-nowrap w-[56rpx]">地域</view>

            <view class="i-carbon-caret-down"></view>
          </view>

          <view
            @click="handleShow(4)"
            class="flex justify-between items-center text-[28rpx] line-height-none text-nowrap"
          >
            <view class="text-nowrap w-[56rpx]">专业</view>
            <view class="i-carbon-caret-down"></view>
          </view>
        </view>

        <SearchInput @confirm="handleChange" placeholder="请输入意向院校" />
      </view>

      <view class="flex gap-[10rpx] px-[32rpx] border-top justify-between">
        <view
          class="flex justify-between items-center text-[28rpx] line-height-none"
          @click="handleShow(3)"
        >
          {{ collegeSearch.tModelValue === '-1' ? `全部${total}` : collegeSearch.tModel }}
          <view class="i-carbon-caret-down"></view>
        </view>

        <!-- <Slider
          v-model:modelValue="sliderValue"
          :min="minScore"
          :max="maxScore"
          :step="1"
          :range="true"
          @change="handleSliderChange"
          class="custom-slider"
        /> -->
        <NumberInterval
          v-model:modelValue="sliderValue"
          :min="minScore"
          :max="maxScore"
          @change="handleSliderChange"
          class="w-[537rpx]"
        />
      </view>
    </template>

    <!-- 滚动主体 -->
    <view
      class="item-wrapper"
      :id="`zp-id-${item.zp_index}`"
      :key="item.zp_index"
      v-for="item in schoolList"
      @click="itemClick(item)"
    >
      <ScrollListItem
        :college="item"
        :score="score"
        :major-count="majorCount"
        @show-action="handleShowAction"
      />
    </view>

    <template #bottom>
      <view class="pb-safe px-[32rpx] pt-[32rpx] bg-[#fff]">
        <view
          :class="`h-[80rpx] rounded-[8rpx] bg-[#1580FF] flex items-center justify-center text-[#fff] ${majorCount === 0 ? 'disabled-btn' : ''}`"
          @click="handlePreview"
        >
          预览志愿表{{ majorCount ? `(${majorCount})` : '' }}
        </view>
      </view>
    </template>
  </z-paging>
  <ActionSheet v-model:show="show" :title="actionTitle" :showClose="true">
    <Region
      v-show="actionType === 2"
      width="210rpx"
      height="60rpx"
      checkgroupStyle="display: grid;grid-template-columns: repeat(4, 1fr);gap: 16rpx;padding: 24rpx 24rpx 36rpx;"
      @change-name="handleRegionName"
    />

    <FilterMenu v-show="actionType === 1" :show-phase="false" ref="filterMenuRef" :menuBit="28" />
    <CustomPickerView
      v-show="actionType === 3"
      :list="typeModelList"
      v-model:modelValue="collegeSearch.tModelValue"
      value-key="value"
      label-key="name"
      @change="handleTypeModelChange"
    />
    <FilterMajorList ref="filterMajorRef" v-show="actionType === 4" :type="1050" class="h-full" />
    <template #footer>
      <view class="flex items-center justify-between mx-[32rpx] gap-[20rpx]">
        <view class="cancel-btn" @click="show = false" v-if="actionType !== 4">取消</view>
        <view class="cancel-btn" @click="resetMajorList" v-else>重置</view>
        <view class="submit-btn" @click="handleConfirm">查看结果</view>
      </view>
    </template>
  </ActionSheet>

  <ScrollListItemAction
    v-model:show="collegeShow"
    :college="showCollegeItem"
    :major-count="majorCount"
    :score="score"
  />
</template>

<script lang="ts" setup>
import SearchInput from '@/pages-sub/components/input/SearchInput.vue'
import ActionSheet from '@/pages-sub/components/ActionSheet.vue'
import Region from '@/pages-sub/home/components/Region.vue'
import FilterMenu from '@/pages-sub/home/components/FilterMenu.vue'
// import Slider from '@/pages-sub/components/Slider.vue'
import NumberInterval from '@/pages-sub/components/interval/NumberInterval.vue'
import CustomPickerView from '@/pages-sub/components/CustomPickerView.vue'

import ScrollListItemAction from './components/ScrollListItemAction.vue'

import ScrollListItem from './components/ScrollListItem.vue'
import HeaderTip from './components/HeaderTip.vue'

import Navbar from '@/pages-sub/components/navbar/Navbar.vue'

import { getPlanProListByFilter } from '@/service/index/api'

import { useUserStore } from '@/store/user'
import { coverTypeModel, useScore } from './composable/useWishesList'

import FilterMajorList from './components/FilterMajorList.vue'

const userStore = useUserStore()

const navigatorBack = () => {
  uni.navigateBack()
}

const schoolList = ref([])
const paging = ref(null)
const filterMenuRef = ref(null)
const filterMajorRef = ref(null)

const location = ref(userStore.userInfo.estimatedAchievement.provinceCode)

const showCollegeItem = ref(null)
const collegeShow = ref(false)
const handleShowAction = (item) => {
  showCollegeItem.value = item
  collegeShow.value = true
}

const total = ref(0)
const typeModelList = ref([])
const handleTypeModelChange = ({ item }) => {
  collegeSearch.value.tModelValue = item.value
  collegeSearch.value.tModel = item.name
}

const majorCount = computed(() => {
  return userStore.userInfo.wishList.reduce((a, b) => a + (b?.vItems?.length || 0), 0)
})

const queryList = (page: number, pageSize: number) => {
  getPlanProListByFilter({
    pageIndex: page,
    pageSize: pageSize,
    location: location.value,
    p: userStore.userInfo.estimatedAchievement.sp,
    subjects: userStore.userInfo.estimatedAchievement.subjectGroup.split(','),
    score: +userStore.userInfo.estimatedAchievement.expectedScore,
    batchName: userStore.userInfo.batchName,
    startscore: sliderValue.value[0],
    endscore: sliderValue.value[1],
    province: province.value,
    nature: collegeSearch.value.nature,
    feature: collegeSearch.value.feature,
    majors: collegeSearch.value.majors,
    keyword: searchValue.value,
    type: collegeSearch.value.tModelValue === '-1' ? null : +collegeSearch.value.tModelValue,
    utype: collegeSearch.value.utype,
    secondmajor: collegeSearch.value.secondmajor,
  }).then((resp) => {
    if (resp.code === 200) {
      paging.value.complete((resp.result as { rows: any[] }).rows)
      const tModels = (resp.result as { tModel: { [key: string]: number } }).tModel
      total.value = Object.values(tModels).reduce((sum: number, n: number) => sum + n, 0)
      typeModelList.value = coverTypeModel((resp.result as { tModel: any }).tModel, total.value)
      let _tem = typeModelList.value.filter(
        (item) => item.value === collegeSearch.value.tModelValue,
      )
      if (_tem.length > 0) {
        collegeSearch.value.tModel = _tem[0].name
      }
    }
  })
}

const virtualListChange = (_vList) => {
  schoolList.value = _vList
}

const itemClick = (item) => {
  uni.navigateTo({ url: `/pages-sub/home/college/info?collegeId=${item.uId}` })
}

const collegeSearch = ref({
  nature: [],
  feature: [],
  majors: [], //专业列表
  tModel: '',
  utype: [],
  tModelValue: '-1',
  secondmajor: [], //二级专业列表
})

const show = ref(false)
const actionTitle = ref('')
const actionType = ref(1)
const handleConfirm = () => {
  show.value = false
  if (actionType.value === 1) {
    let _cur = filterMenuRef.value.handleConfirm()
    collegeSearch.value.feature = _cur.chooseCollegeFeature
    collegeSearch.value.nature = _cur.chooseNature
    collegeSearch.value.utype = _cur.chooseUniType
  } else if (actionType.value === 4) {
    let _cur = filterMajorRef.value.getSearchParam()
    let temSet = new Set()
    collegeSearch.value.majors = []
    _cur.forEach((item) => {
      temSet.add(item.pName)
      collegeSearch.value.majors.push(item.zymc)
    })
    collegeSearch.value.secondmajor = Array.from(temSet.values())
  }
  paging.value.reload()
}

const handleShow = (type: number) => {
  if (type === 1) {
    actionTitle.value = '院校'
  } else if (type === 2) {
    actionTitle.value = '地域'
  } else if (type === 4) {
    actionTitle.value = '专业筛选'
  }

  actionType.value = type
  show.value = true
}

const searchValue = ref('')
const handleChange = (value: string) => {
  searchValue.value = value
  paging.value.reload()
}

const province = ref([])
const handleRegionName = (val: string[]) => {
  province.value = val
}

const sliderValue = ref([0, 0])
const handleSliderChange = (val) => {
  collegeSearch.value.tModelValue = '-1'
  paging.value.reload()
}

const { score, minScore, maxScore } = useScore(
  userStore.userInfo.estimatedAchievement.provinceCode,
  userStore.userInfo.batchName,
  userStore.userInfo.estimatedAchievement.requireSubject,
)

watch(
  () => maxScore.value,
  () => {
    if (maxScore.value !== 0) {
      sliderValue.value[0] =
        +userStore.userInfo.estimatedAchievement.expectedScore < minScore.value + 40
          ? minScore.value
          : +userStore.userInfo.estimatedAchievement.expectedScore - 40

      sliderValue.value[1] =
        +userStore.userInfo.estimatedAchievement.expectedScore > maxScore.value - 40
          ? maxScore.value
          : +userStore.userInfo.estimatedAchievement.expectedScore + 40
    }
  },
  { immediate: true },
)

const isEdit = ref(false)

const handlePreview = () => {
  if (majorCount.value === 0) {
    return
  }
  if (isEdit.value) {
    uni.navigateTo({
      url: `/pages-sub/home/wishesList/wishesList?editType=edit&typeName=智能填报&id=${userStore.userInfo.wishListId}&change=true`,
    })
  } else {
    uni.navigateTo({
      url: `/pages-sub/home/wishesList/wishesList?editType=add&typeName=智能填报`,
    })
  }
}

const resetMajorList = () => {
  filterMajorRef.value.handleClear()
}

onShow(() => {
  if (userStore.userInfo.wishListId) {
    isEdit.value = true
  }
})
</script>

<style lang="scss" scoped>
@import '@/pages-sub/home/styles/picker-view-btn.scss';
@import '@/pages-sub/home/styles/grid-checkbox.scss';

.custom-slider {
  flex: 1 1 auto;
}

.border-top {
  border-top: 2rpx solid #ededed;
}

.disabled-btn {
  background-color: #f5f5f5 !important;
  color: #999 !important;
}
</style>
