<template>
  <!-- 预览 -->
  <div class="tarcer-dev-Preview" v-loading="loading">
    <div class="header">
      <Header />
      <div class="shade"></div>
    </div>
    <HeaderOne v-if="!Ispreview && data" :text="data.name" :allList="allList" />
    <div class="main" v-if="data">
      <div class="flassify">
        <div class="text">
          <p class="p1">{{ data.name }}</p>
          <p class="p2">
            <span v-for="(item, i) in data.teacher" :key="i + item">
              {{ item }}{{ i == data.teacher.length - 1 ? "" : "," }}
            </span>
          </p>
          <p>{{ data.updateTime }}</p>
        </div>
        <div class="pay_collect" v-if="!Ispreview">
          <div class="price" v-if="!data.isPurchased">
            ￥
            <span class="price_1" v-text="changePrice('1', data.price)"></span>
            <span class="price_2" v-text="changePrice('2', data.price)"></span>
          </div>
          <div class="pay" @click="buy" v-if="!data.isPurchased">购买</div>
          <div class="download" v-if="data.isPurchased && IsDownload">
            <img
              @click="download"
              src="../../assets/teacherdev/download.png"
              alt=""
            />
            <!-- <span>DOWNLOAD</span> -->
          </div>
          <div class="collect">
            <img
              @click="changeCollect"
              v-show="!data.isFavorite"
              src="../../assets/teacherdev/collect4.png"
              alt=""
            />
            <img
              @click="changeCollect"
              v-show="data.isFavorite"
              src="../../assets/teacherdev/collect3.png"
              alt=""
            />
          </div>
        </div>
      </div>
      <div :class="data.isPurchased || Ispreview ? 'buy' : 'NObuy'">
        <!--fileUrl需要改成安全地址 file_url_https -->
        <iframe
          v-if="
            attachment[0].fileType != 'pdf' && attachment[0].fileType != 'PDF'
          "
          :src="
            'https://view.officeapps.live.com/op/view.aspx?src=' +
            `${attachment[0].fileUrlHttps}`
          "
          width="100%"
          height="1000px"
          scrolling="no"
          id="if"
        >
        </iframe>
        <pdf
          v-else
          ref="pdf"
          :src="attachment[0].fileRelativePath"
          v-for="i in numPages"
          :key="i"
          :page="i"
        >
          {{ i / numPages }}
        </pdf>
      </div>
      <div v-if="!data.isPurchased && !Ispreview" @click="buy" class="buyBtn">
        点击购买
      </div>
    </div>
    <el-dialog
      :visible.sync="NopymentShow"
      width="720px"
      :before-close="closeNoPyment"
    >
      <div class="dialogTitle" slot="title">商品详情</div>
      <Confirmorder
        ref="Confirmorder"
        :data="data"
        :goods_type="401"
        :changeOrderNumber="changeOrderNumber"
      />
    </el-dialog>
    <el-dialog
      top="50px"
      :title="'订单号：' + orderNumber"
      :visible.sync="PymentShow"
      width="720px"
      :before-close="closePyment"
    >
      <Payment
        :data="data"
        :orderNumber="orderNumber"
        :closePyment="closePyment"
      />
    </el-dialog>
  </div>
</template>

<script>
import Header from "@/components/Header";
import HeaderOne from "@/components/teacher-dev/HeaderOne";
import pdf from "vue-pdf";
import Confirmorder from "@/components/payment/Confirmorder";
import Payment from "@/components/payment/Payment";
import Cookies from "js-cookie";
import { getToken } from "@/utils/auth";

