<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 CourseService extends BasicService {
  async sync(): Promise<any> {
    return await get<any>('/xkw/course/sync')
  }

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

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

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

const courseService = new CourseService()

const gridRef = ref()

const stageOptions = ref<any[]>([])
const stageMap = ref<Record<string, string>>({})
const subjectOptions = ref<any[]>([])
const subjectMap = ref<Record<string, string>>({})

onMounted(async () => {
  const [stageRes, subjectRes] = await Promise.all([
    get<any>('/xkw/stage/list', { current: 1, size: 999 }),
    get<any>('/xkw/subject/list', { current: 1, size: 999 }),
  ])

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

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

function syncData() {
  hud.confirmLoad('确定要同步课程数据吗？', {
    option: '同步',
    hideSuccess: false,
    task: async () => {
      await courseService.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: 600 },
  form: {
    titleWidth: 100,
    data: {
      name: '',
      shortName: '',
      stageId: '',
      subjectId: '',
      status: 0,
    },
    items: [
      {
        field: 'name',
        title: '课程名称',
        required: true,
        span: 12,
        itemRender: { name: mj_form_input },
      },
      {
        field: 'shortName',
        title: '简称',
        span: 12,
        itemRender: { name: mj_form_input },
      },
      {
        field: 'stageId',
        title: '学段',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: computed(() => stageOptions.value) as any,
          props: { clearable: true },
        },
      },
      {
        field: 'subjectId',
        title: '学科',
        span: 12,
        itemRender: {
          name: mj_form_select,
          options: computed(() => subjectOptions.value) as any,
          props: { clearable: true },
        },
      },
      {
        field: 'status',
        title: '状态',
        span: 12,
        itemRender: {
          name: mj_form_switch,
          props: {
            openValue: 0,
            closeValue: 1,
            openLabel: '正常',
            closeLabel: '禁用',
          },
        },
      },
    ],
  },
  addFields: ['name', 'shortName', 'stageId', 'subjectId', 'status'],
  updateFields: ['id', 'name', 'shortName', 'stageId', 'subjectId', 'status'],
}

const grid: MjGridProps = {
  columns: [
    { type: 'seq' },
    { field: 'name', title: '课程名称', minWidth: 140 },
    { field: 'shortName', title: '简称', width: 120 },
    {
      field: 'stageId',
      title: '学段',
      width: 120,
      slots: { default: 'stageId_default' },
    },
    {
      field: 'subjectId',
      title: '学科',
      width: 120,
      slots: { default: 'subjectId_default' },
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      slots: { default: 'status_default' },
    },
    {
      title: '操作',
      width: 200,
      slots: { default: 'operation' },
      fixed: 'right',
    },
  ],
}
</script>

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

      <template #stageId_default="{ row }">
        {{ stageMap[row.stageId] || row.stageId }}
      </template>

      <template #subjectId_default="{ row }">
        {{ subjectMap[row.subjectId] || row.subjectId }}
      </template>

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

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