<template>
  <div class="goods-details-wrapper" :class="{'no-pt': isWeb}">
    <CommonNavbar
      id="header"
      :isWeb="isWeb"
      :bgColor="bgColor"
      v-show="isShowNavbar"
      :isBlack="isBlack"
      :isShowShare="isShowShare"
      :title="navTitle"
      :shareTitle="goods.goodsName"
      :shareTitleInfo="shareTitleInfo"
      :isFixNavbar="isFixNavbar"
      :shareUrl="shareUrl"
      borderStyle="0px solid #fff"
    ></CommonNavbar>
    <!-- 轮播 -->
    <div class="swiper-box">
      <van-swipe :show-indicators="false" @change="onSwiperChange">
        <van-swipe-item v-for="(item, index) in swiperList" :key="index">
          <img class="img" :src="item.goodsImgUrl" alt />
        </van-swipe-item>
      </van-swipe>
      <div class="indicator">{{ swiperCurtIndex + 1 }}/{{ swiperList.length }}</div>
    </div>
    <!-- 商品信息 -->
    <div class="info-box border-line">
      <p class="title">{{ goods.goodsName }}</p>
      <div class="price">
        <div class="money">
          <span class="yuan">￥{{ goods.salePriceNew.yuan }}</span>
          <span class="fen">.{{ goods.salePriceNew.fen }}</span>
          <span v-if="goods.hasDiscount" class="del">原价: ¥{{ goods.costPriceText }}</span>
        </div>
        <div class="bought">{{ goods.saledNum }}购买</div>
      </div>
    </div>
    <!-- 购买数量、优惠券、支付方式 -->
    <div class="buy-box border-line">
      <div class="flex">
        <div class="name">购买数量</div>
        <div class="buy-num">
          <div class="reduce" @click="onReduce"></div>
          <div class="num">{{ goodsNum }}</div>
          <div class="plus" @click="onPlus"></div>
        </div>
      </div>

      <div class="flex buy-way">
        <div class="name">优惠券</div>
        <div @click="showCouponPopup" class="coupon-select coupon-pc" :class="{'no-coupon' : getCPText() == '无优惠券'}">{{getCPText()}}</div>
      </div>

      <div class="flex buy-way">
        <div class="name">
          支付方式
          <span>目前只支持微信支付</span>
        </div>
        <div class="way">微信支付</div>
      </div>
    </div>
    <!-- tab切换 -->
    <div class="tab-box">
      <div
        class="tab-item"
        :class="{'tab-active': curtTabIdx === index}"
        v-for="(tab, index) in tabs"
        :key="index"
        @click="tabToggle(index)"
      >{{ tab.name }}</div>
      <div class="tab-line" :style="{left: `${tabLeft}px`}"></div>
    </div>
    <!-- 详情 -->
    <div class="detail-box deep-img-w100" v-html="tabs[curtTabIdx] && tabs[curtTabIdx]['detail']"></div>
    <!-- 底部购买 -->
    <div class="btn-box">
      <div class="money">
        <p>
          合计：
          <span class="yuan">￥{{ totalPrice.yuan }}</span>
          <span class="fen">.{{ totalPrice.fen }}</span>
          <!-- <span v-if="goods.hasDiscount" class="del">原价: ¥{{ totalPrice.costPriceText }}</span> -->
        </p>
        <!-- <p v-if="totalPrice.savePrice" class="coupon">已使用优惠券，为您再优惠{{ totalPrice.savePrice }}元</p> -->
      </div>
      <div
        class="btn"
        :class="[goods.isSale === 2 ? 'cannot-buy' : 'can-but']"
        @click="preCreateOrder"
      >{{ goods.isSale === 2 ? '商品已下架' : '确认支付' }}</div>
    </div>
    <Loading v-show="showLoading" />

    <!-- 优惠券弹框 -->
    <CouponSelectList
      v-if="isShowCoupon"
      :showSelectCoupon="isShowCoupon"
      @cancle="closeCouponPopup"
      @confirm="setCurrentPopup"
    ></CouponSelectList>

    <CourseDialog
      content="微信授权"
      subContent="<p style='font-size: 16px; font-weight: bold; text-align: center;'>云鹊医申请以下权限：</p><p style='font-size: 14px; color: #999; text-align: center; padding-bottom: 10px;'>获得你的公开信息（头像，昵称等）</p>"
      cancleBtnText="取消"
      confirmBtnText="允许"
      needSubContent
      :isShowDialog="isShowDialog"
      @handlerAction="handlerAction"
    ></CourseDialog>

    <ShowCantBuyTips
      subContent="您所在的省份暂无法录入该继续医学教育项目学分，请勿购买。"
      cancleBtnText="我知道了"
      isSingle
      needSubContent
      :isShowDialog="isShowCantBuyTips"
      @handlerAction="isShowCantBuyTips=false"
    ></ShowCantBuyTips>
  </div>
