<script lang="ts" setup name="questionBank_questionAdd">
import type { FormInstance } from 'element-plus'

import { useTabbarStore, useUserStore } from '@vben/stores'

import { questionResourceService } from '#/api/service/question-bank/question-resource'
import dayjs from '#/plugins/dayjs'
import { router } from '#/router'
import { type_options } from '../paper-mgr/index.ts'
import { getStageByGrade, provinces, useBasicData } from '#/store/basic-data'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

// https://vueup.github.io/vue-quill/
// https://www.wangeditor.com/
// https://github.com/tinymce/tinymce-vue
// https://ckeditor.com/docs/ckeditor5/latest/getting-started/installation/cloud/vuejs-v3.html

const tabStore = useTabbarStore()
const basicDataStore = useBasicData()
const { getChannelTypeOptions } = basicDataStore
const { channelTypeMap } = storeToRefs(basicDataStore)

const { userInfo } = storeToRefs(useUserStore())
const bookOptions = userInfo.value.personConfig?.books
const bookMap = obj.list2map(bookOptions, 'id')
const book = ref({} as any)

const route = useRoute()

type ResourceFile = {
  channelTypeId: any
  fileUrl: any
  totalNum: any

  uploadFiles: any[]
  uploadId: any
  uploadRef: any
}

// 年份
const year_options = [] as any[]
for (let i = 2025; i >= 2010; i--) {
  year_options.push({
    label: `${i}`,
    value: `${i}`,
  })
}

// 表单数据
const formRef = ref<FormInstance | undefined>()
const formData = reactive({
  province: 0,
  year: '2025',
  sources: [],
  textbookId: undefined,
  resourceFileList: [] as ResourceFile[],
  name: '',
  paperTemplate: 1,
  type: undefined,
})

// 题型
const channelTypeOptions = ref([] as any[])

const { getChapters } = useBasicData()

// 章节
const chapterRef = ref()
const chapterSearchText = ref('')
const chapters = ref([] as any)
watch(
  () => chapterSearchText.value,
  (v) => {
    // eslint-disable-next-line unicorn/no-array-callback-reference
    chapterRef.value.filter(v)
  },
)
function chapterFilter(v: any, chapter: any) {
  if (!v) return true
  return chapter.name.toLowerCase().includes(v.toLowerCase())
}

// 书本变化了
async function bookChange(textbookId: any) {
  chapters.value = await getChapters(textbookId)
  book.value = bookMap[textbookId]
  // 获取题型
  channelTypeOptions.value = await getChannelTypeOptions(
    getStageByGrade(book.value.gradeId),
    book.value.subjectId,
  )
  // 清空文件
  formData.resourceFileList = []
  addFile()
}

// 添加文件项
function addFile() {
  formData.resourceFileList.push({
    channelTypeId: channelTypeOptions.value[0].value,
    fileUrl: '',
    totalNum: '',
    uploadRef: ref(),
    uploadFiles: [],
    uploadId: obj.snowflakeId(),
  })
}

// 删除文件项
function removeFile(index: any) {
  if (formData.resourceFileList.length > 1) {
    formData.resourceFileList.splice(index, 1)
  }
}

function handleChapterCheck(chapter: any, checked: boolean) {
  if (checked) {
    // 取消之前选中的节点
    chapterRef.value.setCheckedKeys([chapter.id])
  }
}

// 根据文件id获取文件url
function getFileUrl(uploadId: any) {
  for (const file of formData.resourceFileList) {
    if (file.uploadId === uploadId) {
      return file.fileUrl
    }
  }
  return undefined
}

// 根据文件id设置文件url
function setFileUrl(uploadId: any, fileUrl: any) {
  for (const file of formData.resourceFileList) {
    if (file.uploadId === uploadId) {
      file.fileUrl = fileUrl
      return
    }
  }
}

