<template>
  <div id="share">
    <el-dialog
      :visible.sync="dialogVisible"
      width="520px"
      :show-close="false"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">分享</div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Close@2x.png"
            alt=""
            @click="dialogVisible = false"
          />
        </div>
      </div>
      <el-form label-width="180px" :model="formLabelAlign">
        <el-form-item label="观看权限：">
          <el-radio-group v-model="formLabelAlign.watchPer" @change="submitTable">
            <el-radio :label="1">已开通课程的学员</el-radio>
            <el-radio :label="2">所有学员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="观看链接（PC端）：">
          <span id="copycode">{{ formLabelAlign.enCodePC }}</span
          ><el-button
            v-if="formLabelAlign.enCodePC"
            type="text"
            style="margin-left: 10px"
            @click="copyUrl"
            >复制</el-button
          >
        </el-form-item>
        <el-form-item label="观看二维码：">
          <img
            style="width: 100px; height: 100px"
            :src="formLabelAlign.enCode"
            alt=""
          />
          <el-button
            type="text"
            @click="downloadFileByBase64(formLabelAlign.enCode, '小程序二维码')"
            >下载</el-button
          >
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <!-- <el-button type="primary" @click="submitTable">保 存</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false, //分享窗口
      formLabelAlign: {
        watchPer: 1,
        enCode: "",
      },
      keyIdArray: [],
      sectionType: "",
      goodsId: "",
    };
  },
  methods: {
    /**
     * 复制地址
     */
    copyUrl() {
      const range = document.createRange();//创建range对象;
      range.selectNode(document.getElementById("copycode")); //获取复制内容的 id 选择器
      const selection = window.getSelection(); //创建 selection对象
      if (selection.rangeCount > 0) selection.removeAllRanges(); //如果页面已经有选取了的话，会自动删除这个选区，没有选区的话，会把这个选取加入选区
      selection.addRange(range); //将range对象添加到selection选区当中，会高亮文本块
      document.execCommand("copy"); //复制选中的文字到剪贴板
      this.$message.success("复制成功");
      selection.removeRange(range); // 移除选中的元素
    },
    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      if (!dataurl) {
        this.$message.error("下载失败");
        return;
      }
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    //下载方法
    downloadFile(url, name = "下载图") {
      var a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("download", name);
      a.setAttribute("target", "_blank");
      let clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },

    downloadFileByBase64(base64, name) {
      var myBlob = this.dataURLtoBlob(base64);
      var myUrl = URL.createObjectURL(myBlob);
      this.downloadFile(myUrl, name);
    },
    /**
     * 打开分享窗口
     */
    openBox(rows, goodsId) {
      this.keyIdArray = rows.keyId.split("-").map(Number);
      this.goodsId = goodsId;
      this.sectionType = rows.sectionType;
      this.$api
        .coursesectionwatchper({
          goodsId: this.goodsId,
          courseId: this.keyIdArray[0] || "",
          moduleId: this.keyIdArray[1] || "",
          chapterId: this.keyIdArray[2] || "",
          sectionId: this.keyIdArray[3] || "",
          sectionType: this.sectionType,
        })
        .then((res) => {
          if (res.data) {
            if (!res.data.watchPer) {
              res.data.watchPer = 1;
            }
            this.formLabelAlign = res.data;
          } else {
            this.formLabelAlign = {
              goodsId: this.goodsId,
              courseId: this.keyIdArray[0] || "",
              moduleId: this.keyIdArray[1] || "",
              chapterId: this.keyIdArray[2] || "",
              sectionId: this.keyIdArray[3] || "",
              sectionType: this.sectionType,
              watchPer: 1,
            };
          }
          this.dialogVisible = true;
        });
    },
    /**
     * 保存分享
     */
    submitTable() {
      let data;
      if (this.formLabelAlign.id) {
        data = this.formLabelAlign;
      } else {
        data = {
          goodsId: this.goodsId,
          courseId: this.keyIdArray[0] || "",
          moduleId: this.keyIdArray[1] || "",
          chapterId: this.keyIdArray[2] || "",
          sectionId: this.keyIdArray[3] || "",
          sectionType: this.sectionType,
          watchPer: this.formLabelAlign.watchPer,
        };
      }
      this.$api.coursesectionaddwatchper(data).then((res) => {
        this.$message.success("保存成功");
      });
    },
  },
};
</script>

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