</template>

<script>
import { Swipe, SwipeItem } from "vant";
import Loading from "@/components/common/common-loading";
import CourseDialog from "@/components/course/course-dialog";
import ShowCantBuyTips from "@/components/course/course-dialog";
import CouponSelectList from "@/components/coupon/component-select-list";

import CommonNavbar from "@/components/common/common-navbar";
import { wxConfig, chooseWXPay } from "@/utils/wxShare";
import {
  getAPPID,
  getTradeType,
  getWebPageUrl,
  isWeiXin,
  wxOauth,
  debounce,
  getHactiveUrl
} from "@/utils";
import { mapGetters, mapActions } from "vuex";
import { convertToYuan } from "@/utils";
import { setCookie, getCookie, delCookie } from "@/utils/index";
const isWechat = isWeiXin();
// wxConfig(location.href);

export default {
  components: {
    Swipe,
    SwipeItem,
    Loading,
    CourseDialog,
    CouponSelectList,
    CommonNavbar,
    ShowCantBuyTips
  },
  data() {
    return {
      token: "",
      isWeb: window.__isWeb,
      isAndroid: !window.__isAndroid,
      goods: {
        goodsName: "",
        salePriceNew: {},
        salePrice: {}
      }, // 商品信息
      totalPrice: {}, // 底部价格
      swiperList: [], // 轮播图
      swiperCurtIndex: 0, // 轮播当前下标
      goodsNum: 1, // 数量
      tabs: [],
      curtTabIdx: 0,
      tabW: 0, // tab的宽度
      showLoading: false,
      isShowDialog: false,
      isShowCoupon: false, //是否展示激活弹框,
      courseUrl: "",
      defaultCouponId: "",
      needSortAndSelect: true,
      orderId: "",
      bgColor: "#fff",
      navTitle: "商品详情",
      isFixNavbar: true,
      isShowNavbar: true,
      isBlack: true,
      // shareTitle: goods.goodsName,
      shareTitleInfo: "",
      isShowShare: true,
      isShowCantBuyTips: false,
      couponToken: ""
    };
  },
  computed: {
    ...mapGetters([
      "userInfo",
      "webUserInfo",
      "currentCoupon",
      "goodsInfo4Coupon",
      "selectCouponList"
    ]),
    wxInfo() {
      return this.$store.state.user.wxInfo;
    },
    wxCode() {
      return this.$store.state.user.wxCode;
    },
    tabLeft() {
      const num = this.curtTabIdx + 0.25 + 15 / 115;
      return this.tabW * num;
    }
  },

  watch: {
    webUserInfo: {
      handler(userInfo) {
        console.log("userInfo", userInfo);
        if (userInfo.id) {
          this.getGoodsInfo();
        }
      },
      deep: true
    }
  },

  created() {
    let _this = this;
    console.log("in goods detail new", 111111111);
    let href = location.href;
    this.shareUrl = href;
    this.projectId = this.$route.query.projectId;
    this.goodsId = this.$route.query.goodsId;
    this.courseUrl = this.$route.query.courseUrl || "";
    if(this.courseUrl) {
      sessionStorage.setItem("courseUrl", this.courseUrl);
    }
    this.couponToken = this.$route.query.couponToken || "";
    console.log('this.couponToken', this.couponToken);
    this.shareUrl = getWebPageUrl(
      `profexam/#/goods-detail?goodsId=${this.goodsId}`
    );
    if (href.indexOf("singlemessage") >= 0 || href.indexOf("wx_code") >= 0) {
      if (this.projectId) {
        this.shareUrl = getWebPageUrl(
          `profexam/#/goods-detail?goodsId=${this.goodsId}&projectId=${this.projectId}`
        );
      } else {
        this.shareUrl = getWebPageUrl(
          `profexam/#/goods-detail?goodsId=${this.goodsId}`
        );
      }
      location.replace(this.shareUrl);
    }
    localStorage.setItem("returnUrl", this.shareUrl);

    window.__getUserInfo4GD = function(param) {
      console.log("__getUserInfo4GD", param);
      _this.token = param.userToken;
      _this.setUserInfo(param);
      _this.getGoodsInfo();
    };

    window.__refresh = function() {
      _this.getUserInfo();
    };

    window.__WXpay = function(params) {
      _this.showLoading = false;
      _this.paycallback(params);
    };
  },

  mounted() {
    this.getTabW();
    console.log("this.isWeb ... isWechat - 1", this.isWeb, isWechat);
    // 数量加减
    this.curtGoodsNum = this.goodsNum;
    this.countTotalPrice = debounce(this.getTotalPrice, 300);
    // 记录参数，授权登录返回时重新赋值，在main.js
    sessionStorage.setItem(
      "goodsDetailParams",
      JSON.stringify(this.$route.query)
    );

    if (this.isWeb) {
      let { token, info } = this.$store.state.user;
      token =
        token ||
        this.couponToken ||
        localStorage.getItem("couponToken") ||
        getCookie("couponToken");
      this.token = token;
      console.log("token && !info.id", !info.id, token);

      // if (!token) {
      //   this.goLogin();
      //   return;
      // }

      if (token && !info.id) {
        // this.commonCheckToken(() => {
        // this.$store.dispatch('setToken', this.token);
        this.$store.dispatch("getUserInfo");
        // });
        // return;
      }
      // 从登陆页面过来时
      this.getGoodsInfo();
    } else {
      this.getUserInfo();
    }
  },
  methods: {
    ...mapActions([
      "setUserInfo",
      "setCurrentCoupon",
      "setGoodsInfo4Coupon",
      "setSelectCouponList"
    ]),

    // 优惠券选择按钮文案
    getCPText() {
      let text = "";
      // 有且选择了优惠券，则直接显示优惠券的优惠价格
      if (this.currentCoupon.couponId) {
        text = "-¥" + this.yuan(this.currentCoupon.discountAmount);
        // 如果没有选择优惠券
      } else {
        if (this.goodsInfo4Coupon.count) {
          text = this.goodsInfo4Coupon.count + "张优惠券";
        } else {
          text = "无优惠券";
        }
      }
      return text;
    },

    // 查询我的可用优惠券
    getCanUseCoupons(params) {
      const { goodsType, cardType, price } = params;
      this.GET(`trade/coupon/app/goodsCoupons`, {
        goodsType,
        cardType,
        amount: price
      }).then(res => {
        if (res.code == "000000") {
          params.count = (res.data || []).length;
          this.setGoodsInfo4Coupon(params);
          this.handlerCouponList(res.data || [], params.price);
          // 设置优惠券个数
        } else {
          params.count = 0;
          this.setGoodsInfo4Coupon(params);
          this.setCurrentCoupon({});
          this.setSelectCouponList([]);
        }
      });
    },

    // 处理数据，并且先排序，再将不可用的放在最后
    handlerCouponList(couponList, goodsPrice) {
      if (!couponList.length) return [];
      let newList = [],
        obj = {},
        firstCanCoupon = null,
        firstCanCouponIndex = 0,
        item = {},
        count = 0;
      for (let i = 0; i < couponList.length; i++) {
        item = couponList[i];
        // 要根据商品价格及券适用类型来计算
        item.disabled = !item.enableFlag;
        if (!item.disabled) {
          count++;
        }
        // 是否已经选择
        item.isChecked = !!item.checkFlag;
        if (!firstCanCoupon && item.isChecked) {
          firstCanCoupon = item;
          firstCanCouponIndex = i;
        }
        newList.push(item);
      }

      this.setCurrentCoupon(JSON.parse(JSON.stringify(firstCanCoupon)) || {});
      this.setSelectCouponList(newList);
      this.goodsInfo4Coupon.count = count;
      this.setGoodsInfo4Coupon(this.goodsInfo4Coupon);
    },

    // 判断是否可用
    isCanSelect(coupon, goodsPrice) {
      console.log(
        "isCanSelect",
        coupon.requiredTotalFee,
        goodsPrice,
        goodsPrice >= coupon.requiredTotalFee
      );
      return goodsPrice >= coupon.requiredTotalFee;
    },

    //获取用户信息
    getUserInfo() {
      rocNative.getUserInfo({
        __funcName: "__getUserInfo4GD"
      });
    },

    // 微信支付回调
    paycallback(params) {
      // 0成功 -1错误 -2 用户取消 -3 没有安装微信
      // let courseUrl = encodeURIComponent(this.courseUrl);
      // let courseUrl = sessionStorage.getItem("courseUrl");
      let courseUrl = encodeURIComponent(sessionStorage.getItem("courseUrl") || "");
      let url =
        getHactiveUrl() +
        `/message_push/#/order?orderBack=1&id=${this.orderId}&courseUrl=${courseUrl}`;
      if (params.result == -3) {
        this.$toast("您未安装微信，暂不能支付");
      } else if (params.result == -2) {
        this.POST(`/trade/center/order/pay_cancelled`, {
          orderId: this.orderId
        })
          .then(res => {
            this.jumpToOrder(url);
          })
          .catch(err => {});
      } else {
        this.jumpToOrder(url);
      }
    },

    // 跳转到指定页面
    jumpToOrder(pageUrl) {
      let paramList = [
        {
          key: "pageUrl",
          value: pageUrl,
          type: 4,
          seqNo: 1
        }
      ];
      rocNative.dispatchEventByModuleCode({
        modeCode: "M300",
        jsonString: paramList
      });
    },

    // 关闭优惠券弹框
    closeCouponPopup() {
      this.isShowCoupon = false;
    },

    // 显示优惠券弹框
    showCouponPopup() {
      this.commonCheckToken(() => {
        this.isShowCoupon = true;
      });
    },

    // 设置当前选中的优惠券
    setCurrentPopup(currentCoupon) {
      console.log("setCurrentPopup", currentCoupon);
      this.setCurrentCoupon(currentCoupon);
      this.getCPText();
      this.isShowCoupon = false;
      this.needSortAndSelect = false;
      // 要重新调用计算价格接口
      // this.countTotalPrice();
      this.getTotalPrice(currentCoupon);
    },

    // tab切换
    tabToggle(index) {
      this.curtTabIdx = index;
      this.$sendBuriedData({
        component_tag: `888#8880${index + 4}`
      });
    },

    // 获取商品信息
    getGoodsInfo() {
      if (!this.goodsId) {
        return;
      }
      // this.commonCheckToken(() => {
      this.GET(`trade/goods/goodInfoV3/${this.goodsId}`, {}).then(res => {
        if (res.code == "000000") {
          const goods = res.data;
          const tabs = [];
          let priceNew = goods.preferentialPrice || goods.costPrice;
          let price =
            goods.couponPrice || goods.preferentialPrice || goods.costPrice;
          this.goods = goods;
          this.defaultCouponId =
            (goods.couponDTO && goods.couponDTO.couponId) || "";
          // 获取到商品后，再获取优惠券
          this.getCanUseCoupons({
            goodsType: goods.goodsType,
            cardType: goods.cardType,
            price: priceNew,
            count: 0
          });
          goods.salePriceNew = this.formatPrice(priceNew);
          goods.salePrice = this.formatPrice(price);
          goods.costPriceText = (goods.costPrice / 100).toFixed(2);
          goods.hasDiscount = !!goods.preferentialPrice;
          // goods.hasDiscount = !!(goods.couponPrice || goods.preferentialPrice);
          let savePrice = 0;
          if (goods.couponPrice) {
            if (goods.preferentialPrice) {
              savePrice = (
                (goods.preferentialPrice - goods.couponPrice) /
                100
              ).toFixed(2);
            } else {
              savePrice = ((goods.costPrice - goods.couponPrice) / 100).toFixed(
                2
              );
            }
          }
          if (goods.goodsDescWhere) {
            tabs.push({ name: "使用范围", detail: goods.goodsDescWhere });
          }
          if (goods.goodsDescHow) {
            tabs.push({ name: "如何使用", detail: goods.goodsDescHow });
          }
          if (goods.goodsDescQaq) {
            tabs.push({ name: "常见问题", detail: goods.goodsDescQaq });
          }
          this.totalPrice = {
            ...goods.salePrice,
            preferentialPrice: goods.preferentialPrice,
            costPrice: goods.costPrice,
            costPriceText: goods.costPriceText,
            savePrice
          };
          this.swiperList = (res.data && res.data.imgList) || [];
          this.tabs = tabs;
          this.getTabW();
          let sharePrice = goods.preferentialPrice || goods.costPrice;
          let shareTitleInfo = "¥" + (sharePrice / 100).toFixed(2);
          shareTitleInfo += "\n" + (goods.shareContent || "");
          let shareUrl = getWebPageUrl(
            `profexam/#/goods-detail?goodsId=${this.goods.id}`
          );
          this.shareTitleInfo = shareTitleInfo;
          this.wechatShare(
            {
              link: shareUrl,
              title: goods.goodsName,
              friendtitle: goods.goodsName,
              desc: shareTitleInfo,
              imgUrl: "https://file.yunqueyi.com/logo.png"
            },
            () => {
              console.log("share success...");
            }
          );
        } else {
          this.$toast(res.message);
        }
      });
      // });
    },

    // 多件商品的价格
    // TODO，要多传优惠券id参数
    getTotalPrice(currentCoupon) {
      const num = this.curtGoodsNum;
      let couponId = 0;
      if (currentCoupon) {
        couponId = currentCoupon.couponId || -1;
      }
      this.GET(
        `trade/goods/getPrice/${this.goodsId}/${num}/${couponId}`,
        {}
      ).then(res => {
        if (res.code == "000000") {
          const {
            couponPrice,
            preferentialPrice,
            costPrice,
            savePrice
          } = res.data;
          let price = couponPrice || preferentialPrice || costPrice;
          this.totalPrice = {
            ...this.formatPrice(price),
            preferentialPrice,
            costPrice: costPrice,
            costPriceText: (costPrice / 100).toFixed(2),
            savePrice: savePrice ? (savePrice / 100).toFixed(2) : 0
          };
          this.goodsInfo4Coupon.price = preferentialPrice || costPrice;
          this.setGoodsInfo4Coupon(this.goodsInfo4Coupon);
          this.goodsNum = num;
          if (this.needSortAndSelect) {
            this.getCanUseCoupons(this.goodsInfo4Coupon);
            // this.handlerCouponList(this.selectCouponList, preferentialPrice || costPrice);
          }
          this.needSortAndSelect = true;
        } else if (res.code === "200006") {
          this.$store.dispatch("logout");
        }
      });
    },

    // 价格转成元、分
    formatPrice(price) {
      let yuan = (price / 100).toFixed(0);
      let fen = price % 100;
      fen = fen < 10 ? `0${fen}` : fen;
      return {
        yuan,
        fen
      };
    },

    // 获取切换标签宽度
    getTabW() {
      if (this.tabs.length === 0) {
        return;
      }
      this.$nextTick(() => {
        const { width } = this.$el
          .querySelector(".tab-item")
          .getBoundingClientRect();
        this.tabW = width;
      });
    },

    // 轮播切换
    onSwiperChange(index) {
      this.swiperCurtIndex = index;
    },

    // 数量增
    onPlus() {
      this.$sendBuriedData({
        component_tag: `888#88801`
      });
      this.commonCheckToken(() => {});

      let num = this.curtGoodsNum;
      if (
        this.goods.limitPurchase &&
        this.goods.limitPurchaseNum &&
        num >= this.goods.limitPurchaseNum
      ) {
        this.$toast("已达最大限购数量");
        return;
      }
      if (this.goods.goodsStocks && num >= this.goods.goodsStocks) {
        this.$toast("库存不足");
        return;
      }
      this.curtGoodsNum = num + 1;
      this.countTotalPrice();
    },

    // 数量减
    onReduce() {
      this.$sendBuriedData({
        component_tag: `888#88802`
      });
      this.commonCheckToken(() => {});
      let num = this.curtGoodsNum;
      if (num <= 1) {
        this.$toast("最少购买一张哦");
        return;
      }
      this.curtGoodsNum = num - 1;
      this.countTotalPrice();
    },

    handlerAction(type) {
      if (type === 2) {
        wxOauth();
      }
      this.isShowDialog = false;
    },

    // 判断是否能购买
    preCreateOrder() {
      this.commonCheckToken(() => {
        const { goodsType, cardType } = this.goods;
        console.log("goodsType, cardType", goodsType, cardType);
        // 只有一类卡才做相应判断
        if (goodsType == 2 && cardType == 1) {
          this.GET(
            `trade/goods/sale/checkProvince?goodsType=${goodsType}&cardType=${cardType}`,
            {}
          ).then(({ data }) => {
            if (data == 1) {
              this.createOrder();
            } else {
              this.isShowCantBuyTips = true;
            }
          });
        } else {
          this.createOrder();
        }
      });
    },

    // 创建订单
    createOrder() {
      this.$sendBuriedData({
        component_tag: `888#88803`
      });

      // 微信内先去授权
      if (isWechat && !this.wxInfo.openid) {
        this.isShowDialog = true;
        return;
      }

      // 避免多次支付
      if (this.showLoading) {
        return;
      }
      const { id, couponDTO, isSale } = this.goods;
      const { preferentialPrice, costPrice } = this.totalPrice;
      if (!id || isSale !== 1) {
        return;
      }

      // 重新使用优惠券
      let couponId = (this.currentCoupon && this.currentCoupon.couponId) || 0;
      const orderData = {
        couponId: couponId,
        // couponId: couponDTO ? couponDTO.couponId : 0,
        goodsId: id,
        goodsQuantity: this.goodsNum,
        orderSource: 3,
        preferentialPrice: this.goods.preferentialPrice,
        price: this.goods.costPrice
      };
      console.log("orderData...", orderData);
      this.showLoading = true;
      // this.POST("trade/center/order/createV2", orderData)
      this.POST("trade/center/order/createV4", orderData)
        .then(res => {
          if (res.code == "000000") {
            const orderId = res.data.orderId;
            this.orderId = res.data.orderId;
            // if (isWechat) {
            //   this.goWxPayInner(orderId);
            // } else {
            //   this.goWxPayOut(orderId);
            // }

            // 在站外，则调用站外支付
            console.log(
              "this.isWeb ... isWechat - 2 this.orderId",
              this.isWeb,
              isWechat,
              this.orderId
            );
            if (this.isWeb) {
              console.log("in web...");
              if (isWechat) {
                this.goWxPayInner(orderId);
              } else {
                this.goWxPayOut(orderId);
              }
            } else {
              console.log("not in web...");
              rocNative.WXpay({
                __funcName: "__WXpay",
                orderId: String(orderId)
              });
            }

            if (this.projectId) {
              this.createRelation(this.projectId, orderId);
            }
          } else {
            this.$toast(res.message);
            this.showLoading = false;
            if (res.code === "200006") {
              this.$store.dispatch("logout");
            }
          }
        })
        .catch(() => {
          this.showLoading = false;
        });
    },

    // 微信内支付
    goWxPayInner(orderId) {
      const data = {
        openId: this.wxInfo.openid,
        orderId,
        payChannel: 1,
        tradeType: getTradeType(),
        userId: this.$store.state.user.info.id
      };
      this.POST("trade/center/jsapi_prepay", data)
        .then(res => {
          if (res.code == "000000" && res.data) {
            // console.log('______prepay_____', res.data);
            const that = this;
            const payData = {
              ...res.data,
              appid: res.data.appId,
              timestamp: res.data.timeStamp,
              success: function() {
                let query = { orderId };
                if (that.projectId) {
                  query.projectId = that.projectId;
                }
                that.$router.push({ path: "/prezult", query });
              },
              fail: function() {
                that.$toast("支付失败，请重试~");
              },
              cancel: function() {
                // that.$toast('支付取消~');
              },
              complete: function() {}
            };
            chooseWXPay(payData);
          } else {
            this.$toast(res.message);
          }
          this.showLoading = false;
        })
        .catch(() => {
          this.showLoading = false;
        });
    },

    // 站外微信支付
    goWxPayOut(orderId) {
      const data = {
        // openId: getAPPID(),
        orderId,
        payChannel: 1,
        tradeType: getTradeType()
      };
      this.POST("trade/center/mweb_prepay", data)
        .then(res => {
          if (res.code == "000000") {
            if (res.data) {
              let redirectUrl = this.getRedirectUrl(orderId);
              let jumpLink =
                res.data + "&redirect_url=" + encodeURIComponent(redirectUrl);
              window.location.href = jumpLink;
            }
          } else {
            this.$toast(res.message || "暂时不能支付");
          }
          this.showLoading = false;
        })
        .catch(() => {
          this.showLoading = false;
        });
    },

    // 设置微信重定向URL
    getRedirectUrl(orderId) {
      let path = `profexam/#/prezult?orderId=${orderId}`;
      if (this.projectId) {
        path += `&projectId=${this.projectId}`;
      }
      return getWebPageUrl(path);
    },

    // 绑定项目和订单的关系(idType=1)，这里只判断cardType是否为4
    createRelation(projectId, orderId) {
      let idType = 1,
        channel = 1;
      if (this.goods.cardType == 4) {
        idType = 2;
      }
      if (this.isWeb) {
        channel = 3;
      }
      let cardType = this.goods.cardType;
      this.POST(
        `cme/projectCard/correlation/${idType}/${projectId}/${orderId}`,
        {
          channel: channel
        }
      ).then(res => {
        if (res.code == "000000") {
          //
        } else {
          this.$toast(res.message);
        }
      });
    },

    // 显示元
    yuan(fen) {
      return convertToYuan(fen);
    }
  },
  beforeDestroy() {
    sessionStorage.removeItem("courseUrl");
  },
};
</script>

