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

import { computed, onMounted, ref } from 'vue'

import { Refresh } from '@element-plus/icons-vue'

import { get } from '#/api/http'
import { BasicService } from '#/api/service/basic'
import MjTable, {
  mj_form_input,
  mj_form_select,
  mj_form_switch,
} from '#/components/mj/mj-table'
import hud from '#/utils/hud'

class TextbookService extends BasicService {
  async sync(): Promise<any> {
    return await get<any>('/xkw/textbook/sync')
  }

  protected findPageUrl(): string {
    return '/xkw/textbook/list'
  }

  protected removeUrl(): string {
    return '/xkw/textbook/batch/delete'
  }

  protected saveOrUpdateUrl(): string {
    return '/xkw/textbook/saveOrUpdate'
  }
}

const textbookService = new TextbookService()

const gridRef = ref()

const gradeOptions = ref<any[]>([])
const gradeMap = ref<Record<string, string>>({})
const versionOptions = ref<any[]>([])
const versionMap = ref<Record<string, string>>({})
const courseOptions = ref<any[]>([])
const courseMap = ref<Record<string, string>>({})
const termOptions = ref<any[]>([])
const termMap = ref<Record<string, string>>({})

const volumeOptions = [
  { value: '上册', label: '上册' },
  { value: '下册', label: '下册' },
  { value: '全册', label: '全册' },
]

onMounted(async () => {
  const [gradeRes, versionRes, courseRes, termRes] = await Promise.all([
    get<any>('/xkw/grade/list', { current: 1, size: 999 }),
    get<any>('/xkw/textbookVersion/list', { current: 1, size: 999 }),
    get<any>('/xkw/subject/list', { current: 1, size: 999 }),
    get<any>('/xkw/term/list', { current: 1, size: 999 }),
  ])

  if (gradeRes?.rows) {
    const map: Record<string, string> = {}
    gradeOptions.value = gradeRes.rows.map((item: any) => {
      map[item.id] = item.name
      return { value: item.id, label: item.name }
    })
    gradeMap.value = map
  }

  if (versionRes?.rows) {
    const map: Record<string, string> = {}
    versionOptions.value = versionRes.rows.map((item: any) => {
      map[item.id] = item.name
      return { value: item.id, label: item.name }
    })
    versionMap.value = map
  }

  if (courseRes?.rows) {
    const map: Record<string, string> = {}
    courseOptions.value = courseRes.rows.map((item: any) => {
      map[item.id] = item.name
      return { value: item.id, label: item.name }
    })
    courseMap.value = map
  }

  if (termRes?.rows) {
    const map: Record<string, string> = {}
    termOptions.value = termRes.rows.map((item: any) => {
      map[item.id] = item.name
      return { value: item.id, label: item.name }
    })
    termMap.value = map
  }
})

function syncData() {
  hud.confirmLoad('确定要同步教材数据吗？', {
    option: '同步',
    hideSuccess: false,
    task: async () => {
      await textbookService.sync()
      gridRef.value?.reload()
    },
  })
}

const searchForm: MjFormProps = {
  items: [
    {
      field: 'keyword',
      title: '关键字',
      itemRender: {
        name: mj_form_input,
        props: { clearable: true, placeholder: '请输入关键字' },
      },
    },
  ],
}

const editForm: MjEditFormProps = {
  modal: { width: 700 },
  form: {
    titleWidth: 100,
    data: {
      name: '',
      gradeId: '',
      ordinal: '',
      textbookId: '',
      term: '',
      versionId: '',
      volume: '',
      courseId: '',
      status: 0,
    },
    items: [
      {
        field: 'name',
        title: '教材名称',
        required: true,
        span: 12,
        itemRender: { name: mj_form_input },
      },
      {
        field: 'courseId',
        title: '学科',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: computed(() => courseOptions.value) as any,
          props: { clearable: true },
        },
      },
      {
        field: 'gradeId',
        title: '年级',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: computed(() => gradeOptions.value) as any,
          props: { clearable: true },
        },
      },
      {
        field: 'versionId',
        title: '教材版本',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: computed(() => versionOptions.value) as any,
          props: { clearable: true },
        },
      },
      {
        field: 'term',
        title: '学期',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: computed(() => termOptions.value) as any,
          props: { clearable: true },
        },
      },
      {
        field: 'volume',
        title: '册别',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: volumeOptions,
          props: { clearable: true },
        },
      },
      {
        field: 'textbookId',
        title: '教材ID',
        span: 12,
        itemRender: { name: mj_form_input },
      },
      {
        field: 'ordinal',
        title: '排序',
        span: 12,
        itemRender: {
          name: mj_form_input,
          props: { type: 'number' },
        },
      },
      {
        field: 'status',
        title: '状态',
        span: 12,
        itemRender: {
          name: mj_form_switch,
          props: {
            openValue: 0,
            closeValue: 1,
            openLabel: '启用',
            closeLabel: '禁用',
          },
        },
      },
    ],
  },
  addFields: [
    'name',
    'gradeId',
    'ordinal',
    'textbookId',
    'term',
    'versionId',
    'volume',
    'courseId',
    'status',
  ],
  updateFields: [
    'id',
    'name',
    'gradeId',
    'ordinal',
    'textbookId',
    'term',
    'versionId',
    'volume',
    'courseId',
    'status',
  ],
}

const grid: MjGridProps = {
  columns: [
    { type: 'seq' },
    { field: 'name', title: '教材名称', minWidth: 160 },
    {
      field: 'courseId',
      title: '学科',
      width: 120,
      slots: { default: 'courseId_default' },
    },
    {
      field: 'gradeId',
      title: '年级',
      width: 120,
      slots: { default: 'gradeId_default' },
    },
    {
      field: 'versionId',
      title: '教材版本',
      width: 140,
      slots: { default: 'versionId_default' },
    },
    {
      field: 'term',
      title: '学期',
      width: 120,
      slots: { default: 'term_default' },
    },
    { field: 'volume', title: '册别', width: 100 },
    { field: 'ordinal', title: '排序', width: 80 },
    {
      field: 'status',
      title: '状态',
      width: 100,
      slots: { default: 'status_default' },
    },
  ],
}
</script>

<template>
  <div class="textbook-mgr g-container">
    <MjTable
      ref="gridRef"
      :grid="grid"
      :service="textbookService"
      :search-form="searchForm"
      :edit-form="editForm"
    >
      <template #toolbarButtonsExtra>
        <el-button type="warning" :icon="Refresh" @click="syncData">
          同步数据
        </el-button>
      </template>

      <template #courseId_default="{ row }">
        {{ courseMap[row.courseId] || row.courseId }}
      </template>

      <template #gradeId_default="{ row }">
        {{ gradeMap[row.gradeId] || row.gradeId }}
      </template>

      <template #versionId_default="{ row }">
        {{ versionMap[row.versionId] || row.versionId }}
      </template>

      <template #term_default="{ row }">
        {{ termMap[row.term] || row.term }}
      </template>

      <template #status_default="{ row }">
        <el-tag :type="row.status === 0 ? 'success' : 'danger'">
          {{ row.status === 0 ? '启用' : '禁用' }}
        </el-tag>
      </template>
    </MjTable>
  </div>
</template>

<style scoped>
.textbook-mgr {
  height: 100% !important;
}
</style>
