<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="课程名称" prop="lessonName">
        <el-input
          v-model="queryParams.lessonName"
          placeholder="请输入课程名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="培训开始时间" prop="trainStartTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.trainStartTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择培训开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="培训结束时间" prop="trainEndTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.trainEndTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择培训结束时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="培训状态" prop="trainStatus">
        <el-select v-model="queryParams.trainStatus" placeholder="请选择培训状态" clearable size="small">
          <el-option label="待发布" value="0" />
          <el-option label="已发布" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="manageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程名称" align="center" prop="lessonName" />
      <el-table-column label="培训时长/分" align="center" prop="trainDuration" />
      <el-table-column label="培训开始时间" align="center" prop="trainStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="培训结束时间" align="center" prop="trainEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="视频" align="center" prop="video">&ndash;&gt;
        <template v-slot="{ row: { lessonName, video } }">
          <a @click="downLoadVideo(video, lessonName)" class="down-load">下载视频</a>
        </template>
      </el-table-column>-->
      <el-table-column label="附件地址" align="center" prop="annexUrl">
        <template v-slot="{ row: { annexUrl } }">
          <a
            v-if="annexUrl && annexUrl.indexOf('.txt') >= 0"
            @click="downloadText(annexUrl)"
            class="down-load"
          >下载附件</a>
          <span v-else-if="annexUrl ==null || annexUrl== ''">-</span>
          <a v-else :href="annexUrl" class="down-load">下载附件</a>
        </template>
      </el-table-column>
      <el-table-column label="培训状态" align="center" prop="trainStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.trainStatus == '0'">待发布</span>
          <span v-if="scope.row.trainStatus == '1'">已发布</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="trainManageDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.trainStatus == '0'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="trainPublish(scope.row)"
            v-if="scope.row.trainStatus == '0'"
          >发布</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"
    />

    <!-- 添加或修改培训管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="lessonName">
              <el-input :disabled="isView" v-model="form.lessonName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训时长" prop="trainDuration">
              <el-input :disabled="isView" style="width: 312px" v-model="form.trainDuration" placeholder="分钟" /> <span>(分钟)</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="培训开始时间" prop="trainStartTime">
              <el-date-picker clearable size="small"
                              style="width: 100%"
                              v-model="form.trainStartTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              :disabled="isView"
                              placeholder="选择培训开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训结束时间" prop="trainEndTime">
              <el-date-picker clearable size="small"
                              style="width: 100%"
                              v-model="form.trainEndTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              :disabled="isView"
                              placeholder="选择培训结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 培训人员选择 -->
        <el-form-item label="培训人员选择" prop="aaaa">
          <PeopleChoice
            ref="changePaple"
            :disabled="isView"
            @getPeopleList="getPeopleList"/>
        </el-form-item>

        <el-form-item label="课程内容" prop="lessonContent">
          <editor v-if="open" :readOnly="isView" v-model="form.lessonContent" :min-height="192"/>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="视频地址" prop="videoUrl">
              <FileUpload
                listType="picture"
                @resFun="getFileInfoVideo"
                @remove="listRemoveVideo"
                :fileArr="fileListVideo"
                :fileSize="500"
                :fileType="['mp4']"
                :disabled="isView"
              />
              <el-input v-show="false" disabled v-model="form.videoUrl"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件地址" prop="annexUrl">
              <FileUpload
                listType="picture"
                @resFun="getFileInfoFile"
                @remove="listRemoveFile"
                :fileArr="fileListFile"
                :fileType="fileType"
                :disabled="isView"
              />
              <el-input v-show="false" disabled v-model="form.annexUrl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listManage, getManage, delManage, addManage, updateManage, exportManage } from "@/api/trainManage/manage";
