<template>
  <BaseContainer class="material-detail">
    <NavBar title="文件下载" />
    <view class="header">
      <image mode="aspectFill" :src="material.image" alt="" />
      <view class="header-body">
        <view>{{ material.title }}</view>
        <view class="header-body-bottom">
          <view class="header-body-left flex-auto flex flex-column flex-between">
            <view>{{ material.ficti + material.sales }}人已下载</view>
            <view :class="{ money: material.pay_type }" class="price-box">
              <template v-if="material.pay_type">
                ￥
                <text>{{ material.money }}</text>
                <text>￥{{ material.member_money }}</text>
              </template>
              <template v-else> 免费 </template>
            </view>
          </view>
          <view class="button flex flex-column flex-center-x" @click="createShare">
            <i class="iconfont iconfenxiang"></i>
            <view>分享</view>
          </view>
          <view class="button flex flex-column flex-center-x" @click="collect">
            <i :class="[
              'iconfont',
              material.collect ? 'iconshoucang2' : 'iconshoucang11',
            ]"></i>
            <view>{{ material.collect ? "已收藏" : "收藏" }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 相关讲师 -->
    <RelatedLecturer v-if="lecturer" :lecturer="lecturer" />
    <view class="main">
      <view>
        <view>详情</view>
      </view>
      <mp-html container-style="padding: 30rpx;background: #ffffff;" :content="material.abstract"></mp-html>
    </view>
    <view class="footer">
      <navigator open-type="switchTab" class="button flex flex-column flex-center-y" url="/pages/index/index">
        <image :src="getImgPath('/wap/first/zsff/images/special01.png')" alt="" />
        首页
      </navigator>
        <view class="link"  >
            <view class="cont">
              <view>        
               
              </view>
            </view>
          </view>
      <!-- 抖音客服 -->
      <view class="button flex flex-column flex-center-y" v-if="TOUTIAO_STATUS">
        <image :src="getImgPath('/wap/first/zsff/images/special02.png')" alt="" />
        <button class="im"  open-type="im" :data-im-id="imId" bindim="imCallback"  binderror="onimError"> 
        <image :src="getImgPath('/wap/first/zsff/images/special02.png')" alt="" />
        客服</button>
      </view>
      <!-- 系统客服 -->
      <view class="button flex flex-column flex-center-y" @click="customerService" v-else>
        <image :src="getImgPath('/wap/first/zsff/images/special02.png')" alt="" />
        客服
      </view>
      <view v-if="
        !material.pay_type ||
        isPay ||
        (!material.member_pay_type && is_member)
      " class="flex button flex-center" @click="download(1)">
        立即下载
      </view>
      <button v-else class="button" @click="buy">立即购买</button>
    </view>
    <view :class="{ mask: hasDialog }" @touchmove.prevent @click="hasDialog = false"></view>
    <view v-if="(hasDialog && material.type == 1) || type == 1" class="android">
      <view class="dowmimage">
        <image mode="aspectFill" :src="getImgPath('/wap/first/zsff/images/material1.png')" alt="" />
      </view>

      <view>{{ material.title }}</view>
      <button class="flex-center" type="button" @click="download(2)">
        立即下载
      </button>
    </view>
    <view v-if="(hasDialog && material.type == 2) || type == 2" class="ios">
      <image :src="getImgPath('/wap/first/zsff/images/material2.png')" alt="" mode="aspectFill" />
      <view>复制下方链接及提取码到网盘下载</view>
      <view>
        <view>
          <view>链接：</view>
          <view>
            <a :href="material.network_disk_link">{{
              material.network_disk_link
              }}</a>
          </view>
        </view>
        <view>
          <view>提取码：</view>
          <view>{{ material.network_disk_pwd }}</view>
          <button @click="handleSetClipboard" class="btn flex flex-center" type="button">
            一键复制
          </button>
        </view>
      </view>
    </view>

    <PayDialog :open.sync="payDialogOpen" :money="Number(money)" :now_money="now_money" :special_id="material.id"
      :pay_type_num="pay_type_num" :is-wechat="isWechat" :is-alipay="is_alipay" :is-balance="is_yue"
      :template-id="templateId" :wxpay-h5="wxpayH5" :payStatus="false" :isMember="!!is_member" :isMembership="true"
      :memberMoney="Number(material.member_money)" @change="changeVal" />

    <TkiQrcode loadMake v-if="isQrcodeCanvasVisable" ref="qrcode" :showLoading="false" :val="qrcodeText"
      @result="handleQrcodeCreateSuccess" />

    <canvas canvas-id="poster" v-if="isPosterCanvasVisable" class="poster-canvas" />
    <web-view v-if="webViewUrl" :src="webViewUrl"></web-view>
  </BaseContainer>
</template>

<script>
  import RelatedLecturer from "@/components/RelatedLecturer/index.vue";
  import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html.vue";
  import PayDialog from "@/components/PayDialog/index.vue";
  import {
    delSpecialOrder,
    getDataDetails,
    aliPayApp,
    aliPayWap,
  } from "@/api/special";
  import { getLecturer } from "@/api/auth";
  import { recordDownload, toggleCollectMaterial } from "@/api/material";
  import posterMixin from "@/mixins/poster";
  import userInfoMixin from "@/mixins/userInfo";
  import { CUSTOMER_DETAIL_TYPE, CUSTOMER_SUPPORT_TYPE } from "@/constants/customer-type";

  export default {
    mixins: [posterMixin, userInfoMixin],
    components: {
      PayDialog,
      RelatedLecturer,
      mpHtml,
    },
    data() {
      return {
        isPosterCanvasVisable: false,
        material: {},
        is_member: false,
        isPay: false,
        isWechat: false,
        isAndroid: false,
        hasDialog: false,
        isCollect: false,
        payDialogOpen: false, // 是否显示支付弹窗
        money: 0,
        now_money: 0,
        link_pay_uid: "",
        pay_type_num: 70,
        is_alipay: false,
        is_yue: false,
        templateId: "",
        wxpayH5: false,
        loginShow: false,
        site_name: "",
        poster_image: "",
        lecturer: null,
        mer_id: 0,
        uid: 0,
        site_url: "",
        url: "",
        isOpenWeixing: false,
        type: null,
        webViewUrl: null,
        TOUTIAO_STATUS:false,
        imId:"",
      };
    },
    computed: {
      shareQrcodeData() {
        return {
          spread_uid: this.userInfo?.uid,
          id: this.mer_id,
        };
      },
    },
    onLoad(options) {
      const { id } = this.$util.mergeLaunchParams(options);
      this.mer_id = id;
      this.getData();
      this.getLecturer();
      /* #ifdef MP-TOUTIAO */
      this.TOUTIAO_STATUS = true;
      /* #endif */
    },
    onShow() {
      if (this.isOpenWeixing && this.orderId) {
        this.$util.wxh5PayIsSuccess(this.orderId, 5, this);
        this.isOpenWeixing = false;
      }
    },
    methods: {
      handleSetClipboard() {
        uni.setClipboardData({
          data:
            "链接：" +
            this.material.network_disk_link +
            "\n提取码：" +
            this.material.network_disk_pwd,
          success: () => {
            this.$util.showMsg("复制成功!");
          },
          fail: () => {
            this.$util.showMsg("复制失败!");
          },
        });
      },
      getData() {
        getDataDetails(this.mer_id).then(({ data }) => {
          const {
            material,
            site_url,
            is_member,
            isPay,
            site_name,
            isWechat,
            is_alipay,
            is_yue,
            now_money,
            wxpayH5,
            uid,
            d_im
          } = data;
          Object.assign(this, {
            material,
            site_url,
            is_member,
            isPay,
            site_name,
            isWechat,
            is_alipay: !!is_alipay,
            is_yue: !!is_yue,
            now_money: Number(now_money),
            wxpayH5,
            uid,
            url: site_url,
            poster_image: material.poster_image,
            imId:d_im
          });
        });
      },
      // 分享
      createShare() {
        this.createSharePoster("download", {
          id: this.mer_id,
          spread_uid: this.userInfo?.uid,
          url: 'pages/special/data_details'
        });
      },
      // 收藏
      collect() {
        toggleCollectMaterial(this.mer_id).then(() => {
          this.material.collect = !this.material.collect;
          this.$util.showMsg(this.material.collect ? "收藏成功" : "取消收藏成功");
        });
      },
      // 购买
      buy() {
        this.$util.checkLogin(() => {
          this.money = this.is_member
            ? this.material.member_money
            : this.material.money;
          this.payDialogOpen = true;
        });
      },
      // 下载
      download(type) {
        let that = this
        if (type === 1) {
          this.hasDialog = true;
        } else {
          this.recordDownload();
          // #ifdef H5 
          window.open(this.material.link);
          // #endif
          // #ifdef  MP-WEIXIN
          uni.setClipboardData({
            data: this.material.link,
            success: function () {
              that.$util.showMsg("该文件类型不支持小程序预览,已复制文件地址，请去浏览器下载")
              that.hasDialog = false
            }
          });
          // #endif
          // #ifdef APP-PLUS
          uni.downloadFile({
            url: this.material.link, //仅为示例，并非真实的资源
            success: (res) => {
              if (res.statusCode === 200) {
                console.log('下载成功');
              }
              uni.saveFile({
                tempFilePath: res.tempFilePath,
                success: function (red) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                    success: (sus) => {
                      console.log('成功打开')
                    }
                  })
                  console.log(red)
                }
              })
            }
          });
          // #endif
        }
      },
      changeVal(opt) {
        if (typeof opt !== "object") {
          opt = {};
        }
        var action = opt.action || "";
        var value = opt.value || "";
        this[action] && this[action](value);
      },
      // 支付完成后回调事件
      pay_order: function (data) {
        this.orderId = data.data.result.orderId || "";
        switch (data.data.status) {
          case "PAY_ERROR":
          case "ORDER_EXIST":
          case "ORDER_ERROR":
            this.extendOrder(data.msg);
            break;
          case "WECHAT_PAY":
            this.wechatPay(data.data.result.jsConfig);
            // this.$util.weixinAppPay(data.data.result.jsConfig,this);
            break;
          case "WECHAT_H5_PAY":
            this.payDialogOpen = false;
            this.$util.wechatH5Pay(data.data.result.jsConfig, this);
            break;
          case "WECHAT_ROUTINE_PAY":
            this.$util.wechatRoutinePay(data.data.result.jsConfig, this);
            break;
          case "SUCCESS":
            this.successOrder(data.msg);
            break;
          case "ZHIFUBAO_PAY":
            this.aliPay(data.data.result, "datadownload");
            break;
          case 'TOUTIAO_PAY':
            this.$util.toutiaoPay(data.data.result.jsConfig, this);
            break;
          case 'KUAISHOU_PAY':
            this.$util.kuaishouPay(data.data.result.jsConfig, this);
            break
        }
      },
      aliPay(msn, type) {
        this.$util.aliPay(msn, type, this);
      },
      extendOrder(msg) {
        if (typeof msg === "object" && msg.errMsg === "chooseWXPay:cancel") {
          msg = "微信支付取消";
        } else {
          msg = "支付失败";
        }
        this.$util.showMsg(msg);
        this.payDialogOpen = false;
        if (this.orderId) {
          delSpecialOrder(this.orderId);
        }
      },
      wechatPay(config) {
        this.$util.weixinpay(config, this);
      },
      successOrder(msg) {
        this.$util.showMsg(msg ? msg : "支付成功");
        this.payDialogOpen = false;
        this.isPay = true;
      },
      // 联系客服
      customerService() {
        this.$util.goSupport(CUSTOMER_DETAIL_TYPE.GOOD, CUSTOMER_SUPPORT_TYPE.DATA, this.mer_id);
      },
      recordDownload() {
        recordDownload(this.mer_id).then(() => {
          this.material.sales++;
        });
      },
      // 相关讲师
      getLecturer() {
        getLecturer(this.mer_id).then(({ data }) => {
          this.lecturer = data;
        });
      },
    },
  };