// 上传文件
async function uploadFile(options: any) {
  const fileUrl = getFileUrl(options.data.uploadId)
  if (fileUrl) return

  try {
    const res = await questionResourceService.uploadFile({
      ...options.data,
      file: options.file,
    })
    // 设置url
    setFileUrl(res.id, res.url)
    finalSave()
  } catch {
    hud.hide()
    hud.error('文件上传失败')
  }
}

// 最后的保存
async function finalSave() {
  // 看看是否所有都上传完毕
  for (const file of formData.resourceFileList) {
    if (!file.fileUrl) return
  }
  // 全部文件都上传完毕
  data.resourceFileList = formData.resourceFileList.map((item) => ({
    channelTypeId: item.channelTypeId,
    channelTypeBaseId: channelTypeMap.value[item.channelTypeId].baseId,
    totalNum: item.totalNum,
    fileUrl: item.fileUrl,
  }))
  // 开始保存
  try {
    await questionResourceService.save(data)
    hud.hide()
    hud.success('保存成功')
    tabStore.closeTabByKey(route.fullPath, router)
    router.push('/question-bank/question-resource')
  } finally {
    hud.hide()
  }
}

// 提交
let data = {} as any
function submit() {
  // 如果paperTemplate 是模板，删除type
  if (formData.paperTemplate === 0) {
    delete formData.type
  }

  // console.log(formData)
  if (!formData.textbookId) {
    hud.error('请选择教材')
    return
  }
  // 如果是试卷模板，必须选择类型
  if (formData.paperTemplate === 1 && !formData.type) {
    hud.error('请选择类型')
    return
  }

  if (!book.value) {
    hud.error('您未绑定本教材，无法进行操作')
    return
  }

  const chapterIds = chapterRef.value.getCheckedKeys(false, false)
  // if (chapterIds.length === 0) {
  //   hud.error('请选择章节')
  //   return
  // }

  data = {} as any
  // 教材
  data.textbookId = formData.textbookId
  // 阶段
  data.stagePid = getStageByGrade(book.value.gradeId)
  // 年级
  data.gradeId = book.value.gradeId
  // 学科
  data.subjectId = book.value.subjectId
  // 名称
  data.name =
    formData.name || `${dayjs().format('YYYY-MM-DD_HH:mm')}_${book.value.title}`
  // 省份
  data.province = formData.province
  // 年份
  data.year = formData.year
  // 来源
  data.sources = toRaw(formData.sources).join(',')
  // 章节
  data.chapterId = chapterIds[0] || ''
  // 类型
  data.type = formData.type ? Number(formData.type) : undefined
  // 试卷模板
  data.paperTemplate = formData.paperTemplate
  // 配置
  data.configJson = JSON.stringify({
    textbookTitle: book.value.title,
  })

  // 文件处理
  for (const file of formData.resourceFileList) {
    const num = Number(file.totalNum)
    if (!num || num < 1) {
      hud.error('请输入题目数量')
      return
    }
    if (file.uploadFiles.length === 0) {
      hud.error('请选择文件')
      return
    }
  }
  // 开始上传文件
  for (const file of formData.resourceFileList) {
    file.uploadRef.submit()
  }
  hud.loading('保存中...')
}
</script>

