<template>
  <ie-page bg-color="#F6F8FA" :fix-height="true">
    <ie-navbar :title="title" />
    <view class="mt-16 bg-white py-10">
      <view class="">
        <uv-cell-group :border="false">
          <uv-cell isLink :border="true" :cellStyle="cellStyle" :rightIconStyle="rightIconStyle"
            @click="handleUniversitySelect">
            <template #title>
              <text class="text-30 text-fore-subtitle whitespace-nowrap">选择院校</text>
            </template>
            <template #value>
              <text v-if="form.universityName" class="mx-10 text-30 text-fore-title">
                {{ form.universityName }}
              </text>
              <text v-else class="mr-10 text-30 text-fore-placeholder">请选择</text>
            </template>
          </uv-cell>
          <uv-cell isLink :border="false" :cellStyle="cellStyle" :rightIconStyle="rightIconStyle"
            @click="handleMajorSelect">
            <template #title>
              <text class="text-30 text-fore-subtitle whitespace-nowrap">选择专业</text>
            </template>
            <template #value>
              <text v-if="form.majorName" class="mx-10 text-30 text-fore-title">
                {{ form.majorName }}
              </text>
              <text v-else class="mr-10 text-30 text-fore-placeholder">请选择</text>
            </template>
          </uv-cell>
        </uv-cell-group>
      </view>
    </view>
    <ie-safe-toolbar :height="84" :shadow="false">
      <view class="px-46 pt-24">
        <ie-button type="primary" @click="handleAdd">确认</ie-button>
      </view>
    </ie-safe-toolbar>
    <ie-popup ref="popupRef" title="选择专业" @confirm="handleConfirm">
      <view class="h-[50vh] bg-white px-30 pt-20 flex flex-col">
        <view>
          <uv-search v-model="keyword" shape="square" :showAction="false" placeholder="请输入专业名称" />
        </view>
        <view class="mt-20 flex-1 min-h-1">
          <scroll-view scroll-y class="h-full">
            <view v-for="item in filteredMajorList" :key="item.id"
              class="px-20 py-16 bg-white sibling-border-top flex items-center gap-x-20" @click="handleSelect(item)">
              <view class="flex-1 min-w-1 flex-shrink-0">
                <view class="flex items-center gap-x-10 text-fore-title">
                  <span class="text-30 " :class="[isActive(item) ? 'text-primary' : 'text-fore-title']">{{
                    item.name
                  }}</span>
                  <span v-if="item.notice" class="text-22 text-fore-light flex-1 min-w-1 ellipsis-1"
                    :class="[isActive(item) ? 'text-primary' : 'text-fore-title']">{{
                      `（${item.notice}）`
                    }}</span>
                </view>
                <view class="mt-6 text-22 text-fore-light"
                  :class="[isActive(item) ? 'text-primary' : 'text-fore-light']">
                  {{
                    item.ancestors
                  }}
                </view>
              </view>
              <uv-icon v-if="isActive(item)" name="checkmark" size="20" color="#31A0FC" />
            </view>
          </scroll-view>
        </view>
      </view>
    </ie-popup>
  </ie-page>
</template>

<script lang="ts" setup>
import { useTransferPage } from '@/hooks/useTransferPage';
import { University } from '@/types/university';
import { DirectedSchool, UniversityMajor } from '@/types/study';
import { SelectedUniversityMajor } from '@/types/voluntary';
import { getUniversityMajorList } from '@/api/modules/university';
import { useUserStore } from '@/store/userStore';
import { routes } from "@/common/routes";
import { UniversityPickerPageOptions } from "@/types/transfer";

const userStore = useUserStore();
const { prevData, transferTo, transferBack } = useTransferPage<UniversityPickerPageOptions, any>();
const { directedSchoolList } = toRefs(userStore);
const form = ref<Partial<SelectedUniversityMajor>>({});
const keyword = ref('');
const cellStyle = {
  padding: '20rpx 40rpx'
}
const rightIconStyle = {
  fontSize: '14px'
}
const majorList = ref<UniversityMajor[]>([]);
const filteredMajorList = computed(() => {
  return majorList.value.filter(item => item.name.includes(keyword.value));
});
const title = computed(() => prevData.value.title || '添加定向院校')
const handleUniversitySelect = () => {
  transferTo(routes.universityPicker).then((res: any) => {
    if (res) {
      const university = res as University;
      if (university.code !== form.value.universityId) {
        selectedMajor.value = null;
        form.value.majorId = '';
        form.value.majorName = '';
      }
      form.value.universityId = university.code;
      form.value.universityName = university.name;
      form.value.universityLogo = university.logo;
      form.value.info = university;
      loadMajorList(university.code);
    }
  });
}

const popupRef = ref();
const selectedMajor = ref<Pick<UniversityMajor, 'ancestors' | 'code' | 'id' | 'name'> | null>(null);
const handleMajorSelect = () => {
  if (!form.value.universityId) {
    uni.$ie.showToast('请选择院校');
    return;
  }
  keyword.value = '';
  if (form.value.majorId) {
    selectedMajor.value = {
      ancestors: form.value.majorAncestors || '',
      code: form.value.majorId || '',
      id: Number(form.value.majorId),
      name: form.value.majorName || ''
    }
  } else {
    selectedMajor.value = null;
  }
  popupRef.value.open();
}

const handleConfirm = () => {
  if (!selectedMajor.value) {
    uni.$ie.showToast('请选择专业');
    return;
  }
  form.value.majorAncestors = selectedMajor.value.ancestors;
  form.value.majorId = selectedMajor.value.id.toString();
  form.value.majorName = selectedMajor.value.name;
  popupRef.value.close();
}
const handleSelect = (item: UniversityMajor) => {
  selectedMajor.value = item;
}

const handleAdd = async () => {
  if (!form.value.universityId) {
    uni.$ie.showToast('请选择院校');
    return;
  }
  if (!form.value.majorId) {
    uni.$ie.showToast('请选择专业');
    return;
  }
  if (prevData.value.fromVoluntary === true) {
    // 志愿类
    if (prevData.value.selectedUniversityId === form.value.universityId &&
      prevData.value.selectedMajorId === form.value.majorId) {
      return uni.$ie.showToast('请勿选择相同院校专业')
    }
    return transferBack(form.value)
  }
  // 检查数据是否已存在
  const historyData = directedSchoolList.value;
  const isExist = historyData.some(item => item.universityId === form.value.universityId && item.majorId === form.value.majorId);
  if (isExist) {
    uni.$ie.showToast('该院校专业已存在');
    return;
  }
  uni.$ie.showLoading();
  const params = {
    ...form.value,
    code: form.value.universityId
  } as DirectedSchool;
  await userStore.saveDirectedSchoolList([params, ...directedSchoolList.value]);
  uni.$ie.hideLoading();
  uni.$ie.showSuccess('保存成功');
  setTimeout(() => {
    transferTo('/pagesStudy/pages/targeted-setting/targeted-setting', {
      type: 'redirectTo'
    });
  }, 600);
}
const isActive = (item: UniversityMajor) => {
  return selectedMajor.value && selectedMajor.value.id === item.id;
}
const loadMajorList = async (universityId: string) => {
  uni.$ie.showLoading();
  const { data } = await getUniversityMajorList({ universityId });
  majorList.value = data;
  uni.$ie.hideLoading();
}

onLoad(() => {
  handleUniversitySelect();
});
</script>

<style lang="scss" scoped></style>