</script>

<style>
  page {
    padding-bottom: 100rpx;
    padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
  }
</style>

<style scoped lang="scss">
  .layui-layer-imgsee {
    display: none;
  }

  a[href^="tel"] {
    color: #2c8eff;
  }

  /* 资料详情 */
  .material-detail .header image {
    display: block;
    width: 100%;
    height: 420rpx;

    object-fit: cover;
  }

  .header-body {
    padding: 20rpx 30rpx;
    font-size: 36rpx;
    color: #333;
  }

  .header-body-bottom {
    display: flex;
    align-items: flex-end;
    margin-top: 15rpx;
    font-size: 22rpx;
    color: #999999;
  }

  .header-body-left {
    height: 107rpx;
  }

  .price-box {
    font-weight: bold;
    font-size: 36rpx;
    color: #ff6b00;
  }

  .money {
    font-size: 24rpx;
  }

  .material-detail .header .money text:first-child {
    font-size: 40rpx;
  }

  .material-detail .header .money text:nth-child(2) {
    padding-right: 46rpx;
    background: url(getAssetsPath("/wap/first/zsff/images/vip.png")) right center/46rpx 21rpx no-repeat;
    font-size: 28rpx;
    color: #282828;
  }

  .material-detail .header .button {
    font-family: inherit;
    font-weight: normal;
    font-size: 26rpx;
    line-height: normal;
    color: #999999;
  }

  .material-detail .header .button~.button {
    width: 84rpx;
    margin-left: 40rpx;
  }

  .material-detail .header .button .iconfont {
    font-size: 40rpx;
    color: #707070;
  }

  .material-detail .header .button .iconshoucang2 {
    color: #ff6b00;
  }

  .material-detail .header .button view {
    margin-top: 12rpx;
  }

  .material-detail .main {
    border-top: 14rpx solid #f5f5f5;
  }

  .material-detail .main>view:first-child {
    display: flex;

    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.03);
  }

  .material-detail .main>view:first-child view {
    position: relative;
    height: 96rpx;
    padding-right: 28rpx;
    padding-left: 28rpx;
    font-weight: bold;
    font-size: 32rpx;
    line-height: 96rpx;
    color: #282828;
  }

  .material-detail .main>view:first-child view::after {
    content: " ";
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 44rpx;
    height: 4rpx;
    border-radius: 2rpx;
    background-color: #2c8eff;

    transform: translateX(-50%);
  }

  .material-detail .main>view:last-child {
    padding: 30rpx;
  }

  .material-detail .main image {
    display: block;
    width: 100%;
  }

  .material-detail .footer {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;

    display: flex;
    padding-right: 30rpx;
    padding-bottom: var(--safe-bottom);
    padding-left: 8rpx;
    border-top: 1px solid #eee;
    background-color: #ffffff;
  }

  .material-detail .footer .button:not(:last-child) {
    height: 100rpx;
    padding-right: 22rpx;
    padding-left: 22rpx;
    font-family: inherit;
    font-weight: normal;
    font-size: 18rpx;
    line-height: normal;
    color: #333;
  }

  .material-detail .footer image {
    display: block;
    width: 40rpx;
    height: 40rpx;
    margin: 0 auto 5rpx;
  }

  .material-detail .footer .button:last-child {
    flex: 1;
    align-self: center;
    height: 76rpx;
    border-radius: 38rpx;
    margin-left: 26rpx;
    background: linear-gradient(90deg, #409dff 0%, #1e85fb 100%);
    font-family: inherit;
    font-weight: normal;
    font-size: 28rpx;
    line-height: 76rpx;
    color: #ffffff;
  }

  .material-detail .android,
  .material-detail .ios {
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 56;
    width: 600rpx;
    border-radius: 36rpx;
    background-color: #ffffff;

    transform: translate(-50%, -50%);
  }

  .material-detail .android img,
  .material-detail .ios image {
    display: block;
    width: 410rpx;
    height: 410rpx;
    margin: 24rpx auto;
  }

  .material-detail .android view {
    max-width: 90%;
    margin: 37rpx auto;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-weight: bold;
    font-size: 32rpx;
    text-align: center;
    color: #282828;
  }

  .material-detail .android button {
    width: 418rpx;
    height: 96rpx;
    line-height: 96rpx;
    border-radius: 48rpx;
    margin: 74rpx auto 94rpx;
    background: linear-gradient(180deg, #409dff 0%, #1e85fb 100%);

    box-shadow: 0 8rpx 20rpx rgba(0, 60, 230, 0.24);
    font-family: inherit;
    font-weight: normal;
    font-size: 30rpx;
    color: #ffffff;
  }

  .material-detail .ios>view:nth-child(2) {
    font-size: 32rpx;
    text-align: center;
    color: #b8b8b8;
  }

  .material-detail .ios>view:last-child {
    padding: 25rpx 20rpx 20rpx;
    border-radius: 10rpx;
    margin: 42rpx 30rpx 48rpx;
    background-color: #ececec;
    font-size: 26rpx;
    color: #666;
  }

  .material-detail .ios>view>view {
    display: flex;
  }

  .material-detail .ios>view>view view {
    margin-top: 18rpx;
  }

  .material-detail .ios>view>view>view:nth-child(2) {
    flex: 1;
    word-break: break-all;
  }

  .material-detail .ios navigator {
    color: inherit;
  }

  .material-detail .ios button {
    width: 140rpx;
    height: 44rpx;
    border-radius: 22rpx;
    background-color: #2c8eff;
    font-family: inherit;
    font-weight: normal;
    font-size: 22rpx;
    color: #ffffff;
  }

  .material-detail .share-image {
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 56;
    width: 600rpx;
    height: 960rpx;

    transform: translate(-50%, -50%);
  }

  .poster-canvas {
    width: 600px;
    height: 960px;
  }

  .dowmimage {
    margin: auto;

    image {
      width: 414rpx;
      height: 414rpx;
    }
  }
</style>