import Editor from '@/components/Editor';
import FileUpload from "@/components/FileUpload";
import uploadfile from "@/assets/uploadfile.png";
import PeopleChoice from "@/components/PeopleChoice";
export default {
  name: "Manage",
  components: {
    Editor,
    FileUpload,
    PeopleChoice
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训管理表格数据
      manageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lessonName: null,
        trainDuration: null,
        trainStartTime: null,
        trainEndTime: null,
        lessonContent: null,
        videoUrl: null,
        annexUrl: null,
        trainStatus: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lessonName: [
          { required: true, message: "请输入课程名称", trigger: "blur" }
        ],
        trainDuration: [
          { required: true, message: "请输入培训时长", trigger: "blur" }
        ],
        trainStartTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        trainEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        lessonContent: [
          { required: true, message: "请输入培训内容", trigger: "blur" }
        ],
      },
      fileListVideo:[],
      fileListFile:[],
      fileType: ["pdf"],
      // 培训人员
      jsonSelectNameList: null,
      peopleList: [],
      isView: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询培训管理列表 */
    getList() {
      this.loading = true;
      listManage(this.queryParams).then(response => {
        this.manageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        trainManageId: null,
        lessonName: null,
        trainDuration: null,
        trainStartTime: null,
        trainEndTime: null,
        lessonContent: null,
        videoUrl: null,
        annexUrl: null,
        trainStatus: "0",
        createTime: null,
        updateTime: null,
        remark: null,
        isDel: null,
        tTrainPersonList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.trainManageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      /*this.$nextTick(() => {
          this.$refs.changePaple.changeNameList(undefined);
      })*/
      this.title = "添加培训管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isView = false;
      const trainManageId = row.trainManageId || this.ids
      getManage(trainManageId).then(response => {
        this.form = response.data;
        this.fileListVideo = this.form.video? [
          {
            name: this.form.lessonName + "视频",
            url: uploadfile,
          },
        ]:[];
        this.fileListFile = this.form.annexUrl?[
          {
            name: this.form.lessonName + "附件",
            url: uploadfile,
          },
        ]:[];
        this.open = true;
        this.$nextTick(() => {
          this.$refs.changePaple.changeNameList(this.form.tTrainPersonList);
        })
        this.title = "修改培训管理";
      });
    },
    /**详情*/
    trainManageDetail(row){
      this.reset();
      this.isView = true;
      const trainManageId = row.trainManageId || this.ids
      getManage(trainManageId).then(response => {
        this.form = response.data;
        this.fileListVideo = this.form.video? [
          {
            name: this.form.lessonName + "视频",
            url: uploadfile,
          },
        ]:[];
        this.fileListFile = this.form.annexUrl?[
          {
            name: this.form.lessonName + "附件",
            url: uploadfile,
          },
        ]:[];
        this.open = true;
        this.$nextTick(() => {
            this.$refs.changePaple.changeNameList(this.form.tTrainPersonList);
        })
        this.title = "培训管理详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.peopleList.length < 1) {
            this.$message.error("请至少选择一个考试人员");
            return;
          }
          this.form.tTrainPersonList = this.peopleList;
          this.form.trainDuration = this.form.trainDuration;
          if (this.form.trainManageId != null) {
            updateManage(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addManage(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const trainManageIds = row.trainManageId || this.ids;
      this.$confirm('是否确认删除培训管理名称为"' + row.lessonName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delManage(trainManageIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 发布*/
    trainPublish(row) {
      const trainManageIds = row.trainManageId || this.ids;
      this.$confirm('是否确认发布培训管理名称为"' + row.lessonName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateManage({"trainManageId":trainManageIds,"trainStatus":"1","publishTime":new Date().getTime()}).then(response => {
            this.msgSuccess("发布成功");
            this.getList();
        });

    }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有培训管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportManage(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    getFileInfoVideo(res) {
      this.form.videoUrl = res.url;
      this.fileListVideo = [
        {
          name: res.fileName,
          url: uploadfile,
        },
      ];
    },
    listRemoveVideo(e) {
      this.fileListVideo = [];
      this.form.videoUrl = "";
      // this.form.videoName = null;
    },
    getFileInfoFile(res) {
      this.form.annexUrl = res.url;
      this.fileListFile = [
        {
          name: res.fileName,
          url: uploadfile,
        },
      ];
    },
    listRemoveFile(e) {
      this.fileListFile = [];
      this.form.annexUrl = "";
    },
    // 获取培训人员的list
    getPeopleList(list) {
      console.log("培训人员", list);
      this.peopleList = list;
    },
    downloadText(url) {
      // url = url.replace(/\\/g, "/");
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
      xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let blob = this.response;
          console.log(blob);
          // 转换一个blob链接
          // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串),
          // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
          let downLoadUrl = window.URL.createObjectURL(
            new Blob([blob], {
              type: "txt",
            })
          );
          // 视频的type是video/mp4,图片是image/jpeg
          // 01.创建a标签
          let a = document.createElement("a");
          // 02.给a标签的属性download设定名称
          a.download = name;
          // 03.设置下载的文件名
          a.href = downLoadUrl;
          // 04.对a标签做一个隐藏处理
          a.style.display = "none";
          // 05.向文档中添加a标签
          document.body.appendChild(a);
          // 06.启动点击事件
          a.click();
          // 07.下载完毕删除此标签
          a.remove();
        }
      };

      xhr.send();
    },
    downLoadVideo(url, name) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "arraybuffer"; // 返回类型blob
      xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let blob = this.response;
          console.log(blob);
          // 转换一个blob链接
          // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串),
          // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
          let downLoadUrl = window.URL.createObjectURL(
            new Blob([blob], {
              type: "video/mp4",
            })
          );
          // 视频的type是video/mp4,图片是image/jpeg
          // 01.创建a标签
          let a = document.createElement("a");
          // 02.给a标签的属性download设定名称
          a.download = name;
          // 03.设置下载的文件名
          a.href = downLoadUrl;
          // 04.对a标签做一个隐藏处理
          a.style.display = "none";
          // 05.向文档中添加a标签
          document.body.appendChild(a);
          // 06.启动点击事件
          a.click();
          // 07.下载完毕删除此标签
          a.remove();
        }
      };
      xhr.send();
    },
  }
};
</script>
<style scoped lang="scss">
  .down-load {
    color: #0bab0c;
  }
</style>