<script setup lang="ts">
import type { MjGridProps } from '#/components/mj/mj-table'
import type { SelectedItems } from '#/components/mj/mj-table/const'

import { BookOutline } from '@vben/icons'
import { useUserStore } from '@vben/stores'

import { schoolBookService } from '#/api/service/question-bank/school-book'
import { staffService } from '#/api/service/subject/staff'
import { useAuthStore } from '#/store/auth'
import hud from '#/utils/hud'

defineOptions({ name: 'SchoolBook' })

defineProps<{
  fixedSchool?: any
  schoolId?: any
  schoolName?: any
}>()

const selectedItems = defineModel<SelectedItems>('selectedItems')

const { userInfo } = storeToRefs(useUserStore())
const authStore = useAuthStore()
const gridRef = ref()
const curStaff = ref({} as any)

async function loadCurStaff() {
  const params: any = { selfInfo: 1 }
  if (userInfo.value.isSpStaff) {
    params.providerId = userInfo.value.providerId
  } else if (userInfo.value.isStaff) {
    params.schoolId = userInfo.value.schoolId
  }
  const res = await staffService.findPage(1, 1, params)
  if (res.rows?.length) {
    curStaff.value = res.rows[0]
  }
}
loadCurStaff()

// 搜索表单
const searchForm = {
  items: [
    {
      slots: { default: 'setTextbookBtn' },
    },
  ],
  data: {},
} as any

// 表格
const grid = {
  columns: [
    {
      title: '年级',
      field: 'gradeName',
    },
    {
      title: '学科',
      field: 'subjectName',
    },
    {
      title: '版本',
      field: 'versionName',
    },
    {
      title: '教材',
      field: 'textbookName',
    },
  ],
} as MjGridProps

// 设置教材
const bookSelectVisible = ref(false)

function showBookSelect() {
  bookSelectVisible.value = true
}

function onBookSelect(books: any) {
  hud.load({
    task: async () => {
      await staffService.saveOrUpdate({
        id: curStaff.value.id,
        textbookIds: books.map((item: any) => item.id),
        config: JSON.stringify({ books }),
      })
      gridRef.value.reload()
      await authStore.updateUserInfo()
    },
    option: '保存',
    hideSuccess: false,
  })
}
</script>

<template>
  <div class="school-book g-container">
    <MjTable
      v-bind="$attrs"
      ref="gridRef"
      hide-toolbar
      hide-remove
      :grid="grid"
      :service="schoolBookService"
      :search-form="searchForm"
      :selected-items="selectedItems"
      @update:selected-items="(val) => (selectedItems = val)"
    >
      <template #setTextbookBtn>
        <el-button type="primary" :icon="BookOutline" @click="showBookSelect">
          设置教材
        </el-button>
      </template>
    </MjTable>
    <textbook-multi-select v-model="bookSelectVisible" @ok="onBookSelect" />
  </div>
</template>

<style lang="scss" scoped>
.school-book {
  height: 100% !important;
}
</style>
