<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="题型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择题型" clearable>
          <el-option v-for="item in questionTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createUserName">
        <el-input
          v-model="queryParams.createUserName"
          placeholder="请输入创建人"
          clearable
          v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTimeDate">
        <el-date-picker
          v-model="queryParams.createTimeDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="5">
        <el-button type="primary" size="mini" @click="handleAddQuestion">新建试题</el-button>
        <el-button type="primary" size="mini" @click="handleImport">导入题目</el-button>
      </el-col>

      <el-col :span="2">
        <div>单选题：{{ questionsNums.num || 0 }}道</div>
      </el-col>
      <el-col :span="2">
        <div>多选题：{{ questionsNums.num2 || 0 }}道</div>
      </el-col>
      <el-col :span="2">
        <div>判断题：{{ questionsNums.num3 || 0 }}道</div>
      </el-col>
      <el-col :span="2">
        <div>简答题：{{ questionsNums.num4 || 0 }}道</div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table :data="tableData" fit highlight-current-row style="width: 100%" @selection-change="selectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <!-- 试题库名称 -->
      <el-table-column prop="content" label="题目" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span style="color: #409eff; cursor: pointer">
            {{ scope.row.content }}
          </span>
        </template>
      </el-table-column>
      <!-- 题目数量 -->
      <el-table-column prop="questionType" label="题型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.questionType === '1'">单选题</span>
          <span v-else-if="scope.row.questionType === '2'">多选题</span>
          <span v-else-if="scope.row.questionType === '3'">判断题</span>
          <span v-else-if="scope.row.questionType === '4'">简答题</span>
        </template>
      </el-table-column>
      <!-- 标签 -->
      <el-table-column prop="questionLabel" label="标签" align="center" />
      <!-- 创建人 -->
      <el-table-column prop="createUserName" label="创建人" align="center" />
      <!-- 创建时间 -->
      <el-table-column prop="createTimeDate" label="创建时间" align="center" />
      <!-- 操作 -->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleDelete(scope.row)"
            icon="el-icon-delete"
            style="color: #e47470"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新建试题 -->
    <NewTestItem
      ref="NewTestItem"
      :dialogTitle="dialogTitle"
      :questionsLibraryId="questionsLibraryId"
      :questionId="questionId"
      @getList="getList"
    />

    <el-dialog :title="`题目导入`" :visible.sync="questionOpen" width="60%" style="height: 1000px">
      <div style="padding: 15px; width: 100%; height: 750px">
        <el-steps :active="active" :finish-status="status" align-center>
          <el-step title="选择文件"></el-step>
          <el-step title="数据预览"></el-step>
          <el-step title="异常数据"></el-step>
          <el-step title="导入完成"></el-step>
        </el-steps>
        <div class="step1" style="margin-bottom: 30px">
          <div
            style="
              display: flex;
              flex-direction: column;
              padding: 20px;
              margin-left: 7%;
              margin-top: 20px;
              border: 1px solid #ababab;
              border-radius: 5px;
              margin-right: 7%;
            "
            v-if="active === 1"
          >
            <span style="font-size: 18px; font-weight: bold">模板下载</span>
            <span style="font-size: 16px; margin-top: 10px">
              请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除
            </span>
            <el-button type="text" style="float: left; margin-top: 10px; width: 60px" @click="downloadTemplate">
              下载模板
            </el-button>
            <!--                      <span style="font-size: 16px;color: #8a8a8a;margin-top: 10px;cursor: pointer" @click="downloadTemplate"-->
            <!--                      >下载模板</span>-->
          </div>
          <div
            style="
              display: flex;
              flex-direction: column;
              padding: 20px;
              margin-left: 7%;
              margin-top: 20px;
              border: 1px solid #ababab;
              border-radius: 5px;
              margin-right: 7%;
            "
            v-if="active === 1"
          >
            <span style="font-size: 18px; font-weight: bold">上传文件</span>
            <span style="font-size: 16px; margin-top: 10px">
              文件后缀名必须为xls或xlsx(即Excel格式),文件大小不得大于5MB,最多支持1000行数据
            </span>
            <input type="file" id="excel-file" style="display: none" />
            <el-form ref="form" :model="formPerson" style="margin-top: 10px" :rules="rulesPerson">
              <el-form-item prop="fileList">
                <el-upload
                  multiple
                  drag
                  accept=" .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf "
                  :show-file-list="true"
                  class="upload-demo"
                  action="#"
                  :limit="1"
                  :file-list="formPerson.fileList"
                  :on-change="filePersonChange"
                  :on-remove="handlePersonRemove"
                  :before-upload="beforePersonUpload"
                  :auto-upload="false"
                  ref="upload"
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                  <div class="el-upload__text">只能上传 xls/xlsx 文件，且不超过10MB</div>
                </el-upload>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div class="step2" style="margin-bottom: 30px">
          <div
            v-if="active === 2"
            style="
              height: 620px;
              overflow-x: auto;
              overflow-y: auto;
              display: flex;
              flex-direction: column;
              padding: 20px;
              margin-left: 7%;
              margin-top: 20px;
              margin-right: 7%;
            "
          >
            <div
              v-if="errorLine.length > 0 || errorCorrectAnswers.length > 0"
              style="background: #ebebeb; padding: 10px"
            >
              <div style="font-size: 16px; font-weight: 600; margin-bottom: 10px; color: red">异常数据</div>
              <div v-if="errorLine.length > 0" style="width: 100%">
                行数：{{ errorLine.join(',') }}
                有空数据或者错误数据
              </div>
              <div v-if="errorCorrectAnswers.length > 0" style="width: 100%">
                表格中正确答案选项不存在，请仔细核对！
              </div>
              <div
                v-if="errorCorrectAnswers.length > 0"
                style="margin-top: 10px; font-weight: 400; font-size: 16px; width: 100%"
              >
                错误行数:{{ errorCorrectAnswers }}
              </div>
            </div>
            <!-- 这里展示excel数据的表格 -->
            <el-table :data="excelData" style="width: 100%; height: 700px; overflow-x: auto; overflow-y: auto">
              <!-- 表格列定义 -->
              <el-table-column prop="questionId" width="55" show-overflow-tooltip align="center" />
              <el-table-column prop="content" width="240" show-overflow-tooltip align="center" />
              <el-table-column prop="questionAnswerVoList" show-overflow-tooltip width="240" align="center" />
              <el-table-column prop="correctAnswer" show-overflow-tooltip width="120" align="center" />
              <el-table-column prop="analysis" show-overflow-tooltip width="120" align="center" />
              <el-table-column prop="questionType" show-overflow-tooltip width="120" align="center" />
            </el-table>
          </div>
        </div>

        <div class="step3" style="margin-bottom: 30px">
          <div v-if="active === 3">
            <div
              style="
                display: flex;
                flex-direction: column;
                padding: 20px;
                margin-left: 7%;
                margin-top: 20px;
                margin-right: 7%;
                margin-bottom: 30px;
              "
            >
              <span style="font-size: 16px; margin-top: 10px">
                以下是已经在库的手机号（人员已经录入），请先根据手机号删除相应行内容，然后再进行导入
              </span>
              <span style="margin-top: 10px; width: 100%">{{ errorCode.substring(1, errorCode.length - 1) }}</span>
            </div>
          </div>
        </div>

        <div class="step4" style="margin-bottom: 30px">
          <div v-if="active === 4">
            <div
              style="
                display: flex;
                flex-direction: column;
                padding: 20px;
                margin-left: 7%;
                margin-top: 100px;
                margin-right: 7%;
                align-items: center;
                justify-content: center;
              "
            >
              <img src="@/assets/file/import_success_blue.png" alt="导入成功" />
              <span style="margin-top: 20px; font-size: 18px">
                数据导入成功，请在列表中查看，提交审核之前请先上传相关人员的文件！
              </span>
            </div>
          </div>
        </div>
        <div v-if="type === '导入'">
          已导入：{{ importedCount }} / 1000
          <el-progress :percentage="importProgress"></el-progress>
        </div>
        <div class="el-footer" style="position: absolute; top: 90%; left: 74%; margin-top: 10px">
          <el-button type="primary" style="margin-top: 12px" @click="before" v-if="active === 2 || active === 3">
            上一步
          </el-button>
          <el-button type="primary" style="margin-top: 12px" @click="next" v-if="active === 0 || active === 1">
            下一步
          </el-button>
          <el-button
            type="primary"
            style="margin-top: 12px"
            @click="importExcel"
            v-if="active === 2 && errorLine.length === 0 && errorCorrectAnswers.length === 0"
          >
            导入
          </el-button>
          <el-button type="primary" plain style="margin-top: 12px; margin-bottom: 10px" @click="personClose">
            关闭
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQuestionsExamList, delTopic, getQuestionsExamNums } from '@/api/educationalTraining/resourceAdministration'
import NewTestItem from '@/views/educationalTraining/learningManagement/learningTasks/components/NewTestItem'
import { downloadFile, getTemplateLink } from '@/api/tool/select'
import { importPersonData, importQuestionData } from '@/api/importData/importData'
import XLSX from '@/utils/xlsx.full.min'
import { StrUtil } from '@/utils/StrUtil'
import debounce from 'lodash/debounce'

