<script setup>

import dayjs from "dayjs";
import activityApi from "app/src/api/activity/activity";
import {useQuasar} from "quasar";

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

const open = defineModel('open')
const activityEditForm = defineModel("activityEditForm", {
  required: true,
  default: {
    id: 0,
    name: 'undefined',
    start: '2024/06/26',
    end: '2024/07/26',
    term: '2023-2024-2',
  }
})

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 quasar = useQuasar()

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

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

    await activityApi.update(activityEditForm.value.id, 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="activityEditForm.name" class="text-base" outlined label="活动名称"></q-input>
          <div class="flex flex-row gap-4">
            <q-input v-model="activityEditForm.start" outlined type="date" label="开始时间"/>
            <q-input v-model="activityEditForm.end" outlined type="date" label="结束时间"/>
          </div>
          <q-select :options="terms" v-model="activityEditForm.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="updateActivityAction()">好的</q-btn>
        </q-card-actions>
      </div>

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

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