<template>
  <!-- 预览 -->
  <div v-if="isData" v-loading="loading" class="tarcer-dev-Preview">
    <HeaderPage />

    <HeaderOne v-if="!Ispreview && data" :text="data.name" :all-list="allList" />
    <div v-if="data" class="main">
      <div class="flassify">
        <div class="text">
          <p class="p1">{{ data.name }}</p>
          <p class="p2">
            {{ $t('Key227') }}：
            <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 v-if="!Ispreview" class="pay_collect">
          <div v-if="!data.isPurchased" class="price">
            ¥
            <span class="price_1" v-html="changePrice(data.price * 1, 24, 16)"></span>
          </div>
          <div v-if="!data.isPurchased" class="pay" @click="buy"><!-- 购买 -->{{ $t('Key72') }}</div>
          <div v-if="data.isPurchased && IsDownload" class="download">
            <img src="../../assets/teacherdev/download.png" alt="" @click="download" />
            <!-- <span>DOWNLOAD</span> -->
          </div>
          <div class="collect">
            <img v-show="!data.isFavorite" src="../../assets/teacherdev/collect4.png" alt="" @click="changeCollect" />
            <img v-show="data.isFavorite" src="../../assets/teacherdev/collect3.png" alt="" @click="changeCollect" />
          </div>
        </div>
      </div>
      <div :class="data.isPurchased || Ispreview ? 'buy' : 'NObuy'">
        <!--fileUrl需要改成安全地址 file_url_https -->
        <iframe id="ifm" :src="attachment[0].newpath" width="100%" height="1000px"></iframe>
        <!-- <object
          type="text/html"
          height="1000px"
          width="100%"
          :data="attachment[0].newpath"
        ></object> -->
        <!-- <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>
        <iframe
          v-else
          :src="'./pdf/web/viewer.html?file=' + attachment[0].fileRelativePath"
          style="width: 100%; height: 1000px"
        ></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" class="buyBtn" @click="buy"><!-- 点击购买 -->{{ $t('Key574') }}</div>
    </div>
    <el-dialog :visible.sync="NopymentShow" width="720px" :before-close="closeNoPyment">
      <div slot="title" class="dialogTitle"><!-- 商品详情 -->{{ $t('Key52') }}</div>
      <Confirmorder
        ref="Confirmorder"
        :data="data"
        :goods_type="401"
        :change-order-number="changeOrderNumber"
        :goods_detail_type="goods_detail_type"
      />
    </el-dialog>
    <el-dialog
      top="50px"
      :title="$t('Key472') + '：' + orderNumber"
      :visible.sync="PymentShow"
      width="720px"
      :before-close="closePyment"
    >
      <Payment :data="data" :order-number="orderNumber" :close-pyment="closePyment" />
    </el-dialog>
  </div>
</template>

<script>
import HeaderPage 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 { updateWordPack } from '@/utils/i18n';
import { getToken, getConfig } from '@/utils/auth';

const Base64 = require('js-base64').Base64;

