<script setup>
import {ref, watch} from "vue";
import {useQuasar} from "quasar";
import activityApi from "app/src/api/activity/activity";
import activityTargetApi from "app/src/api/activity/activity_target";

import {useRoute, useRouter} from "vue-router";
import AdminActivityTargetEditPane from "pages/admin/activity/targets/AdminActivityTargetEditPane.vue";
import AdminActivityTargetAddPane from "pages/admin/activity/targets/AdminActivityTargetAddPane.vue";
import {useMajorsStore} from "stores/majors";

const route = useRoute()
const router = useRouter()

const activityId = Number(route.params.id)

const majorStore = useMajorsStore()

async function init() {
  try {
    const activityTargetList = await activityTargetApi.list(activityId)

    activityTargetListPagination.value.page = 1
    activityTargetListPagination.value.rowsNumber = activityTargetList.length
    activityTargetListPagination.value.rowsPerPage = 10

    let tmp = []
    activityTargetList.forEach(data => {
      tmp.push({
        id: data.id,
        major: data.major,
        grade: data.grade,
        course: data.course,
      })
    })

    activityTargetRows.value = tmp
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
    console.warn(e)
  } finally {
    loading.value = false
  }
}

init()

function getMajorName(majorId) {
  const majors = majorStore.majors
  for (const major of majors) {
    if (major.id === majorId) {
      return major.name
    }
  }

  return ''
}

const activityTargetListPagination = ref({
  sortBy: 'desc',
  descending: false,
  page: 1,
  rowsPerPage: 100,
  rowsNumber: 10
})

const activityTargetColumns = [
  {name: 'grade', align: 'left', label: '年级', field: 'grade', sortable: true},
  {name: 'major', align: 'left', label: '专业', field: 'major', sortable: true},
  {name: 'course', align: 'left', label: '课程', field: 'course'},
  {name: 'edit', align: 'left', label: '操作', field: 'edit'},
]

const activityTargetRows = ref([])

const filter = ref('')

const loading = ref(true)

const quasar = useQuasar()

async function refreshActivityTargets() {
  loading.value = true
  try {
    const response = await activityTargetApi.list(activityId)

    activityTargetListPagination.value.page = 1
    activityTargetListPagination.value.rowsNumber = response.length
    activityTargetListPagination.value.rowsPerPage = 10

    let tmp = []
    response.forEach(data => {
      tmp.push({
        id: data.id,
        major: data.major,
        grade: data.grade,
        course: data.course,
      })
    })

    activityTargetRows.value = tmp
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
  } finally {
    loading.value = false
  }
}

/**
 * @typedef {{
 *         "id": number,
 *         "activity": number,
 *         "grade": number,
 *         "major": number,
 *         "course": number[],
 *         "createTime": string,
 *         "editTime": string
 *     }} ActivityTarget
 */

/**
 *
 * @type {import('vue').Ref<ActivityTarget>}
 */
const activityTargetInfoRef = ref({})

const activityAddDialogState = ref(false)

const activityEditDialogState = ref(false)

async function openActivityEditDialog(id) {
  if (activityEditDialogState.value === false) {
    loading.value = true
    try {
      console.log('id', id)
      activityTargetInfoRef.value = await activityTargetApi.getInfo(id)
      activityEditDialogState.value = true
    } catch (e) {
      console.warn(e)
      quasar.dialog({
        transitionShow: 'fade',
        transitionHide: 'fade',
        title: '啊哈？',
        message: e.message
      })
    } finally {
      loading.value = false
    }
  }
}

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

  try {
    await activityTargetApi.add(activityId, target)
    dialog.hide()
    await refreshActivityTargets()
  } catch (e) {
    dialog.update({
      title: '啊哈？',
      message: e.message,
      progress: false,
      ok: true
    })
  }
}

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

  try {
    await refreshActivityTargets()
    dialog.hide()
  } catch (e) {
    dialog.update({
      title: '啊哈？',
      message: e.message,
      progress: false,
      ok: true
    })
  }
}

function deleteActivityTargetAction(id) {
  const dialog = quasar.dialog({
    transitionShow: 'fade',
    transitionHide: 'fade',
    title: '确认？',
    message: '真的要删除？',
    cancel: true,
  })
    .onCancel(() => dialog.hide())
    .onOk(() => deleteActivityTarget(id))
}

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

  try {
    await activityTargetApi.deleteActivityTarget(id)
    dialog.hide()
    await refreshActivityTargets()
  } catch (e) {
    dialog.update({
      title: '啊哈？',
      message: e.message,
      progress: false,
      ok: true
    })
  } finally {
    dialog.hide()
  }
}

</script>

<template>
  <div class="flex flex-col gap-4 px-6 pt-1 pb-6 max-w-full">
    <div>
      <h1 class="text-3xl mb-1">管理活动对象</h1>
      <p>在这里可以添加/删除选课活动中适用的年级，并且指定该年级可选的课程</p>
    </div>

    <div class="flex flex-col gap-1 max-w-full">
      <q-table :loading="loading" :filter="filter" :columns="activityTargetColumns" :rows="activityTargetRows"
               class="table-admin max-w-full">
        <template v-slot:top>
          <q-btn @click="activityAddDialogState = true" class="q-ml-sm" color="primary" icon="add" label="添加"/>
          <q-space/>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="grade" :props="props">{{ props.row.grade }}</q-td>
            <q-td key="major" :props="props">{{ getMajorName(props.row.major) }}</q-td>
            <q-td key="course" :props="props">{{ props.row.course.join('，') }}</q-td>

            <q-td key="edit" :props="props">
              <div class="flex flex-row justify-start gap-4 w-full transition-all">
                <q-btn @click="openActivityEditDialog(props.row.id)" outline label="查看/修改"
                       icon="edit"></q-btn>
                <q-btn @click="deleteActivityTargetAction(props.row.id)" outline color="red" label="删除"
                       icon="delete"></q-btn>
              </div>
            </q-td>
          </q-tr>
        </template>
      </q-table>

      <div>
        <router-link to="/admin/activity">
          <q-btn class="text-base w-fit mt-4" color="primary" outline label="返回选课活动页"></q-btn>
        </router-link>
      </div>

    </div>

    <q-inner-loading
      :showing="loading"
      label="与服务器通信中..."
      label-class="text-teal"
      label-style="font-size: 1.1em"
      color="gray"
      class="z-10"
    />

    <AdminActivityTargetAddPane v-model:open="activityAddDialogState" @on-ok="addActivityTargetAction"/>

    <AdminActivityTargetEditPane v-model:data="activityTargetInfoRef" v-model:open="activityEditDialogState"
                                 @on-ok="updateActivityAction"/>
  </div>
</template>

<style lang="sass">
.table-admin
  transition: all 0.2s linear 0.2s

  th, td
    font-size: 1rem !important

  th
    font-weight: bold

  .q-table__top,
  .q-table__bottom,
  thead tr:first-child th
    background-color: white

  thead tr:first-child th:first-child
    background-color: white

  tbody tr:nth-child(odd)
    background-color: rgb(248, 248, 248)

  tbody tr:nth-child(even)
    background-color: white

  th:first-child,
  td:first-child
    position: sticky
    left: 0
    z-index: 1

  th:first-child
    z-index: 3 !important

  thead tr th
    position: sticky
    z-index: 2

  thead tr:first-child th
    top: 0
</style>

<style scoped lang="sass">

</style>
