<script setup>
import {ref} from "vue";
import {useQuasar} from "quasar";
import courseApi from "app/src/api/course/course";
import AdminCourseAddPane from "pages/admin/course/AdminCourseAddPane.vue";
import AdminCourseEditPane from "pages/admin/course/AdminCourseEditPane.vue";
import majorManager from "app/src/api/major/major";
import AdminCourseTeacherSelectingPane from "pages/admin/course/AdminCourseTeacherSelectingPane.vue";

const courseListPagination = ref({
  sortBy: 'id',
  descending: true,
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 10
})

const courseListColumns = [
  // {name: 'id', align: 'left', label: 'id', sortable: true},
  {name: 'name', align: 'left', label: '课程', sortable: true},
  {name: 'courseHours', align: 'left', label: '课时', field: 'courseHours', sortable: true},
  {name: 'examRatio', align: 'left', label: '考试成绩占比', field: 'examRatio', sortable: true},
  {name: 'term', align: 'left', label: '春/秋学期', field: 'springTerm', sortable: true},
  {name: 'edit', align: 'left', label: '操作', field: 'edit'}
]

const courseRows = ref([])

const filter = ref('')

const loading = ref(false)

const quasar = useQuasar()

async function init() {
  loading.value = true

  try {
    const response = await courseApi.list(1, 10)
    updateListData(response)
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
  }

  loading.value = false
}

init()

function forceRefreshCourses() {
  courseRows.value = []
  courseListPagination.value.page = 1
  courseListPagination.value.rowsPerPage = 10
  refreshCourses({pagination: {page: 1, rowsPerPage: 10}})
}

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

  loading.value = true;

  try {
    const response = await courseApi.list(page, rowsPerPage === 0 ? 999 : rowsPerPage);
    updateListData(response);
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    });
  }

  loading.value = false;
}

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

  courseRows.value.splice(0, courseRows.value.length, ...response.result)
}

const courseAddDialogState = ref(false)

function openCourseAddDialog() {
  courseAddDialogState.value = true
}

const courseInfoEditForm = ref({
  id: 0,
  name: 'undefined',
  courseHours: 0,
  examRatio: 1.0,
  springTerm: 'true'
})

const courseEditDialogState = ref(false)

async function openCourseEditDialog(id) {
  if (courseEditDialogState.value === false) {
    courseInfoEditForm.value.id = id;
    loading.value = true
    try {
      const data = await courseApi.getInfo(id);

      courseInfoEditForm.value.id = data.id;
      courseInfoEditForm.value.name = data.name;
      courseInfoEditForm.value.courseHours = data.courseHours;
      courseInfoEditForm.value.examRatio = data.examRatio;
      courseInfoEditForm.value.springTerm = data.springTerm + '';

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

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

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

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

const courseTeacherSelectingDialogState = ref(false)
const adminCourseTeacherSelectingPane = ref()

async function openCourseTeacherSelectingDialog(id) {

  loading.value = true
  await adminCourseTeacherSelectingPane.value.init(id)
  loading.value = false

  courseTeacherSelectingDialogState.value = true
}

</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 :filter="filter" :columns="courseListColumns" :rows="courseRows"
               v-model:pagination="courseListPagination" :loading="loading" @request="refreshCourses"
               class="table-admin max-w-full">
        <template v-slot:top>
          <q-btn class="q-ml-sm" color="primary" icon="add" @click="openCourseAddDialog" label="添加"/>
          <q-space/>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <!--            <q-td key="id" :props="props">{{ props.row.id }}</q-td>-->
            <q-td key="name" :props="props">
              <span class="break-all whitespace-normal">{{ props.row.name }}</span>
            </q-td>
            <q-td key="courseHours" :props="props">{{ props.row.courseHours }}</q-td>
            <q-td key="examRatio" :props="props">{{ props.row.examRatio }}</q-td>
            <q-td key="term" :props="props" :class="props.row.springTerm === true ? 'text-green' : 'text-amber-700'">
              {{ props.row.springTerm === true ? '春季期' : '秋季期' }}
            </q-td>
            <q-td key="edit" :props="props">
              <div class="flex flex-row justify-start gap-4 w-full transition-all">
                <q-btn @click="openCourseEditDialog(props.row.id)" outline label="查看/修改" icon="edit"/>
                <q-btn @click="openCourseTeacherSelectingDialog(props.row.id)" outline label="设置上课教师"
                       icon="group"/>
                <router-link :to="'/admin/schedule/' + props.row.id">
                  <q-btn outline label="上课安排设置" icon="calendar_today"/>
                </router-link>
                <router-link :to="`/admin/course/${props.row.id}/status`">
                  <q-btn outline label="查看选课情况" icon="event_available"/>
                </router-link>
                <q-btn @click="deleteCourseAction(props.row.id, props.row.name)" outline color="red" label="删除"
                       icon="delete"/>
              </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"
    />

    <AdminCourseAddPane v-model:open="courseAddDialogState" @on-ok="forceRefreshCourses"/>

    <AdminCourseEditPane v-model:course-info-form="courseInfoEditForm" v-model:open="courseEditDialogState"
                         @on-ok="forceRefreshCourses"/>

    <AdminCourseTeacherSelectingPane ref="adminCourseTeacherSelectingPane"
                                     v-model:open="courseTeacherSelectingDialogState"/>
  </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>
