<script setup>

import {computed, ref} from "vue";
import dayjs from "dayjs";
import termUtils from "app/src/utils/term";
import activityApi from "app/src/api/activity/activity";
import {useQuasar} from "quasar";

const open = defineModel("open")

const func = defineEmits([
  'onClose', 'onOk'
])

const today = dayjs()

const activityInfoForm = ref({
  name: '',
  start: today.format("YYYY-MM-DD"),
  end: today.add(30, 'day').format("YYYY-MM-DD"),
  term: '',
})

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`)
  }

  activityInfoForm.value.term = termUtils.getCurrentTermString()
}

generateTerm()

const quasar = useQuasar()

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

  try {
    const activity = {
      name: activityInfoForm.value.name,
      start: dayjs(activityInfoForm.value.start).format(),
      end: dayjs(activityInfoForm.value.end).format(),
      term: activityInfoForm.value.term,
    }

    await activityApi.add(activity)

    dialog.hide()
    open.value = false
    func('onOk');
  } catch (e) {
    dialog.update({
      title: '啊哈？',
      message: e.message,
      progress: false,
      ok: true
    })
  }
}

</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>
          <q-input v-model="activityInfoForm.name" class="text-base" outlined label="活动名称"></q-input>
          <div class="flex flex-row gap-4">
            <q-input v-model="activityInfoForm.start" outlined type="date" label="开始时间"/>
            <q-input v-model="activityInfoForm.end" outlined type="date" label="结束时间"/>
          </div>
          <q-select :options="terms" v-model="activityInfoForm.term" class="text-base" outlined label="学期"></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>
          <q-btn flat class="w-14" v-close-popup>算了</q-btn>
          <q-btn flat class="w-14" color="blue" @click="addActivityAction">好的</q-btn>
        </q-card-actions>
      </div>
    </q-card>
  </q-dialog>
</template>

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