<script setup>
import {ref} from "vue";
import teacherManager from "app/src/api/teacher/teacher";
import {useQuasar} from "quasar";
import courseTeacherApi from "app/src/api/course/course_teacher";
import {errors} from "workbox-build/build/lib/errors";

const open = defineModel("open")

const courseIdRef = ref(0)

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

// eslint-disable-next-line vue/no-setup-props-destructure
const selectedTeacher = ref([])

const quasar = useQuasar()

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

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

const teacherListData = ref([])

const filter = ref('')

const loading = ref(true)

async function init(courseId) {
  loading.value = true
  courseIdRef.value = courseId

  try {
    if (!teacherListData.value || teacherListData.value.length === 0) {
      const response = await teacherManager.list(1, 10);
      teacherListPagination.value.page = response.current;
      teacherListPagination.value.rowsNumber = response.total;
      teacherListData.value = response.result;
    }

    selectedTeacher.value = await courseTeacherApi.list(Number(courseId))

  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
  }

  loading.value = false
}

defineExpose({
  init
})

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

  loading.value = true

  try {
    const response = await teacherManager.list(page, rowsPerPage === 0 ? 999 : rowsPerPage)

    teacherListPagination.value.page = response.current
    teacherListPagination.value.rowsNumber = response.total
    teacherListPagination.value.rowsPerPage = response.pageSize

    teacherListData.value.splice(0, teacherListData.value.length, ...response.result)
  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
  }

  loading.value = false
}

function getSelectedString() {
  let text = '已选择：'
  selectedTeacher.value.forEach((e, i) => {
    text += e.name + ((i === selectedTeacher.value.length - 1) ? '' : ', ')
  })

  return text
}

async function updateCourseTeacher() {
  loading.value = true

  try {
    const teacherIdList = []
    selectedTeacher.value.forEach(teacherInfo => {
      teacherIdList.push(teacherInfo.id)
    })

    await courseTeacherApi.update(Number(courseIdRef.value), teacherIdList)

    open.value = false
    func('onOk');

  } catch (e) {
    quasar.dialog({
      transitionShow: 'fade',
      transitionHide: 'fade',
      title: '啊哈？',
      message: e.message
    })
  }

  loading.value = false
}

</script>

<template>
  <q-dialog persistent no-esc-dismiss no-shake transition-show="fade" transition-hide="fade"
            v-model="open">
    <q-card class="teacher-selecting-dialog px-2 flex flex-col justify-between">
      <div>
        <div class="sticky top-0 bg-white z-10">
          <q-card-section>
            <div class="text-h6">选择上课老师</div>
          </q-card-section>
          <q-separator/>
        </div>

        <q-card-section class="scroll">
          <div class="flex flex-col gap-4 text-base">
            <span class="text-base">在这里选择上此课程的老师</span>
            <q-table flat :filter="filter" :loading="loading"
                     :selected-rows-label="getSelectedString"
                     v-model:selected="selectedTeacher"
                     selection="multiple"
                     v-model:pagination="teacherListPagination" @request="refreshTeachers"
                     :columns="teacherListColumns" :rows="teacherListData"
                     class="table-admin w-full max-h-full max-w-full">
            </q-table>

          </div>
        </q-card-section>
      </div>

      <div class="sticky bottom-0 bg-white z-10">
        <q-separator/>
        <q-card-actions align="right">
          <slot name="actions"></slot>
          <q-btn flat v-close-popup>算了</q-btn>
          <q-btn flat @click="updateCourseTeacher">好的</q-btn>
        </q-card-actions>
      </div>

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

<style lang="sass">
.teacher-selecting-dialog
  min-height: 55vh

.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>
