<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.trainingPlanName" />
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="search.lessonScheduleState">
            <el-option label="待审核" value="1" />
            <el-option label="通过" value="2" />
            <el-option label="驳回" value="3" />
          </el-select>
        </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="trainingPlanName"
          show-overflow-tooltip
          label="名称"
          align="center"
        />
        <el-table-column
          show-overflow-tooltip
          label="学习开始时间"
          align="center"
        >
          <template #default="{ row }">
            {{ row.learningStartTime }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="学习结束时间"
          align="center"
        >
          <template #default="{ row }">
            {{ row.learningEndTime }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="是否需要考试"
          align="center"
        >
          <template #default="{ row }">
            {{ row.isExamination === '1' ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="状态" align="center">
          <template #default="{ row }">
            {{ initlessonScheduleState(row.lessonScheduleState) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="approveNickName"
          show-overflow-tooltip
          label="审核人"
          align="center"
        />
        <el-table-column
          show-overflow-tooltip
          label="审核时间"
          align="center"
        >
        <template #default="{ row }">
            {{ row.approveTime?row.approveTime :'-' }}
          </template>
      </el-table-column>
        <el-table-column label="操作" width="200" >
          <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
              style="color: #e6a23c"
              type="text"
              @click="doAdd(4, scope.row)"
              v-if="scope.row.lessonScheduleState == '1' && scope.row.approveName === $store.state.user.name"
            >
              审核
            </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="50%"
      :title="isEdit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ul   v-if="(isEdit == '审批' ||isEdit == '查看' )&& ruleForm.lessonScheduleState ==3">
        <li>驳回时间：{{ruleForm.approveTime}}</li>
        <li>驳回原因：{{ruleForm.approveOpinion}}</li>
      </ul>
      <div style="height: 70vh; overflow: auto">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleFormRef"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="名称：" prop="trainingPlanName">
            <el-input
              :disabled="disabledVal"
              v-model="ruleForm.trainingPlanName"
              maxlength="99"
              style="width: 70%"
            ></el-input>
          </el-form-item>

          <el-form-item label="岗位：" prop="sysPostList">
            <el-select
              v-model="ruleForm.sysPostList"
              style="width: 70%"
              :disabled="disabledVal"
              multiple
            >
              <el-option
                v-for="item in postList"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始结束时间：" prop="allTime">
            <el-date-picker
              v-model="ruleForm.allTime"
              :disabled="disabledVal"
              style="width: 70%"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item
            label="培训计划分类："
            prop="trainingPlanClassificationId"
          >
            <el-select
              @change="
                changeTrainingPlanClassification(
                  ruleForm.trainingPlanClassificationId,
                  2
                )
              "
              v-model="ruleForm.trainingPlanClassificationId"
              style="width: 70%"
              :disabled="disabledVal"
            >
              <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="计划类型：" prop="planType">
            <el-radio-group v-model="ruleForm.planType" :disabled="disabledVal">
              <el-radio label="1">文件</el-radio>
              <el-radio label="2">课程</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="文件："
            prop="trainingPlanDocumentsList"
            v-if="ruleForm.planType == 1 && !disabledVal"
          >
            <el-upload
              drag
              class="upload-demo"
              :http-request="addCourse"
              :on-remove="removeCourse"
              :on-change="changeCourse"
              action="#"
              :file-list="ruleForm.trainingPlanDocumentsList"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="文件："
            v-if="ruleForm.planType == 1 && disabledVal"
          >
            <el-row>
              <el-col
                style="color: #1890ff"
                v-for="item in ruleForm.trainingPlanDocumentsList"
                :key="item.id"
              >
                <span @click="gotoUrl(item)" style="cursor: pointer">
                  {{ item.name }}
                </span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item
            label="课程："
            prop="trainingPlanCourseList"
            v-if="ruleForm.planType == 2"
          >
            <el-select
              v-model="ruleForm.trainingPlanCourseList"
              style="width: 70%"
              :disabled="disabledVal"
              multiple
            >
              <el-option
                :label="item.courseTitle"
                :value="item.id"
                v-for="item in courseOptions"
                :key="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="封面图片：" v-if="!disabledVal">
            <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-form-item label="封面图片：" v-else>
            <div v-if="!imgList.length">暂无封面</div>
            <el-image
              v-else
              style="width: 1rem; height: 1rem"
              :src="ruleForm.coverPhoto"
              :preview-src-list="imgList"
              alt="暂无封面"
            >
            </el-image>
          </el-form-item>

          <el-form-item label="简介：" prop="briefIntroduction">
            <el-input
              :disabled="disabledVal"
              v-model="ruleForm.briefIntroduction"
              style="width: 70%"
              type="textarea"
              maxlength="999"
              rows="4"
            ></el-input>
          </el-form-item>

          <el-form-item label="备注：">
            <el-input
              :disabled="disabledVal"
              v-model="ruleForm.remarkInfo"
              style="width: 70%"
              type="textarea"
              maxlength="99"
              rows="4"
            ></el-input>
          </el-form-item>

          <el-form-item label="是否需要考试：" prop="isExamination">
            <el-radio-group v-model="ruleForm.isExamination">
              <el-radio label="1">是</el-radio>
              <el-radio label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="考试次数："
            prop="retakesNumber"
            v-if="ruleForm.isExamination == 1"
          >
            <el-input
              :disabled="disabledVal"
              v-model="ruleForm.retakesNumber"
              type="number"
              on-keypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))"
              style="width: 70%"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="证书："
            prop="certificateId"
            v-if="ruleForm.isExamination == 1"
          >
            <el-select
              v-model="ruleForm.certificateId"
              style="width: 70%"
              :disabled="disabledVal"
            >
              <el-option
                :label="item.certificateName"
                :value="item.id"
                v-for="item in cerOptions"
                :key="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="审核人：" prop="approveBy">
            <el-select
              v-model="ruleForm.approveBy"
              style="width: 70%"
              :disabled="disabledVal"
            >
              <el-option
                :label="item.nickName"
                :value="item.userId"
                v-for="item in approveByOptions"
                :key="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

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

      <span slot="footer" class="dialog-footer" v-if="isEdit == '审批'">
        <el-button @click="dialogRejectVisible = true">驳 回</el-button>
        <el-button type="primary" @click="dorejectSubmit">通 过</el-button>
      </span>
    </el-dialog>

    <!-- 驳回的弹窗 -->
    <el-dialog
      :visible.sync="dialogRejectVisible"
      v-if="dialogRejectVisible"
      width="30%"
      top="20"
      title="驳回原因"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form label-width="100px" class="demo-ruleForm">
        <el-form-item label="驳回原因：">
          <el-input
            v-model="rejectForm.approveOpinion"
            maxlength="100"
            style="width: 70%"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectCancle">取消</el-button>
        <el-button type="primary" @click="rejectSubmit">确认</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 {
  getTrainingPlanList,
  getTrainingPlanById,
  delTrainingPlanById,
  getCourseSelect,
  saveTrainingPlan,
  allList,
  queryLastLevelClassification,
  upload,
  optionselect,
  getCertificateSelect,
  auditTrainingPlan,
  getBaseApi,
  resourceDownload
} from '@/api/planClass/planClass.js'
import { positiveIntNum } from '@/utils/rules.js'
export default {
  name: 'RuoyiPlanClass',
  components: {
    previewFile
  },
  data() {
    return {
       // 文件预览
       previewAnnex: false,
      previewUrl: '',
      previewType: '',
      filename: '',

      baseUrl: process.env.VUE_APP_BASE_API,
      isSearch: false, //控制搜索框是否显示
      search: {
        trainingPlanName: '',
        lessonScheduleState: '',
        pageNo: 1,
        pageSize: 10
      },
      total: 0, //总数
      postList: [],

      list: [],
      dialogVisible: false, //新增/修改的dialog
      dialogRejectVisible: false, //驳回的dialog
      isEdit: '',
      disabledVal: false, //查看禁用
      optionList: [], //培训计划分类的下拉
      courseOptions: [], // 课程下拉菜单
      cerOptions: [], // 证书下拉菜单
      approveByOptions: [], // 审核人下拉菜单
      ruleForm: {
        trainingPlanName: '',
        sysPostList: [],
        allTime:[], //开始结束时间
        learningStartTime: '',
        learningEndTime: '',
        trainingPlanClassificationId: '',
        planType: '',
        certificateId: '',
        trainingPlanDocumentsList: [],
        trainingPlanCourseList: [],
        imgFileList: '',
        briefIntroduction: '',
        remarkInfo: '',
        isExamination: '',
        retakesNumber: '',
        approveBy: ''
      },
      rejectForm: {
        approveOpinion: ''
      },

      // 封面上传的参数
      dialogImageUrl: '',
      dialogLookImg: false,
      imgFileList: 'imgFileList',
      imgList: [], // 预览的数组

      // 图片的限制格式
      whiteList: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'bmp', 'svg', 'jpg'],

      rules: {
        trainingPlanName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sysPostList: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ],
        learningStartTime: [
          { required: true, message: '请输入开始时间', trigger: 'change' }
        ],
        learningEndTime: [
          { required: true, message: '请输入结束时间', trigger: 'change' }
        ],
        trainingPlanClassificationId: [
          { required: true, message: '请选择培训计划分类', trigger: 'change' }
        ],
        planType: [
          { required: true, message: '请选择计划类型', trigger: 'change' }
        ],
        trainingPlanDocumentsList: [
          { required: true, message: '请上传文件', trigger: 'blur' }
        ],
        trainingPlanCourseList: [
          { required: true, message: '请选择课程', trigger: 'change' }
        ],
        briefIntroduction: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        isExamination: [
          { required: true, message: '请选择是否需要考试', trigger: 'change' }
        ],
        retakesNumber: [
          { required: true, message: '请输入考试次数', trigger: 'blur' },
          positiveIntNum
        ],
        approveBy: [
          { required: true, message: '请选择审核人', trigger: 'change' }
        ],
        allTime: [
          { required: true, message: '请选择开始结束时间', trigger: 'change' }
        ],
      },
      loading: false // loading 效果
    }
  },

  mounted() {
    console.log(this.$store.state.user.name)
    this.initPostList() // 岗位初始化
    this.initList() // 列表初始化
    this.initQueryLastLevelClassification() //培训计划分类下拉菜单
  },

  methods: {
    // 列表初始化
    initList() {
      try {
        this.loading = true
        getTrainingPlanList(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.trainingPlanName = ''
      this.search.lessonScheduleState = ''
      this.initList()
    },
    async initQueryLastLevelClassification(val) {
      const res = await queryLastLevelClassification()
      this.optionList = res.data
    },
    async initPostList() {
      const res = await optionselect()
      // console.log(res);
      this.postList = res.data
    },

    initSubject(type) {
      switch (type) {
        case '0':
          return '全部'
        case '1':
          return '单选题'
        case '2':
          return '多选题'
        case '3':
          return '判断题'
        default:
          return '-'
      }
    },
    initStatus(type) {
      switch (type) {
        case '1':
          return '待审核'
        case '2':
          return '通过'
        case '3':
          return '审核不通过'
        default:
          return '-'
      }
    },
    async doAdd(type, val) {
      this.initAllList()
      if (type === 1) {
        this.isEdit = '新增'
        this.ruleForm = {
          trainingPlanName: '',
          sysPostList: [],
          learningStartTime: '',
          learningEndTime: '',
          trainingPlanClassificationId: '',
          planType: '',
          allTime:[], //开始结束时间
          certificateId: '',
          trainingPlanDocumentsList: [],
          trainingPlanCourseList: [],
          imgFileList: '',
          briefIntroduction: '',
          remarkInfo: '',
          isExamination: '',
          retakesNumber: '',
          approveBy: ''
        }
        this.ruleForm.fileListCourse = []
        this.ruleForm.imgFileList = []
        this.disabledVal = false
      } else if (type === 2) {
        this.isEdit = '编辑'
        const res = await getTrainingPlanById({ id: val.id })
        this.ruleForm = { ...res.data, fileListCourse: [], imgFileList: [] }
        this.ruleForm.trainingPlanDocumentsList = []
        res.data.trainingPlanDocumentsList.forEach((item) => {
          this.ruleForm.trainingPlanDocumentsList.push({
            name: item.name,
            fileUrl: item.fileUrl
          })
        })
        this.dialogImageUrl = this.baseUrl+ val.coverPhoto
        if (val.coverPhoto) {
          this.ruleForm.imgFileList.push({
            uid: Date.now(),
            url: this.baseUrl+ val.coverPhoto,
            name: '封面'
          })
        }
        this.ruleForm.sysPostList = res.data.sysPostList.map(
          (item) => +item.postId
        )
        this.ruleForm.trainingPlanCourseList =
          res.data.trainingPlanCourseList.map(
            (item) => item.trainingPlanClassificationId
          )
        this.changeTrainingPlanClassification(
          this.ruleForm.trainingPlanClassificationId,
          1
        )

        this.disabledVal = false
      } else if (type === 3) {
        this.isEdit = '查看'
        this.disabledVal = true
        const res = await getTrainingPlanById({ id: val.id })
        this.ruleForm = { ...res.data }
        this.ruleForm.sysPostList = res.data.sysPostList.map(
          (item) => +item.postId
        )
        this.ruleForm.trainingPlanCourseList =
          res.data.trainingPlanCourseList.map(
            (item) => item.trainingPlanClassificationId
          )
        this.changeTrainingPlanClassification(
          this.ruleForm.trainingPlanClassificationId,
          1
        )
        this.ruleForm.coverPhoto =this.baseUrl+ val.coverPhoto
        this.imgList = this.ruleForm.coverPhoto
          ? this.ruleForm.coverPhoto.split(',')
          : []
      } else {
        this.isEdit = '审批'
        this.disabledVal = true
        const res = await getTrainingPlanById({ id: val.id })
        this.ruleForm = { ...res.data }
        this.ruleForm.sysPostList = res.data.sysPostList.map(
          (item) => +item.postId
        )
        this.ruleForm.trainingPlanCourseList =
          res.data.trainingPlanCourseList.map(
            (item) => item.trainingPlanClassificationId
          )
        this.rejectForm.id = this.ruleForm.id
        this.changeTrainingPlanClassification(
          this.ruleForm.trainingPlanClassificationId,
          1
        )
        this.ruleForm.coverPhoto =this.baseUrl+ val.coverPhoto
        this.imgList = this.ruleForm.coverPhoto
          ? this.ruleForm.coverPhoto.split(',')
          : []
      }
      this.$nextTick(() => {
        this.dialogVisible = true
        this.$nextTick(()=>{
          if(Array.isArray(this.ruleForm.imgFileList)){
            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 = {
          trainingPlanName: '',
          sysPostList: [],
          allTime:[], //开始结束时间
          learningStartTime: '',
          learningEndTime: '',
          trainingPlanClassificationId: '',
          planType: '',
          certificateId: '',
          trainingPlanDocumentsList: [],
          trainingPlanCourseList: [],
          imgFileList: '',
          briefIntroduction: '',
          remarkInfo: '',
          isExamination: '',
          retakesNumber: '',
          approveBy: ''
        }
        this.$refs.ruleFormRef.resetFields()
      })
      this.dialogVisible = false
    },
    // 确定按钮
    submit() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          this.ruleForm.learningStartTime= this.ruleForm.allTime[0]
          this.ruleForm.learningEndTime= this.ruleForm.allTime[1]

          this.ruleForm.sysPostList = this.ruleForm.sysPostList.map((item) => {
            return {
              postId: item,
              id: '',
              trainingPlanId: ''
            }
          })

          this.ruleForm.trainingPlanCourseList =
            this.ruleForm.trainingPlanCourseList.map((item) => {
              return {
                trainingPlanClassificationId: item,
                id: '',
                trainingPlanId: ''
              }
            })

          const res = await saveTrainingPlan(this.ruleForm)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.initList()
          this.$message.success(`${this.isEdit}成功!`)
          this.ruleForm = {
            trainingPlanName: '',
            sysPostList: [],
            learningStartTime: '',
            learningEndTime: '',
            trainingPlanClassificationId: '',
            planType: '',
            allTime:[], //开始结束时间
            certificateId: '',
            trainingPlanDocumentsList: [],
            trainingPlanCourseList: [],
            imgFileList: '',
            briefIntroduction: '',
            remarkInfo: '',
            isExamination: '',
            retakesNumber: '',
            approveBy: ''
          }
          this.dialogVisible = false
        } else {
          this.$message.warning('必传项不能为空!')
          return false
        }
      })
    },

    // 删除
    doDelete(val) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delTrainingPlanById({ id: 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.trainingPlanDocumentsList = fileList
    },
    // 上传课件文件的请求
    async addCourse(file) {
      try {
        if (!file) return this.$message.error('文件有误')
        // this.ruleForm.trainingPlanDocumentsList.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.trainingPlanDocumentsList = []
          return this.$message.error('文件格式不支持')
        }
        this.ruleForm.trainingPlanDocumentsList.push({
          name: res.originalFilename,
          fileUrl: res.fileName
        })
        // this.ruleForm.coursewareName = res.originalFilename
      } catch (error) {
        this.ruleForm.trainingPlanDocumentsList = []
      }
    },
    initlessonScheduleState(type) {
      switch (type) {
        case '1':
          return '待审核'
        case '2':
          return '通过'
        case '3':
          return '驳回'
      }
    },
    // 修改培训计划分类
    async changeTrainingPlanClassification(val, type) {
      const res = await getCourseSelect({
        trainingPlanClassificationId: this.ruleForm.trainingPlanClassificationId
      })
      this.courseOptions = res.data
      const req = await getCertificateSelect({
        trainingPlanClassificationId: this.ruleForm.trainingPlanClassificationId
      })
      this.cerOptions = req.data
      if (type !== 1) {
        this.ruleForm.trainingPlanCourseList = []
      }
    },
    // 审核人下拉
    async initAllList() {
      const res = await allList()
      this.approveByOptions = res.data
    },
    // 通过
    dorejectSubmit() {
      this.$confirm('确认通过吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.rejectForm.lessonScheduleState = '2'
          const res = await auditTrainingPlan(this.rejectForm)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.dialogVisible = false
          this.$message.success('通过成功!')
          this.initList()
        })
        .catch(() => {
          this.$message.info('已取消通过')
        })
    },
    rejectCancle() {
      this.rejectForm.approveOpinion = ''
      this.dialogRejectVisible = false
    },
    async rejectSubmit() {
      if (!this.rejectForm.approveOpinion)
        return this.$message.info('驳回原因不能为空!')
      this.rejectForm.lessonScheduleState = '3'
      const res = await auditTrainingPlan(this.rejectForm)
      if (res.code !== 200) return this.$message.error(res.msg)
      this.dialogVisible = false
      this.dialogRejectVisible = false
      this.$message.success('驳回成功!')
      this.initList()
    },
    gotoUrl(row) {
      console.log(row);
      if (
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'pdf' ||
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'txt' ||
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'excel' ||
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'word' ||
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'xlsx' ||
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'xls' ||
        row.name
          .split('.')
          [row.name.split('.').length - 1].toLocaleLowerCase() ===
          'docx'
      ) {
        console.log(1);
        getBaseApi(row.fileUrl).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.name.split('.')[
              row.name.split('.').length - 1
            ]
          this.filename = row.name
          this.previewAnnex = true
        })
      } else {
        console.log(2);
        resourceDownload(row.fileUrl).then((res) => {
          const aBlob = new Blob([res])
          FileSaver.saveAs(aBlob, row.name)
        })
      }
    }, // 获取文件后缀名
    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 .el-loading-mask {
  background-color: rgba(0, 222, 240, 0.2) !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 {
  width: 350px !important;
  height: 150px;
}
::v-deep .el-upload-list {
  width: 350px !important;
}
</style>