<style lang="less" scoped>
.goods-details-wrapper {
  padding-top: 80px;
  .swiper-box {
    position: relative;
    .indicator {
      position: absolute;
      right: 10px;
      bottom: 10px;
      width: 40px;
      height: 22px;
      line-height: 22px;
      color: #fff;
      font-size: 12px;
      text-align: center;
      padding: 0 8px;
      border-radius: 11px;
      background: rgba(0, 0, 0, 0.2);
    }
    .img {
      display: block;
      width: 100%;
    }
  }
  .border-line {
    padding: 20px 15px;
    border-bottom: 6px solid #f8f9fa;
  }
  .info-box {
    .title {
      font-size: 18px;
      font-weight: bold;
      padding-bottom: 12px;
    }
    .price {
      display: flex;
      align-items: baseline;
      font-size: 12px;
    }
    .money {
      flex: 1;
      width: 100px;
    }
    .yuan {
      color: #fb5b52;
      font-size: 18px;
      font-weight: bold;
    }
    .fen {
      color: #fb5b52;
      font-weight: bold;
    }
    .del {
      color: #979899;
      text-decoration: line-through;
      margin-left: 6px;
    }
    .bought {
      color: #979899;
    }
  }
  .buy-box {
    font-size: 14px;
    .flex {
      display: flex;
      align-items: center;
    }
    .name {
      flex: 1;
      width: 100px;
      font-weight: bold;
    }
    .buy-num {
      display: flex;
    }
    .reduce {
      position: relative;
      width: 22px;
      height: 22px;
      background: url("~@/images/reduce.png") no-repeat center center;
      background-size: 20px auto;
    }
    .num {
      width: 30px;
      height: 22px;
      line-height: 22px;
      text-align: center;
    }
    .plus {
      position: relative;
      width: 22px;
      height: 22px;
      background: url("~@/images/plus.png") no-repeat center center;
      background-size: 20px auto;
    }
    .buy-way {
      margin-top: 25px;
      span {
        color: #979899;
        font-size: 12px;
        margin-left: 6px;
      }
    }
    .way {
      line-height: 18px;
      padding-left: 28px;
      background: url("~@/images/wxpay.png") no-repeat left center;
      background-size: 18px auto;
    }
    .coupon-select {
      // line-height: 12px;
      padding-right: 15px;
      background: url("~@/images/coupon/arrow-right.png") no-repeat right center;
      background-size: 12px auto;
      transform: rotate(0deg);
      // &.top {
      //   position: relative;
      //   top: -1px;
      // }
    }
  }
  .tab-box {
    display: flex;
    position: relative;
    height: 50px;
    padding: 0 15px;
    background-color: #fff;
    &::after {
      position: absolute;
      content: "";
      left: 0;
      bottom: 0;
      width: 200%;
      height: 0;
      border-bottom: 1px solid #f0f1f2;
      transform: scale(0.5);
      transform-origin: left center;
    }
  }
  .tab-item {
    color: #979899;
    font-size: 15px;
    width: 115px;
    height: 50px;
    line-height: 50px;
  }
  .tab-active {
    color: #373839;
    font-weight: bold;
  }
  .tab-line {
    position: absolute;
    left: 30px;
    bottom: 3px;
    width: 10px;
    height: 3px;
    background-color: #449284;
    border-radius: 1.5px;
    transform: translate3d(-5px, 0, 0);
    transition: left 0.3s;
  }
  .detail-box {
    font-size: 14px;
    text-align: justify;
    padding: 15px 15px 75px;
  }
  .btn-box {
    display: flex;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 60px;
    padding: 10px 15px;
    box-shadow: 0 -4px 4px rgba(240, 240, 240, 0.5);
    background-color: #fff;
    .money {
      flex: 1;
      width: 100px;
      font-size: 14px;
    }
    .yuan {
      color: #fb5b52;
      font-size: 18px;
      font-weight: bold;
    }
    .fen {
      font-size: 12px;
      color: #fb5b52;
      font-weight: bold;
    }
    .del {
      color: #979899;
      font-size: 12px;
      text-decoration: line-through;
      margin-left: 6px;
    }
    .coupon {
      color: #979899;
      font-size: 12px;
    }
    .btn {
      width: 125px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      font-size: 16px;
      font-weight: bold;
      border-radius: 20px;
    }
    .can-but {
      background-image: linear-gradient(90deg, #ffa65f, #ff7a4b);
    }
    .cannot-buy {
      background-color: #c7c8c9;
    }
  }
  .coupon-pc {
    font-weight: 400;
    color: #fb5b52;
  }
  &.no-pt {
    padding-top: 0px;
  }
  .no-coupon {
    color: #979899;
  }
}
</style>
