<script setup>
import {ref} from "vue";
import teacherManager from "app/src/api/teacher/teacher";
import {useQuasar} from "quasar";
import AdminTeacherAddPane from "pages/admin/teacher/AdminTeacherAddPane.vue";
import AdminTeacherEditPane from "pages/admin/teacher/AdminTeacherEditPane.vue";

const quasar = useQuasar()

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

const teacherListColumns = [
  {name: 'name', align: 'left', label: '教师', sortable: true},
  {name: 'id', align: 'left', label: 'id', sortable: true},
  {name: 'edit', align: 'left', label: '操作'}
]

const teacherListData = ref([])

const filter = ref('')

const loading = ref(true)

// 先拿第一页的数据
teacherManager.list(1, 10)
    .then(response => {
      teacherListPagination.value.page = response.current
      teacherListPagination.value.rowsNumber = response.total
      teacherListData.value = response.result
    })
    .catch(e => {
      quasar.dialog({
        transitionShow: 'fade',
        transitionHide: 'fade',
        title: '啊哈？',
        message: e.message
      })
    })
    .finally(() => loading.value = false)

function forceRefreshTeachers() {
  teacherListData.value = []
  teacherListPagination.value.page = 1
  teacherListPagination.value.rowsPerPage = 10
  refreshTeachers({pagination: {page: 1, rowsPerPage: 10}})
}

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

  loading.value = true
  teacherManager.list(page, rowsPerPage)
      .then(response => updateListData(response))
      .catch(e => {
        quasar.dialog({
          transitionShow: 'fade',
          transitionHide: 'fade',
          title: '啊哈？',
          message: e.message
        })
      })
      .finally(() => loading.value = false)
}

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

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

const teacherAddDialogState = ref(false)

function openOrCloseTeacherAddDialog() {
  teacherAddDialogState.value = !teacherAddDialogState.value
}

const dialogTeacherInfoRef = ref({
  id: undefined,
  teacherName: undefined,
  username: undefined,
  initialPassword: undefined
})

const teacherEditDialogState = ref(false)

function openOrCloseTeacherEditDialog(id) {
  if (teacherEditDialogState.value === false) {
    dialogTeacherInfoRef.value.id = id
    teacherManager.getInfo(id)
        .then(response => {
          dialogTeacherInfoRef.value.teacherName = response.teacherName
          dialogTeacherInfoRef.value.username = response.username
        })
        .catch(e =>
            quasar.dialog({
              transitionShow: 'fade',
              transitionHide: 'fade',
              title: '啊哈？',
              message: e.message
            })
        )
  }

  teacherEditDialogState.value = !teacherEditDialogState.value
}

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

  teacherManager.add(teacher.teacherName, teacher.username, teacher.initialPassword)
      .then(() => {
        dialog.hide()
        forceRefreshTeachers()
      })
      .catch(e => {
        dialog.update({
          title: '啊哈？',
          message: e.message,
          progress: false,
          ok: true
        })
      })
}

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

  teacherManager.update(id, teacher.teacherName, teacher.username, teacher.initialPassword)
      .then(() => {
        dialog.hide()
        forceRefreshTeachers()
      })
      .catch(e => {
        dialog.update({
          title: '啊哈？',
          message: e.message,
          progress: false,
          ok: true
        })
      })
}

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

  teacherManager.deleteTeacher(id)
      .then(() => {
        dialog.hide()
        forceRefreshTeachers()
      })
      .catch(e => {
        dialog.update({
          title: '啊哈？',
          message: e.message,
          progress: false,
          ok: true
        })
      })
}

function deleteTeacherAction(id, name) {
  const dialog = quasar.dialog({
    transitionShow: 'fade',
    transitionHide: 'fade',
    title: '确认？',
    message: `真的要删除『${name}』？`,
    cancel: true,
  })
      .onCancel(() => dialog.hide())
      .onOk(() => doDeleteTeacher(id))
}
</script>

<template>
  <div class="flex flex-col gap-4 px-6 pt-1 pb-6">
    <div>
      <h1 class="text-3xl mb-1">管理教师</h1>
      <p>在这里可以添加/删除全体教师信息</p>
    </div>

    <div class="flex flex-col gap-1 max-w-full">
      <q-table :pagination="teacherListPagination" :filter="filter" :loading="loading"
               :columns="teacherListColumns" :rows="teacherListData" @request="refreshTeachers"
               class="table-admin max-w-full">
        <template v-slot:top>
          <q-btn class="q-ml-sm" color="primary" icon="add" @click="openOrCloseTeacherAddDialog" 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">{{ props.row.name }}</span>
            </q-td>
            <q-td key="id" :props="props">
              <span class="break-all whitespace-normal">{{ props.row.id }}</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="openOrCloseTeacherEditDialog(props.row.id)" outline label="查看/修改"
                       icon="edit"></q-btn>
                <q-btn @click="deleteTeacherAction(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"
    />

    <AdminTeacherAddPane :open="teacherAddDialogState" @on-close="openOrCloseTeacherAddDialog"
                         @on-ok="addTeacherAction"/>
    <AdminTeacherEditPane :data="dialogTeacherInfoRef" :open="teacherEditDialogState"
                          @on-close="openOrCloseTeacherEditDialog" @on-ok="updateTeacherAction"/>
  </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>