import { materialdetail, materialvisit, LearnWebSI, Personamaterialdetail, getContentFile } from '@/api/api';
export default {
  name: 'TarcerDevPreview',
  components: {
    HeaderPage,
    HeaderOne,
    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,
      isData: false,
      goods_detail_type: null,
      file_preview_url: '',
    };
  },
  computed: {},
  async created() {
    let data = JSON.parse(getConfig());
    this.file_preview_url = data.doc_preview_service_address;
    await updateWordPack({
      word_key_list: [
        'Key5',
        'Key8',
        'Key9',
        'Key39',
        'Key43',
        'Key52',
        'Key53',
        'Key54',
        'Key55',
        'Key58',
        'Key72',
        'Key94',
        'Key475',
        'Key109',
        'Key131',
        'Key214',
        'Key232',
        'Key108',
        'Key396',
        'Key472',
        'Key473',
        'Key474',
        'Key572',
        'Key574',
        'Key575',
        'Key576',
        'Key696',
        'Key697',
        'Key227',
        'Key803',
        'Key790',
        'Key791',
        'Key792',
      ],
    });
    this.isData = true;
  },
  mounted() {
    this.materialId = this.$route.query.id;
    this.Ispreview = this.$route.query.type;
    this.allList = this.$route.query.allList;
    if (this.$route.query.invok_module === 'GCLS-Personal') {
      this.PersonalDetail();
    } else if (this.materialId) {
      this.getdetail();
      if (!this.Ispreview) {
        materialvisit({
          id: this.materialId,
        })
          .then((res) => {})
          .catch((res) => {
            this.loading = false;
          });
      }
    }
  },
  methods: {
    // 下载
    download() {
      let userInfor = getToken()
        ? JSON.parse(getToken())
        : sessionStorage.getItem('GCLS_Token_Tc')
        ? JSON.parse(sessionStorage.getItem('GCLS_Token_Tc'))
        : null;
      let SessionID = '';
      let UserCode = '';
      let UserType = '';
      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(price, fontSize1, fontSize2) {
      let _price = price || 0;
      _price = _price.toFixed(2).toString();
      let arr = _price.split('.');
      let str = `<span style="font-size: ${fontSize1 || 16}px;">${arr[0]}</span>.<span style="font-size: ${
        fontSize2 || 16
      }px;">${arr[1]}</span>`;
      return str;
    },
    // 获取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 Loading failed', 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.$t('Key396'), // "取消收藏成功",
            });
            this.data.isFavorite = false;

            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,
          goods_detail_type: this.goods_detail_type,
        })
          .then((res) => {
            this.$message({
              type: 'success',
              message: this.$t('Key575'), // "收藏成功",
            });
            this.data.isFavorite = true;

            this.loading = false;
            // this.getdetail();
          })
          .catch((res) => {
            this.loading = false;
          });
      }
    },
    // 购买
    buy() {
      if (!this.data.isAudited) {
        // "您还未通过审核不能购买"
        this.$message.warning(this.$t('Key576'));
        return;
      }
      this.NopymentShow = true;
    },
    // 获取学习资料详情
    getdetail() {
      this.loading = true;
      materialdetail({
        materialId: this.materialId,
        isSelectForUpdate: Boolean(this.Ispreview),
      })
        .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_BASE_API +
            //     this.attachment[0].fileRelativePath;
            //   console.log(this.attachment[0].fileRelativePath);
            //   this.getNumPages();
            // }
            this.changePrice(Number(this.data.price), 24, 16);
            this.goods_detail_type = this.getImgType(this.data);
            // 3000的
            // let path = `http://dcsapi.com/?k=71630476088128307289910&url=${this.attachment[0].fileUrlHttps}`;
            // this.attachment[0].newpath = path;
            // 400的
            // let path =
            //   "http://view.xdocin.com/xdoc?_xdoc=" +
            //   this.attachment[0].fileUrlHttps+"&printable=false&saveable=false"
            // this.attachment[0].newpath = path;
            // var originUrl = `${this.attachment[0].fileUrlHttps}?fileId=${this.attachment[0].fileId}`; //要预览文件的访问地址
            // var previewUrl =
            //   originUrl + `&fullfilename=${this.attachment[0].name}`;
            // GC 找的免费的 需要后台部署  谷歌可以 火狐和edge不行
            let path = `${this.file_preview_url}/onlinePreview?url=${Base64.encode(this.attachment[0].fileUrlHttps)}`;
            this.attachment[0].newpath = path;
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    PersonalDetail() {
      this.loading = true;
      Personamaterialdetail({
        materialId: this.materialId,
        isSelectForUpdate: Boolean(this.Ispreview),
      })
        .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);
            let path = `${this.file_preview_url}/onlinePreview?url=${Base64.encode(this.attachment[0].fileUrlHttps)}`;
            this.attachment[0].newpath = path;
            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_BASE_API +
            //     this.attachment[0].fileRelativePath;
            //   console.log(this.attachment[0].fileRelativePath);
            //   this.getNumPages();
            // }
            this.changePrice(Number(this.data.price), 24, 16);
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    getImgType(item) {
      return item.tag.indexOf('downloadable') === -1 ? item.tag[1] : item.tag[2];
    },
  },
};
</script>

<style lang="scss" scoped>
.tarcer-dev-Preview {
  height: 100%;

  .main {
    position: relative;
    min-height: 543px;
    padding-top: 30px;
    padding-bottom: 20px;
    background: #f6f6f6;
  }

  .flassify {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 1140px;
    height: 154px;

    // align-items: center;
    padding: 0 30px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;

    .text {
      height: 100%;
      padding-top: 24px;

      .p1 {
        font-size: 30px;
        font-weight: bold;
        color: #1f2127;
      }

      .p2 {
        margin-top: 8px;
        margin-bottom: 8px;
        font-size: 16px;
        color: #1f2127;
      }
    }

    .pay_collect {
      display: flex;
      align-content: center;

      // position: absolute;
      // right: 30px;
      // bottom: 24px;
      height: 100%;
      padding-top: 90px;

      .price {
        margin-right: 20px;
        font-size: 24px;
        font-weight: bold;

        .price_2 {
          font-size: 16px;
        }
      }

      .pay {
        width: 120px;
        height: 40px;
        margin-right: 20px;
        font-size: 20px;
        font-weight: 600;
        line-height: 40px;
        color: white;
        text-align: center;
        cursor: pointer;
        background: #f90;
        border-radius: 4px;
      }

      .collect {
        display: flex;
        align-items: center;
        height: 40px;
        font-size: 24px;
        font-weight: bold;
        color: #1f2127;

        img {
          width: 24px;
          margin-right: 10px;
          cursor: pointer;
        }
      }

      .download {
        display: flex;
        align-items: center;
        height: 40px;
        margin-right: 20px;
        font-size: 24px;
        font-weight: bold;
        color: #1f2127;

        img {
          width: 24px;
          margin-right: 10px;
          cursor: pointer;
        }
      }
    }
  }

  .buy {
    width: 1200px;
    min-height: 1000px;
    margin: 24px auto;

    // filter: blur(8px);
  }

  .NObuy {
    width: 1200px;
    min-height: 1000px;
    margin: 24px auto;
    filter: blur(8px);
  }

  .buyBtn {
    position: relative;
    top: -150px;
    width: 284px;
    height: 67px;
    margin: 0 auto;
    font-size: 22px;
    font-weight: bold;
    line-height: 67px;
    color: white;
    text-align: center;
    cursor: pointer;
    background: #f90;
    border-radius: 8px;
  }

  .dialogTitle {
  }
}
</style>
<style lang="scss">
.tarcer-dev-Preview {
  .el-dialog__body {
    padding: 30px 32px;
  }
}

.cui-ribbonTopBars {
  display: none !important;
}

.overlay--1PlEz {
  display: none !important;
}

#overlay--1PlEz {
  display: none !important;
}
</style>
