<script setup>
import {ref} from "vue";
import {useQuasar} from "quasar";
import activityApi from "app/src/api/activity/activity";
import dayjs from "dayjs";
import AdminActivityAddPane from "pages/admin/activity/AdminActivityAddPane.vue";
import AdminActivityEditPane from "pages/admin/activity/AdminActivityEditPane.vue";

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

const activityListColumns = [
  {name: 'name', align: 'left', label: '活动名称', sortable: true},
  {name: 'start', align: 'left', label: '开始', field: 'start', sortable: true},
  {name: 'end', align: 'left', label: '结束', field: 'end', sortable: true},
  {name: 'term', align: 'left', label: '学期', field: 'term', sortable: true},
  {name: 'status', align: 'left', label: '状态', field: 'status', sortable: true},
  {name: 'edit', align: 'left', label: '操作', field: 'edit'}
]

const activityRows = ref([])

const filter = ref('')

const loading = ref(true)

const quasar = useQuasar()

function getStatus(start, end) {
  let now = dayjs()
  if (!end.isAfter(now)) {
    return {text: '已结束', color: 'text-red'}
  } else {
    if (start.isAfter(now)) {
      return {text: '未开始', color: 'text-blue'}
    }
  }

  return {text: '进行中', color: 'text-green'}
}

// 先拿第一页的数据
async function load() {
  try {
    const response = await activityApi.list(1, 10);
    updateListData(response);
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    });
  } finally {
    loading.value = false;
  }
}

load()

function forceRefreshActivities() {
  activityRows.value = []
  activityListPagination.value.page = 1
  activityListPagination.value.rowsPerPage = 10
  refreshActivities({pagination: {page: 1, rowsPerPage: 10}})
}

async function refreshActivities(props) {
  const {page, rowsPerPage} = props.pagination

  loading.value = true
  try {
    const response = await activityApi.list(page, rowsPerPage);
    updateListData(response);
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
  } finally {
    loading.value = false;
  }
}

function updateListData(response) {
  activityListPagination.value.page = response.current
  activityListPagination.value.rowsNumber = response.total
  activityListPagination.value.rowsPerPage = response.pageSize

  let tmp = []
  response.result.forEach(data => {
    let start = dayjs(data.startTime)
    let end = dayjs(data.endTime)
    tmp.push({
      id: data.id,
      name: data.name,
      start: start.format('YYYY-MM-DD HH:mm:ss'),
      end: end.format('YYYY-MM-DD HH:mm:ss'),
      term: data.term,
      status: getStatus(start, end),
    })
  })

  activityRows.value.splice(0, activityRows.value.length, ...tmp)
}

const activityAddDialogState = ref(false)

function openOrCloseActivityAddDialog() {
  activityAddDialogState.value = !activityAddDialogState.value
}

const activityInfoForm = ref({
  id: undefined,
  name: undefined,
  start: undefined,
  end: undefined,
  term: undefined,
  status: undefined,
})

const activityEditDialogState = ref(false)

async function openActivityEditDialog(id) {
  if (activityEditDialogState.value === false) {
    activityInfoForm.value.id = id
    loading.value = true
    try {
      const data = await activityApi.getInfo(id)
      activityInfoForm.value.id = data.id
      activityInfoForm.value.name = data.name
      activityInfoForm.value.start = dayjs(data.startTime).format('YYYY-MM-DD')
      activityInfoForm.value.end = dayjs(data.endTime).format('YYYY-MM-DD')
      activityInfoForm.value.term = data.term

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

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

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

function deleteActivityAction(id, name) {
  const dialog = quasar.dialog({
    transitionShow: 'fade',
    transitionHide: 'fade',
    title: '确认？',
    message: '真的要删除"' + name + '"？',
    cancel: true,
  })
    .onCancel(() => dialog.hide())
    .onOk(() => doDeleteActivity(id))
}
</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="activityListColumns" :rows="activityRows"
               class="table-admin max-w-full">
        <template v-slot:top>
          <q-btn @click="openOrCloseActivityAddDialog" class="q-ml-sm" color="primary" icon="add" label="添加"/>
          <q-space/>
          <!--          <q-input outlined dense debounce="300" color="primary" v-model="filter" placeholder="搜索任意字段">-->
          <!--            <template v-slot:append>-->
          <!--              <q-icon name="search"/>-->
          <!--            </template>-->
          <!--          </q-input>-->
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="name" :props="props">
              <span class="break-all whitespace-normal" style="max-width: 20vw;">{{ props.row.name }}</span>
            </q-td>
            <q-td key="start" :props="props">{{ props.row.start }}</q-td>
            <q-td key="end" :props="props">{{ props.row.end }}</q-td>
            <q-td key="term" :props="props">{{ props.row.term }}</q-td>
            <q-td key="status" :props="props"><span :class="props.row.status.color">{{ props.row.status.text }}</span>
            </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>
                <router-link :to="`/admin/activity/${props.row.id}/targets`">
                  <q-btn outline label="设置活动对象" icon="edit"/>
                </router-link>
                <q-btn @click="deleteActivityAction(props.row.id, props.row.name)" outline color="red" label="删除"
                       icon="delete"></q-btn>
              </div>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </div>

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

    <AdminActivityAddPane v-model:open="activityAddDialogState" @on-ok="forceRefreshActivities()"/>

    <AdminActivityEditPane v-model:activity-edit-form="activityInfoForm"
                           v-model:open="activityEditDialogState"
                           @on-ok="forceRefreshActivities()"/>
  </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>
