<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="标题：">
          <el-input type="text" v-model="search.courseTitle" />
        </el-form-item>
        <el-form-item label="培训计划分类：">
          <el-select v-model="search.trainingPlanClassificationId">
            <el-option
              v-for="item in optionList"
              :key="item.id"
              :label="item.categoriesName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作者：">
          <el-input type="text" v-model="search.categoriesAuthor" />
        </el-form-item>
        <el-form-item label="主讲老师：">
          <el-input type="text" v-model="search.categoriesLecturer" />
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="initList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>

    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="doAdd(1)">
            新增</el-button
          >
        </div>
        <div>
          <right-toolbar
            @queryTable="initList"
            :search="true"
            @update:showSearch="isSearch = !isSearch"
          ></right-toolbar>
        </div>
      </div>

      <el-table
        :data="list"
        height="calc(100% - 200px)"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
      >
        <el-table-column width="80" type="index" label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + (search.pageNo - 1) * search.pageSize + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="courseTitle"
          show-overflow-tooltip
          label="标题"
          align="center"
        />
        <el-table-column
          show-overflow-tooltip
          label="培训计划分类"
          align="center"
        >
          <template #default="{ row }">
            {{ row.trainingPlanClassificationId }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="作者" align="center">
          <template #default="{ row }">
            {{ row.categoriesAuthor }}
          </template>
        </el-table-column>
        <el-table-column
          prop="categoriesLecturer"
          show-overflow-tooltip
          label="主讲老师"
          align="center"
        />
        <el-table-column
          prop="createDate"
          show-overflow-tooltip
          label="创建时间"
          align="center"
        />
        <el-table-column
          prop="userName"
          show-overflow-tooltip
          label="创建人"
          align="center"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="doAdd(2, scope.row)">
              编辑
            </el-button>
            <el-button type="text" @click="doAdd(3, scope.row)">
              查看
            </el-button>
            <el-button type="text" @click="doDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :page.sync="search.pageNo"
        :limit.sync="search.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="initList"
      />
    </el-main>

    <!-- 新增/编辑 的dialog -->
    <el-dialog
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="70%"
      :title="isEdit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题：" prop="courseTitle">
              <el-input
                :disabled="disabledVal"
                v-model="ruleForm.courseTitle"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="培训计划分类："
              prop="trainingPlanClassificationId"
            >
              <el-select
                v-model="ruleForm.trainingPlanClassificationId"
                style="width: 100%"
                :disabled="disabledVal"
              >
                <el-option
                  v-for="item in optionList"
                  :key="item.id"
                  :label="item.categoriesName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="作者：" prop="categoriesAuthor">
              <el-input
                :disabled="disabledVal"
                v-model="ruleForm.categoriesAuthor"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主讲老师：" prop="categoriesLecturer">
              <el-input
                :disabled="disabledVal"
                v-model="ruleForm.categoriesLecturer"
                maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="简介：" prop="categoriesBriefIntroduction">
              <el-input
                :disabled="disabledVal"
                v-model="ruleForm.categoriesBriefIntroduction"
                type="textarea"
                maxlength="1000"
                rows="4"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重要内容：" prop="importantContent">
              <el-input
                :disabled="disabledVal"
                v-model="ruleForm.importantContent"
                type="textarea"
                maxlength="1000"
                rows="4"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注：">
          <el-input
            :disabled="disabledVal"
            v-model="ruleForm.remarkInfo"
            type="textarea"
            maxlength="500"
            rows="4"
          ></el-input>
        </el-form-item>

        <el-row>
          <el-col :span="12" v-if="!disabledVal">
            <el-form-item label="课件文件：" prop="fileListCourse">
              <el-upload
                drag
                class="upload-demo"
                :http-request="addCourse"
                :on-remove="removeCourse"
                :on-change="changeCourse"
                action="#"
                :file-list="ruleForm.fileListCourse"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogLookImg" v-if="dialogLookImg">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item label="课件文件：">
              <el-link
                type="primary"
                :underline="false"
                @click="gotoUrl(ruleForm)"
                >{{ ruleForm.coursewareName }}</el-link
              >
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!disabledVal">
            <el-form-item label="封面图片：">
              <el-upload
                :before-upload="beforeUpload"
                ref="uploadRef"
                action="#"
                list-type="picture-card"
                :http-request="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="ruleForm.imgFileList"
                :on-change="handleChange"
                accept=".jpg,.jpeg,.png,.gif,.tif,.bmp,.svg,.jpg,"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogLookImg" v-if="dialogLookImg">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-else>
            <el-form-item label="封面图片：">
              <el-image
                style="width: 1rem; height: 1rem"
                :src="ruleForm.coverPhoto"
                :preview-src-list="imgList"
              >
              </el-image>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer" v-if="!disabledVal">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 文件预览 -->
    <el-dialog
      title="预览附件"
      :visible.sync="previewAnnex"
      :fullscreen="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
    >
      <div class="bbbbb">
        <preview-file
          :preview-url="previewUrl"
          :preview-type="previewType"
          @handleDownload="handleDownload"
        />
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import previewFile from '@/components/previewFile/previewFile.vue'
import FileSaver from 'file-saver'
import {
  getCourseList,
  saveCourse,
  queryLastLevelClassification,
  delCourseById,
  upload,
  getCourseById,
  getBaseApi,
  resourceDownload
} from '@/api/planClass/planClass.js'
export default {
  name: 'RuoyiPlanClass',
  components: {
    previewFile
  },
  data() {
    return {
      // 文件预览
      previewAnnex: false,
      previewUrl: '',
      previewType: '',
      filename: '',

      baseUrl: process.env.VUE_APP_BASE_API,
      isSearch: false, //控制搜索框是否显示
      search: {
        courseTitle: '',
        trainingPlanClassificationId: '',
        categoriesAuthor: '',
        categoriesLecturer: '',
        pageNo: 1,
        pageSize: 10
      },
      total: 0, //总数

      list: [],
      dialogVisible: false, //新增/修改的dialog
      isEdit: '',
      disabledVal: false, //查看禁用

      ruleForm: {
        courseTitle: '',
        trainingPlanClassificationId: '',
        categoriesBriefIntroduction: '',
        categoriesAuthor: '',
        categoriesLecturer: '',
        importantContent: '',
        coursewareUrl: '',
        coursewareName: '',
        coverPhoto: '',
        remarkInfo: '',
        fileListCourse: [], // 课件上传的参数
        imgFileList: [] // 封面上传的参数
      },
      // 封面上传的参数
      dialogImageUrl: '',
      dialogLookImg: false,
      imgFileList: 'imgFileList',
      imgList: [], // 预览的数组

      // 图片的限制格式
      whiteList: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'bmp', 'svg', 'jpg'],
      watchList: ['pdf',
'txt',
'excel',
'word',
'xlsx',
'xls'],

      rules: {
        courseTitle: [
          { required: true, message: '请输入题目标题', trigger: 'blur' }
        ],
        trainingPlanClassificationId: [
          { required: true, message: '请选择培训计划分类', trigger: 'change' }
        ],
        categoriesBriefIntroduction: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        categoriesAuthor: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        categoriesLecturer: [
          { required: true, message: '请输入主讲老师', trigger: 'blur' }
        ],
        importantContent: [
          { required: true, message: '请输入重要内容', trigger: 'blur' }
        ],
        fileListCourse: [
          { required: true, message: '请上传课件文件', trigger: 'change' }
        ],
        imgFileList: [
          { required: true, message: '请上传封面图片', trigger: 'change' }
        ]
      },
      loading: false // loading 效果
    }
  },

  mounted() {
    this.initList() // 列表初始化
    this.initQueryLastLevelClassification() //培训计划分类下拉菜单
  },

  methods: {
    // 列表初始化
    initList() {
      try {
        this.loading = true
        getCourseList(this.search).then((res) => {
          if (res.code === 200) {
            this.list = res.data.list
            this.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
          this.loading = false
        })
      } catch (error) {
        this.loading = false
      }
    },
    // 重置
    reset() {
      this.search.courseTitle = ''
      this.search.trainingPlanClassificationId = ''
      this.search.categoriesAuthor = ''
      this.search.categoriesLecturer = ''
      this.initList()
    },
    async initQueryLastLevelClassification(val) {
      const res = await queryLastLevelClassification()
      this.optionList = res.data
    },
    initSubject(type) {
      switch (type) {
        case '0':
          return '全部'
        case '1':
          return '单选题'
        case '2':
          return '多选题'
        case '3':
          return '判断题'
        default:
          return '-'
      }
    },
    async doAdd(type, val) {
      if (type === 1) {
        this.isEdit = '新增'
        this.ruleForm = {
          courseTitle: '',
          trainingPlanClassificationId: '',
          categoriesBriefIntroduction: '',
          categoriesAuthor: '',
          categoriesLecturer: '',
          importantContent: '',
          coursewareUrl: '',
          coursewareName: '',
          coverPhoto: '',
          remarkInfo: '',
          fileListCourse: [], // 课件上传的参数
          imgFileList: [] // 封面上传的参数
        }
        this.ruleForm.fileListCourse = []
        this.ruleForm.imgFileList = []
        this.disabledVal = false
      } else if (type === 2) {
        this.isEdit = '编辑'
        const res = await getCourseById(val.id)
        this.ruleForm = { ...res.data, fileListCourse: [], imgFileList: [] }
        this.ruleForm.fileListCourse.push({
          name: val.coursewareName
        })
        this.dialogImageUrl = this.baseUrl + val.coverPhoto
        this.ruleForm.imgFileList.push({
          uid: Date.now(),
          url: this.baseUrl + val.coverPhoto,
          name: '封面'
        })

        this.disabledVal = false
      } else {
        this.isEdit = '查看'
        this.disabledVal = true
        this.ruleForm = { ...val }
        this.imgList = this.ruleForm.coverPhoto
          .split(',')
          .map((item) => this.baseUrl + item)
        this.ruleForm.coverPhoto = this.baseUrl + val.coverPhoto
      }
      this.$nextTick(() => {
        this.dialogVisible = true
        this.$nextTick(() => {
          if (this.ruleForm.imgFileList.length > 0) {
            this.$refs.uploadRef.$el.children[1].style.display = 'none'
          } else {
            this.$refs.uploadRef.$el.children[1].style.display = 'block'
          }
        })
      })
    },
    // 取消按钮
    cancle() {
      this.$nextTick(() => {
        this.ruleForm = {
          courseTitle: '',
          trainingPlanClassificationId: '',
          categoriesBriefIntroduction: '',
          categoriesAuthor: '',
          categoriesLecturer: '',
          importantContent: '',
          coursewareUrl: '',
          coursewareName: '',
          coverPhoto: '',
          remarkInfo: '',
          fileListCourse: [], // 课件上传的参数
          imgFileList: [] // 封面上传的参数
        }
        this.$refs.ruleFormRef.resetFields()
      })
      this.dialogVisible = false
    },
    // 确定按钮
    submit() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          const res = await saveCourse(this.ruleForm)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm = {
            courseTitle: '',
            trainingPlanClassificationId: '',
            categoriesBriefIntroduction: '',
            categoriesAuthor: '',
            categoriesLecturer: '',
            importantContent: '',
            coursewareUrl: '',
            coursewareName: '',
            coverPhoto: '',
            remarkInfo: '',
            fileListCourse: [], // 课件上传的参数
            imgFileList: [] // 封面上传的参数
          }
          this.dialogVisible = false
        } else {
          this.$message.warning('必传项不能为空!')
          return false
        }
      })
    },
    // 删除
    doDelete(val) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delCourseById(val.id)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 上传封面需要的参数
    handleRemove(file, fileList) {
      this.ruleForm.imgFileList = fileList
      this.dialogImageUrl = ''
      if (!fileList.length) {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'block'
        this.imgFileList = 'imgFileList'
      }
    },
    handleChange(file, fileList) {
      // 当上传图片成功时，即隐藏上传按钮
      if (fileList.length > 0) {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'none'
      } else {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'block'
      }
    },
    // 封面上传格式校验
    beforeUpload(file) {
      if (file.size === 0) {
        this.$message.error('文件不能为空')
        return false
      }
      const end = file.name.split('.')[file.name.split('.').length - 1]
      if (!this.whiteList.includes(end)) {
        this.$message.error('文件格式错误')
        return false
      }
      return true
    },
    // 封面上传
    async handlePictureCardPreview(file) {
      try {
        if (!file) return this.$message.error('文件有误')
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await upload(formData)
        this.dialogImageUrl = res.url
        this.$nextTick(() => {
          this.dialogVisible = true
        })
        if (res.code !== 200) {
          this.ruleForm.imgFileList = []
          return this.$message.error('文件格式不支持')
        }
        this.ruleForm.coverPhoto = res.fileName
      } catch (error) {
        this.ruleForm.imgFileList = []
      }
    },
    // 移除课件文件的校验
    changeCourse() {
      this.$nextTick(() => {
        this.$refs.ruleFormRef.validateField('fileListCourse')
      })
    },
    // 移除课件文件的上传
    removeCourse(file, fileList) {
      this.ruleForm.fileListCourse = fileList
    },
    // 上传课件文件的请求
    async addCourse(file) {
      try {
        if (!file) return this.$message.error('文件有误')
        if (this.ruleForm.fileListCourse.length) {
          this.ruleForm.fileListCourse.splice(0, 1)
        }
        this.ruleForm.fileListCourse.push({
          name: file.file.name
        })
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await upload(formData)
        if (res.code !== 200) {
          this.ruleForm.fileListCourse = []
          return this.$message.error('文件格式不支持')
        }
        this.ruleForm.coursewareUrl = res.fileName
        this.ruleForm.coursewareName = res.originalFilename
      } catch (error) {
        this.ruleForm.fileListCourse = []
      }
    },
    gotoUrl(row) {
      console.log(
        row.coursewareName
          .split('.')
          [row.coursewareName.split('.').length - 1].toLocaleLowerCase(),
        888
      )
      if (
        this.watchList.includes(row.coursewareName
          .split('.')
          [row.coursewareName.split('.').length - 1].toLocaleLowerCase())) {
        getBaseApi(row.coursewareUrl).then((res) => {
          if (res.code !== 200) return this.$message.error(res.msg)
          let wj = encodeURIComponent(res.msg)
          wj = decodeURIComponent(wj)
          const myBlob = this.dataURLtoBlob(wj)
          this.previewUrl = myBlob
          this.previewType =
            row.coursewareName.split('.')[
              row.coursewareName.split('.').length - 1
            ]
          this.filename = row.coursewareName
          this.previewAnnex = true
        })
      } else {
        resourceDownload(row.coursewareUrl).then((res) => {
          const aBlob = new Blob([res])
          FileSaver.saveAs(aBlob, row.coursewareName)
        })
      }
    }, // 获取文件后缀名
    iconByType(filename) {
      return filename.substring(filename.lastIndexOf('.') + 1, filename.length)
    },
    handleDownload() {
      // 生成地址
      const myUrl = URL.createObjectURL(this.previewUrl)
      // 下载文件
      this.downloadFile(myUrl, this.filename)
    },
    dataURLtoBlob(dataurl) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      // eslint-disable-next-line no-plusplus
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    downloadFile(url, name) {
      const a = document.createElement('a')
      a.setAttribute('href', url)
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      const clickEvent = document.createEvent('MouseEvents')
      clickEvent.initEvent('click', true, true)
      a.dispatchEvent(clickEvent)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

// ::v-deep  {
//   background-color: transparent !important;
// }
::v-deep .el-loading-spinner {
  top: 65% !important;
}
::v-deep .el-loading-spinner i {
  font-size: 0.1513rem !important;
}

::v-deep .el-upload--picture-card {
  background-color: transparent;
}
::v-deep .el-upload-dragger {
  // border: 1px dashed #fff;
  width: 350px !important;
  height: 150px;
}
::v-deep .el-upload-list {
  width: 350px !important;
}
</style>