export default {
  components: { NewTestItem },
  name: 'questionDetails',
  data() {
    return {
      isLoading: false,
      questionsLibraryId: '',
      questionId: '',
      // 是否显示搜索
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        questionType: '', // 题型
        // 创建人
        createUserName: '',
        // 创建时间
        createTimeDate: '',
        startDate: '',
        endDate: '',
      },
      // 题型 1单选题;2多选题;3判断题;4简答题
      questionTypeOptions: [
        { label: '单选题', value: '1' },
        { label: '多选题', value: '2' },
        { label: '判断题', value: '3' },
        { label: '简答题', value: '4' },
      ],
      // 列表数据
      tableData: [],
      loading: false,
      // 弹框标题
      dialogTitle: '新建题库',
      // 试题数量
      questionsNums: {},
      questionOpen: false,
      active: 1,
      importedCount: 0,
      importProgress: 0,
      status: 'success',
      excelData: [],
      uploadData: [],
      errorLine: [],
      errorCorrectAnswers: [],
      errorCode: '',
      type: '',
      formPerson: {
        fileList: [],
        proId: undefined,
        uploadType: undefined,
      },
      rulesPerson: {
        fileList: [{ required: true, message: '请先选择需要导入的excel文件', trigger: 'blur' }],
      },
      questionType: {
        单选题: '1',
        多选题: '2',
        判断题: '3',
        简答题: '4',
      },
      templateLink: '',
    }
  },
  created() {
    // 从路由中获取参数 questionsLibraryId
    this.questionsLibraryId = this.$route.query.questionsLibraryId
    this.getList()
    // this.getQuestionsExamNums()
  },
  methods: {
    // 搜索
    handleSearch() {
      console.log('搜索', this.queryParams)
      if (this.queryParams.createTimeDate) {
        this.queryParams.startDate = this.queryParams.createTimeDate[0]
        this.queryParams.endDate = this.queryParams.createTimeDate[1]
      }
      this.getList()
    },
    // 重置
    handleReset() {
      console.log('重置')
      // 重置查询参数 resetFields
      this.$refs.queryForm.resetFields()
      this.queryParams.startDate = ''
      this.queryParams.endDate = ''
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('获取列表')
      const res = await getQuestionsExamList({ ...this.queryParams, questionsLibraryId: this.questionsLibraryId })
      console.log('🚀 ~ getList ~ data-列表:', res)
      this.tableData = res.rows
      this.total = res.total
      this.getQuestionsExamNums()
    },
    // 新建试题
    handleAddQuestion() {
      console.log('新建试题')
      this.questionId = ''
      this.dialogTitle = '新建试题'
      this.$refs.NewTestItem.openDialog({ isEdit: false })
    },
    handleEdit(item) {
      console.log('编辑', item)
      this.dialogTitle = '编辑试题'
      this.$refs.NewTestItem.openDialog({ ...item, isEdit: true })
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      // 弹框提示
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 删除
          console.log('删除', row)
          const params = {
            questionsLibraryId: row.questionsLibraryId,
            questionId: row.questionId,
          }
          delTopic(params).then(res => {
            console.log('🚀 ~ delTopic ~ res:', res)
            // 刷新列表
            this.getList()
          })
        })
        .catch(() => {
          // 取消
        })
    },
    // 多选框选中数据
    selectionChange(sel) {
      console.log('多选框选中数据', sel)
    },
    // 获取题目数量
    async getQuestionsExamNums() {
      const res = await getQuestionsExamNums({ questionsLibraryId: this.questionsLibraryId })
      this.questionsNums = res.data
      console.log('🚀 ~ getQuestionsExamNums ~ res:', res)
    },
    downloadTemplate() {
      console.log('下载模板', this.templateLink)
      downloadFile(this.templateLink, '题目文件.xlsx')
    },

    importExcel: debounce(function () {
      this.loading = true
      let data = []
      for (let i = 1; i < this.uploadData.length; i++) {
        data.push(this.uploadData[i])
      }
      const param = {
        questionsLibraryId: this.questionsLibraryId,
        importArgList: data,
      }
      console.log('param', param)
      importQuestionData(param).then(response => {
        console.log('response', response)
        if (response.code === 200) {
          if (response.msg === '操作成功') {
            this.$modal.msgSuccess('导入成功')
            this.active = 4
            this.formPerson.fileList = []
            this.excelData = []
            this.getSubPersonList()
            this.loading = false
          } else {
            this.errorCode = response.msg
            this.active = 3
            this.status = 'error'
          }
        }
      })
    }, 500),

    beforePersonUpload(file) {
      const isExcel = /\.(xlsx|xls)$/.test(file.name)
      if (!isExcel) {
        this.$message.error('只能上传.xlsx、.xls 文件!')
        this.formPerson.fileList = []
        return false
      }
      return true
    },
    /** 获取文件数据 */
    filePersonChange(file, fileList) {
      console.log(fileList)
      this.formPerson.fileList = []
      const isExcel = /\.(xlsx|xls)$/.test(file.name)
      if (!isExcel) {
        this.$message.error('只能上传.xlsx、.xls 文件!')
        this.formPerson.fileList = []
        return false
      }
      // 检查文件大小
      if (file.size > 1024 * 1024 * 10) {
        // 10MB 限制
        this.$message.warning('文件大小不能超过10MB')
        fileList = fileList.filter(item => item.uid !== file.uid)
      } else {
        const reader = new FileReader()

        reader.onload = e => {
          this.loading = true
          if (e.target && e.target.result) {
            try {
              const data = new Uint8Array(e.target.result)
              console.log('读取成功:', data)
              const workbook = XLSX.read(data, { type: 'array' })
              const firstSheetName = workbook.SheetNames[0]
              const worksheet = workbook.Sheets[firstSheetName]
              let jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
              const maxColumns = jsonData.reduce((max, row) => Math.max(max, row.length), 0)
              if (maxColumns !== 6) {
                this.active = 1
                this.formPerson.fileList = []
                this.$message.warning('请选择正确的excel进行数据导入  ')
              }
              // 计算最大行数
              const maxRows = jsonData.length
              if (maxRows === 1) {
                this.active = 1
                this.formPerson.fileList = []
                this.$message.warning('表格数据为空，请先填写相关数据，再进行导入')
              }
              this.errorLine = []
              this.errorCorrectAnswers = []
              let mappedAnswers
              this.excelData = []
              this.uploadData = []
              for (let i = 0; i < jsonData.length; i++) {
                if (
                  StrUtil.isBlank(jsonData[i][1]) ||
                  StrUtil.isBlank(jsonData[i][2]) ||
                  StrUtil.isBlank(jsonData[i][3]) ||
                  StrUtil.isBlank(jsonData[i][4]) ||
                  StrUtil.isBlank(jsonData[i][5])
                ) {
                  this.errorLine.push(jsonData[i][0])
                } else {
                  const answers = jsonData[i][3].split('|@|')
                  const questionOptionArr = jsonData[i][2].split('|@|')
                  mappedAnswers = answers.map(answer => {
                    return answer
                      .split('.')
                      .map(letter => letter.charCodeAt(0) - 65)
                      .join('.')
                  })
                  for (let j = 0; j < mappedAnswers.length; j++) {
                    if (mappedAnswers[j] >= questionOptionArr.length) {
                      if (i !== 0) {
                        this.errorCorrectAnswers.push(jsonData[i][0])
                      }
                    }
                  }
                }
                const rowData = {
                  questionId: jsonData[i][0],
                  content: jsonData[i][1],
                  questionAnswerVoList: jsonData[i][2],
                  correctAnswer: jsonData[i][3],
                  analysis: jsonData[i][4],
                  questionType: jsonData[i][5],
                }
                this.excelData.push(rowData)
                const rowDatas = {
                  questionId: jsonData[i][0],
                  content: jsonData[i][1],
                  questionAnswerVoList: [],
                  correctAnswer: mappedAnswers.join(','),
                  analysis: jsonData[i][4],
                  questionType: this.questionType[jsonData[i][5]],
                }
                let arr = jsonData[i][2].split('|@|')
                console.log('arr', arr)
                for (let j = 0; j < arr.length; j++) {
                  rowDatas.questionAnswerVoList.push({
                    options: arr[j],
                    sort: j,
                  })
                }
                this.uploadData.push(rowDatas)
              }
              console.log('excelData：', this.excelData)
              if (this.excelData.length > 999) {
                this.$message.warning('数据量大于999行')
              }
            } catch (error) {
              console.error('处理 Excel 文件时出错:', error)
            }
          } else {
            console.error('文件读取结果无效:', e.target)
          }
          this.loading = false
        }
        reader.onerror = error => {
          this.loading = false
          console.error('文件读取错误:', error)
        }

        // 确保 file.raw 存在并有效
        if (file.raw) {
          reader.readAsArrayBuffer(file.raw)
        } else {
          console.error('文件对象无效')
        }
      }

      // 更新 fileList 状态
      this.formPerson.fileList = fileList
    },
    //移除文件
    handlePersonRemove(file) {
      this.formPerson.fileList.splice(this.formPerson.fileList.indexOf(file), 1)
      this.$emit('input', this.listToString(this.formPerson.fileList))
    },
    getTemplateLink() {
      const params = {
        dictType: 'sys_template_link',
        dictValue: '3',
      }
      getTemplateLink(params).then(response => {
        this.templateLink = response.msg
      })
    },
    handleImport() {
      this.getTemplateLink({ dictValue: 3 })
      this.questionOpen = true
      this.formPerson.fileList = []
    },
    next() {
      if (this.formPerson.fileList.length === 0) {
        this.$message.warning('请先选择需要导入的excel文件')
        return
      }
      this.active++
      this.status = 'success'
    },
    personClose() {
      this.questionOpen = false
      this.formPerson.fileList = []
      this.getList()
    },
    before() {
      this.active--
      this.status = 'success'
      if (this.active === 1) {
        this.excelData = []
        this.errorCode = ''
        this.errorCorrectAnswers = []
        this.errorLine = []
        this.fileList = []
        this.formPerson.fileList = []
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