<template>
  <div class="page g-container">
    <div class="form-box">
      <el-form
        ref="formRef"
        label-width="100px"
        :model="formData"
        class="question-form"
      >
        <!-- 基本信息 -->
        <el-card shadow="never" class="form-section">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="地区" prop="province">
                <el-select v-model="formData.province" placeholder="请选择地区">
                  <el-option
                    v-for="item in provinces"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="年份" prop="year">
                <el-select v-model="formData.year" placeholder="请选择年份">
                  <el-option
                    v-for="item in year_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来源" prop="sources">
                <el-input-tag
                  v-model="formData.sources"
                  placeholder="多个来源之间用回车键隔开"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="教材" prop="textbookId">
                <el-select
                  v-model="formData.textbookId"
                  placeholder="请选择教材"
                  @change="bookChange"
                >
                  <el-option
                    v-for="item in bookOptions"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
            <!--类型-->

            <el-col :span="6">
              <el-form-item label="试卷模板" prop="paperTemplate">
                <el-select
                  v-model="formData.paperTemplate"
                  placeholder="是否试卷模板"
                >
                  <el-option label="否" :value="0" />
                  <el-option label="是" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="formData.paperTemplate === 1">
              <el-form-item label="类型" prop="type">
                <el-select v-model="formData.type" placeholder="请选择类型">
                  <el-option
                    v-for="item in type_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="book.id" :gutter="20">
            <el-col :span="12">
              <el-form-item label="章节" prop="chapterIds">
                <el-input v-model="chapterSearchText" placeholder="搜索章节" />
                <el-tree
                  class="tree"
                  :data="chapters"
                  ref="chapterRef"
                  show-checkbox
                  node-key="id"
                  check-strictly
                  @check="handleChapterCheck"
                  :props="{
                    children: 'children',
                    label: 'name',
                  }"
                  :filter-node-method="chapterFilter"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="channelTypeOptions.length > 0" :gutter="20">
            <el-col :span="24">
              <el-form-item label="文件">
                <div class="options-container file-options-container">
                  <div
                    v-for="(option, index) in formData.resourceFileList"
                    :key="index"
                    class="option-item file-option-item"
                  >
                    <el-button
                      v-if="formData.resourceFileList.length > 1"
                      type="danger"
                      size="small"
                      @click="removeFile(index)"
                    >
                      删除
                    </el-button>
                    <el-select
                      class="option-channel-type"
                      filterable
                      v-model="option.channelTypeId"
                      placeholder="请选择题型"
                    >
                      <el-option
                        v-for="item in channelTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <el-input
                      class="option-total-num"
                      v-model="option.totalNum"
                      placeholder="请输入题目总数量"
                    />
                    <el-upload
                      :ref="(el) => (option.uploadRef = el)"
                      v-model:file-list="option.uploadFiles"
                      class="option-upload"
                      :data="{
                        id: option.uploadId,
                      }"
                      :limit="1"
                      :http-request="uploadFile as any"
                      name="file"
                      :auto-upload="false"
                    >
                      <el-button type="success"> 请选择文件 </el-button>
                    </el-upload>
                    <!-- <OpenEmojiRight v-if="option.fileUrl" width="36" /> -->
                  </div>
                  <el-button type="primary" size="small" @click="addFile">
                    添加文件项
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="primary" size="large" @click="submit()">
        提交
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 88px) !important;

  .file-option-item {
    display: flex;
    gap: 15px;
    align-items: center;

    .option-channel-type {
      width: 150px;
    }

    .option-total-num {
      width: 200px;
    }

    .option-upload {
      display: flex;
      align-items: center;
    }
  }

  .form-box {
    overflow: auto;

    .tree {
      width: 100%;
      max-height: 500px;
      margin-top: 10px;
      overflow: auto;
    }

    .question-form {
      .form-section {
        margin-bottom: 24px;

        .section-title {
          font-weight: 600;
          color: #303133;
        }
      }

      .file-options-container {
        flex: 1;

        :deep(.option-upload) {
          flex: 1;

          .el-upload-list--text {
            flex: 1;
          }
        }
      }

      .options-container {
        .option-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          .option-label {
            min-width: 24px;
            margin-right: 8px;
            font-weight: 600;
          }

          .el-input {
            margin-right: 8px;
          }
        }
      }

      .fill-answers {
        .fill-answer-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;

          .fill-label {
            min-width: 60px;
            margin-right: 8px;
            font-weight: 500;
          }

          .el-input {
            flex: 1;
            margin-right: 8px;
          }
        }
      }
    }
  }

  .form-actions {
    padding: 16px 0 0;
    text-align: center;
    border-top: 1px solid #e4e7ed;

    .el-button {
      margin: 0 8px;
    }
  }

  .question-preview {
    .options {
      margin-top: 16px;

      .option {
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;
      }
    }
  }

  .import-content {
    .import-actions {
      margin-top: 16px;
      text-align: center;

      .el-button {
        margin: 0 8px;
      }
    }
  }
}
</style>
