<script setup>

import {computed, ref} from "vue";
import dayjs from "dayjs";
import termUtils from "app/src/utils/term";
import {useRoute} from "vue-router";
import {useMajorsStore} from "stores/majors";
import majorManager from "app/src/api/major/major";
import courseApi from "app/src/api/course/course";
import {useQuasar} from "quasar";

const func = defineEmits(['onOk'])

const open = defineModel('open')

/**
 *
 * @type {import('vue').Ref<{
 *             "id": number,
 *             "activity": number,
 *             "grade": number,
 *             "major": number,
 *             "course": number[],
 *             "createTime": string,
 *             "editTime": string
 *         }>}
 */
const data = ref({})

async function action() {
  func('onOk', {
    "grade": data.value.grade,
    "major": data.value.major,
    "course": data.value.course
  })
}

const terms = []

function generateTerm() {
  const now = dayjs()
  const thisYear = now.year()
  for (let i = -1; i < 8; i++) {
    const year = thisYear + i
    terms.push(`${year}-${year + 1}-1`)
    terms.push(`${year}-${year + 1}-2`)
  }
}

generateTerm()

const loading = ref(false)

const majorsStore = useMajorsStore()
const courseList = ref([])

const quasar = useQuasar()

function addMajorAction() {
  quasar.dialog({
    transitionShow: 'fade',
    transitionHide: 'fade',
    title: '添加专业',
    message: '输入专业名称<br>需要注意的是，此处的专业名称必须与<strong>教务处学生信息</strong>中显示的专业名称完全一致，否则学生专业可能会匹配不上',
    prompt: {
      model: '',
      type: 'text' // optional
    },
    cancel: true,
    persistent: true,
    html: true,
  })
    .onOk(addMajor)
}

async function addMajor(majorName) {
  const dialog = quasar.dialog({
    transitionShow: 'fade',
    transitionHide: 'fade',
    message: '与服务器通信中...',
    progress: true,
    persistent: true,
    ok: false
  })

  try {
    await majorManager.add(majorName);
    await majorsStore.refreshMajors();
  } catch (e) {
    dialog.update({ title: '啊哈？', message: e });
  } finally {
    dialog.hide();
  }
}

const pageSize = 20
let nextPage = 2
let lastPage = 1
let total = 0

async function onScroll(param) {
  const {index, to} = param
  if (loading.value !== true && nextPage < lastPage && to < total) {
    loading.value = true
    try {
      const pageResult = await courseApi.listCourseNames(nextPage, pageSize)
      pageResult.result.forEach(d => courseList.value.push({value: d.id, label: d.name}))
      nextPage++
    } catch (e) {
      quasar.dialog({
        transitionShow: 'fade',
        transitionHide: 'fade',
        title: '啊哈？',
        message: e.message
      })
    } finally {
      loading.value = false
    }
  }
}

async function init() {
  const pageResult = await courseApi.listCourseNames(1, pageSize)
  pageResult.result.forEach(d => courseList.value.push({value: d.id, label: d.name}))
  nextPage = pageResult.current + 1
  lastPage = pageResult.total / pageSize + 1
  total = pageResult.total
}

init()

</script>

<template>
  <q-dialog no-shake transition-show="fade" transition-hide="fade"
            v-model="open">
    <q-card class="activity-dialog">

      <div class="sticky top-0 bg-white z-10">
        <q-card-section>
          <div class="text-h6">添加选课活动对象</div>
        </q-card-section>
      </div>

      <q-separator/>

      <q-card-section class="">
        <div class="flex flex-col gap-4">
          <span class="text-base">在这里可以添加选课活动的对象信息</span>
          <div class="flex flex-row gap-4">
            <q-input v-model="data.grade" outlined type="number" label="目标年级"/>
            <q-select class="text-base flex-grow min-w-fit" outlined v-model="data.major"
                      :options="majorsStore.majors" map-options emit-value label="目标专业"
                      :option-value="option => option.id" :option-label="option => option.name"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    啥都没有哦(′д｀ )<br>
                    （可以在左下角添加专业）
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>

          <q-select
            outlined v-model="data.course" multiple
            :options="courseList" :loading="loading" @virtual-scroll="onScroll"
            map-options emit-value label="可选课程（多选）"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey">
                  没有课程可选，请添加一些课程
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>
      </q-card-section>

      <q-separator/>

      <div class="sticky bottom-0 bg-white z-10">
        <q-card-actions align="right">
          <slot name="actions"></slot>
          <div class="flex flex-row flex-grow justify-between p-1">
            <q-btn flat @click="addMajorAction" color="primary">添加专业</q-btn>
            <div>
              <q-btn flat class="w-14" v-close-popup>算了</q-btn>
              <q-btn flat class="w-14" color="blue" @click="action" v-close-popup>好的</q-btn>
            </div>
          </div>
        </q-card-actions>
      </div>

    </q-card>
  </q-dialog>
</template>

<style scoped lang="sass">
.activity-dialog
  min-width: 35vw
</style>