import {
  materialdetail,
  materialfavoriteinsert,
  materialfavoritedelete,
  materialvisit,
  LearnWebSI,
} from "@/api/api";
export default {
  name: "tarcer-dev-Preview",
  components: {
    Header,
    HeaderOne,
    pdf,
    Confirmorder,
    Payment,
  },
  data() {
    return {
      numPages: null,
      isCollect: false,
      materialId: null,
      data: null,
      attachment: null,
      loading: false,
      Ispreview: "", // 是不是预览
      NopymentShow: false, //添加订单弹窗
      PymentShow: false, //支付订单弹窗
      orderNumber: null, //订单号
      IsDownload: false, //是否可以下载
      allList: null,
    };
  },
  computed: {},
  methods: {
    // 下载
    download() {
      let userInfor = JSON.parse(getToken());
      let UserCode = "",
        UserType = "",
        SessionID = "";
      if (userInfor) {
        UserCode = userInfor.user_code;
        UserType = userInfor.user_type;
        SessionID = userInfor.session_id;
      }
      let FileID = this.attachment[0].fileId;
      let data = {
        SessionID,
        UserCode,
        UserType,
        FileID,
      };
      location.href =
        process.env.VUE_APP_BASE_API +
        `/GCLSFileServer/WebFileDownload?UserCode=${data.UserCode}&UserType=${data.UserType}&SessionID=${data.SessionID}&FileID=${data.FileID}`;
    },
    // 生成订单 同时切换到支付弹窗
    changeOrderNumber(
      val,
      back_discount_code,
      discount_money,
      receivables_money
    ) {
      this.orderNumber = val;
      this.NopymentShow = false;
      this.data.back_discount_code = back_discount_code;
      this.data.discount_money = discount_money;
      this.data.receivables_money = receivables_money;
      this.PymentShow = true;
      console.log(this.data);
    },
    closeNoPyment() {
      this.NopymentShow = false;
      this.$refs.Confirmorder.clearData();
    },
    closePyment(str) {
      this.PymentShow = false;
      if (str == "支付成功") {
        this.getdetail();
      }
    },
    // 处理价格
    changePrice(type, item) {
      if (item.indexOf(".") != -1) {
        this.data.price = item.split(".")[0] + "." + item.split(".")[1];
        if (type == 1) {
          return item.split(".")[0];
        } else if (type == 2) {
          return "." + item.split(".")[1];
        }
      } else {
        this.data.price = item + ".00";
        if (type == 1) {
          return item;
        }
        if (type == 2) {
          return ".00";
        }
      }
    },
    // 获取pdf的页数
    getNumPages() {
      this.loading = true;
      let _this = this;
      let loadingTask = pdf.createLoadingTask(
        _this.attachment[0].fileRelativePath
      );

      loadingTask.promise
        .then((pdf) => {
          if (_this.data.isPurchased) {
            _this.numPages = pdf.numPages;
          } else {
            _this.numPages = 2;
          }
          _this.loading = false;
        })
        .catch((err) => {
          console.error("pdf 加载失败", err);
        });
    },
    // 修改收藏状态
    changeCollect() {
      this.loading = true;
      if (this.data.isFavorite) {
        let Mname = "order-collection_manager-CancelMyGoodsCollection";
        LearnWebSI(Mname, {
          goods_id_list: [this.materialId],
          goods_type: 401,
        })
          .then((res) => {
            this.$message({
              type: "success",
              message: "取消收藏成功",
            });
            this.loading = false;
            this.getdetail();
          })
          .catch((res) => {
            this.loading = false;
          });
      } else {
        let Mname = "order-collection_manager-AddMyCollection";
        LearnWebSI(Mname, {
          goods_id: this.materialId,
          goods_type: 401,
          goods_name: this.data.name,
          goods_person_name_desc: this.data.teacher,
          goods_picture_id: this.data.coverFileId,
          goods_price: this.data.price,
        })
          .then((res) => {
            this.$message({
              type: "success",
              message: "收藏成功",
            });
            this.loading = false;
            this.getdetail();
          })
          .catch((res) => {
            this.loading = false;
          });
      }
    },
    // 购买
    buy() {
      if (!this.data.isAudited) {
        this.$message.warning("您还未通过审核不能购买");
        return;
      }
      this.NopymentShow = true;
    },
    // 获取学习资料详情
    getdetail() {
      this.loading = true;
      materialdetail({
        materialId: this.materialId,
        isSelectForUpdate: this.Ispreview ? true : false,
      })
        .then((res) => {
          if (res.data.result) {
            let index = res.data.result.tag.indexOf("downloadable");
            if (index != -1) {
              this.IsDownload = true;
            }
            this.data = res.data.result;
            this.data.pymentTeacher = "";
            res.data.result.teacher.forEach((item, i) => {
              if (i != this.data.teacher.length - 1) {
                this.data.pymentTeacher += item + ";";
              } else {
                this.data.pymentTeacher += item;
              }
            });
            this.data.fileType = this.data.tag[this.data.tag.length - 1];
            this.attachment = JSON.parse(res.data.result.attachment);
            this.loading = false;
            if (
              this.attachment[0].fileType == "pdf" ||
              this.attachment[0].fileType == "PDF"
            ) {
              // this.attachment[0].fileRelativePath =
              //   process.env.VUE_APP_BASE_API + this.attachment[0].fileRelativePath;
              this.attachment[0].fileRelativePath =
                process.env.VUE_APP_PDF_API +
                this.attachment[0].fileRelativePath;
              console.log(this.attachment[0].fileRelativePath);
              this.getNumPages();
            }
            this.changePrice(this.data.price);
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },
  },
  created() {},
  mounted() {
    this.materialId = this.$route.query.id;
    this.Ispreview = this.$route.query.type;
    this.allList = this.$route.query.allList;
    if (this.materialId) {
      this.getdetail();
      if (!this.Ispreview) {
        materialvisit({
          id: this.materialId,
        })
          .then((res) => {})
          .catch((res) => {
            this.loading = false;
          });
      }
    }
    let node = document.getElementsByClassName("cui-ribbonTopBars")[0];
    console.log(node);
  },
};
</script>

<style lang="scss" scoped>
.tarcer-dev-Preview {
  height: 100%;
  .header {
    height: 64px;
    background: url("../../assets/teacherdev/Homebg2.png") no-repeat;
    background-size: 100% 100%;
    position: relative;
    .shade {
      position: absolute;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      color: #fff;
      font-weight: bold;
      font-size: 18px;
      justify-content: space-around;
      align-items: center;
      .el-menu-demo {
        background: rgba(0, 0, 0, 0);
        li:hover {
          background: none;
        }
        li {
          background: none;
        }
      }
    }
  }
  .main {
    min-height: 543px;
    background: #f6f6f6;
    padding-bottom: 20px;
    padding-top: 30px;
    position: relative;
  }
  .flassify {
    position: relative;
    width: 1140px;
    height: 154px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;
    .text {
      .p1 {
        font-weight: bold;
        font-size: 30px;
        color: #1f2127;
      }
      .p2 {
        margin-top: 8px;
        margin-bottom: 8px;
        font-size: 16px;
        color: #1f2127;
      }
    }
    .pay_collect {
      position: absolute;
      right: 30px;
      bottom: 24px;
      display: flex;
      align-items: center;
      .price {
        font-weight: bold;
        font-size: 24px;
        margin-right: 20px;
        .price_2 {
          font-size: 16px;
        }
      }
      .pay {
        width: 120px;
        height: 40px;
        background: #ff9900;
        border-radius: 4px;
        color: white;
        font-weight: 600;
        font-size: 20px;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        margin-right: 20px;
      }
      .collect {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 24px;
        color: #1f2127;
        img {
          width: 24px;
          margin-right: 10px;
          cursor: pointer;
        }
      }
      .download {
        margin-right: 20px;
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 24px;
        color: #1f2127;
        img {
          width: 24px;
          margin-right: 10px;
          cursor: pointer;
        }
      }
    }
  }
  .buy {
    width: 1200px;
    margin: 24px auto;
    min-height: 1000px;
    // filter: blur(8px);
  }
  .NObuy {
    width: 1200px;
    margin: 24px auto;
    min-height: 1000px;
    filter: blur(8px);
  }
  .buyBtn {
    width: 284px;
    height: 67px;
    background: #ff9900;
    border-radius: 8px;
    text-align: center;
    line-height: 67px;
    color: white;
    font-weight: bold;
    font-size: 22px;
    margin: 0 auto;
    cursor: pointer;
    position: relative;
    top: -150px;
  }
  .dialogTitle {
  }
}
</style>
<style lang="scss">
.tarcer-dev-Preview {
  .el-dialog__body {
    padding: 30px 32px;
  }
}
.cui-ribbonTopBars {
  display: none !important;
}
</style>