<template>
  <BaseContainer class="initiate-group">
    <NavBar title="拼团详情" />
    <template v-if="info.pinkT">
      <view class="header acea-row row-middle">
        <view class="pictrue">
          <image :src="special.image" mode="aspectFit" />
        </view>
        <view class="text">
          <view class="line1">{{ special.title }}</view>
          <view style="margin-top: 13rpx; font-size: 0">
            <view class="money">
              ¥<text>{{ special.pink_money }}</text>
            </view>
            <view class="mark">{{ info.pinkT.people }}人拼</view>
          </view>
        </view>
        <view v-if="uid == pinkT.uid && pinkBool == 0" class="iconfont iconkaituanchenggong" style="color: #2c8eff">
        </view>
        <view v-else-if="pinkBool == 0" class="iconfont iconzhengzaipintuan"></view>
        <view v-else-if="pinkBool == 1" class="iconfont iconpintuanchenggong" style="color: #2c8eff"></view>
        <view v-else class="iconfont iconpintuanshibai"></view>
      </view>
      <view class="detail-section">
        <view class="count-wrap">
          <view class="text-wrap">
            剩余
            <view class="time-wrap">
              <text class="number">{{ hour }}</text>: <text class="number">{{ minute }}</text>:
              <text class="number">{{ second }}</text>
            </view>
            结束
          </view>
        </view>
        <view class="prompt blue" v-if="!pinkBool">
          拼团中，还差{{ info.count }}人拼团成功
        </view>
        <view class="prompt blue" v-else-if="pinkBool == 1">恭喜您拼团成功</view>
        <view class="prompt" v-else-if="pinkBool > 1 && pinkBool < 4">
          还差{{ info.count }}人，拼团失败
        </view>
        <view class="prompt" v-else-if="pinkBool == 6">拼团人数已满</view>
        <view class="group-wrap">
          <view class="item">
            <image mode="aspectFit" class="king" :src="getImgPath('/wap/first/zsff/images/king.png')" />
            <image mode="aspectFill" class="img" :src="pinkT.avatar" />
          </view>
          <view v-for="item in pinkAll" class="item">
            <image mode="aspectFill" class="img" :src="item.avatar" />
          </view>
          <view class="item" v-for="(x, key) of info.count" :key="key">
            <image mode="aspectFit" style="border: none" class="img"
              :src="getImgPath('/wap/first/zsff/images/symbol.png')" />
          </view>
        </view>
        <view class="handle-section">
          <view class="button flex flex-center" v-if="is_help == 0 && !pinkBool" @click="createPoster">
            邀请好友参团
          </view>
          <view class="button flex flex-center" v-if="is_help == 1 && !pinkBool" @click="OpenPay(3, 1)">
            我要参团
          </view>
          <view class="button flex flex-center" v-else-if="is_help == 0 && pinkBool == 1" @click="OpenPay(5, 0)">
            去学习
          </view>
          <view class="button flex flex-center" v-else-if="
            is_help == 0 && pinkBool > 1 && pinkBool < 4 && uid == pinkT.uid
          " @click="OpenPay(3, 0)">
            重新开团
          </view>
        </view>
      </view>
      <!-- 支付弹窗 -->
      <PayDialog :open.sync="payDialogOpen" :money="Number(money)" :special_id="special.id" :now_money="Number(now_money)"
        :link_pay_uid="link_pay_uid" :pay_type_num="pay_type_num" :pink-id="Number(pink_id)" :is-wechat="isWechat"
        :is-alipay="Boolean(is_alipay)" :is-balance="Boolean(is_yue)" :template-id="templateId"
        :wxpay-h5="Boolean(wxpayH5)" @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" />
    </template>
  </BaseContainer>
</template>

<script>
import {
  delSpecialOrder,
  getSpecialPinkInfo,
  getSpecialTemplateIds,
  aliPayApp,
  aliPayWap,
  SpecialPink
} from "@/api/special";
import posterMixin from "@/mixins/poster";
import { getUserInfo } from "@/api/auth";
import PayDialog from "@/components/PayDialog/index.vue";

export default {
  mixins: [posterMixin],
  components: {
    PayDialog,
  },
  data() {
    return {
      uid: 0,
      info: {},
      is_help: 0,
      pink_id: 0,
      special: {},
      pinkT: {},
      pinkBool: 0,
      pinkAll: [],
      datatime: 0,
      hour: "00",
      minute: "00",
      second: "00",
      shares: false,
      wechat_qrcode: "",
      is_code: true,
      payDialogOpen: false, // 是否显示支付弹窗
      money: 0,
      is_alipay: 0, //支付宝是否开启
      is_yue: 0, //余额是否开启
      now_money: 0, //余额
      link_pay_uid: 0,
      pay_type_num: 3,
      templateId: "",
      wxpayH5: 0,
      loginShow: false,
      siteName: "",
      isWechat: false,
      userInfo: {},
      site_url: "",
      orderId: null,
      special_id: null,
      is_light: 0,
      callback_url: "",
      poster_image: '',
      qrcodeText: "",
      isPosterCanvasVisable: false,
      isQrcodeCanvasVisable: false,
      oid: 0,
      url:'pages/special/pink'
    };
  },
  onLoad({ orderId, pink_id, special_id, is_help, oid, scene }) {
    const parmData = this.$util.mergeLaunchParams(scene)
    this.oid = oid ?? 0;
    if (!this.oid && parmData) {
      SpecialPink(parmData.oid).then(res => {
        this.orderId = res.data.order_id;
        this.pink_id = parmData.pid;
        this.is_help = is_help ?? 1
        this.special_id = parmData.id;
        this.getData().then(this.subscribeTemplate);
      })
    } else {
      this.orderId = orderId;
      this.pink_id = pink_id;
      this.is_help = is_help ?? 0
      this.special_id = special_id;
      this.getData().then(this.subscribeTemplate);
    }

    this.show_time();
    this.getUser()

  },
  onShow() {
    if (this.isOpenWeixing && this.orderId) {
      this.$util.wxh5PayIsSuccess(this.orderId, 1, this)
      this.isOpenWeixing = false
    }
  },
  methods: {

    getUser() {
      getUserInfo().then(({ data }) => {
        this.userInfo = data;
      });
    },
    async getData() {
      uni.showLoading({ mask: true });
      try {
        const { data } = await getSpecialPinkInfo(this.orderId, this.pink_id, this.special_id, this.is_help);
        uni.hideLoading();
        const {
          special_id,
          site_url,
          info,
          pink_id,
          is_help,
          is_light,
          is_alipay,
          is_yue,
          now_money,
          wxpayH5,
          siteName,
          uid,
          callback_url,
          poster_image
        } = data;
        Object.assign(this, {
          special_id,
          site_url,
          info,
          pink_id,
          is_help,
          is_light,
          special: info.special,
          pinkT: info.pinkT,
          pinkBool: info.pinkBool || 0,
          pinkAll: info.pinkAll,
          datatime: info.pinkT.stop_time,
          poster_image: info.special.image,
          is_alipay,
          is_yue,
          now_money,
          wxpayH5,
          siteName,
          uid,
          callback_url,
          isOpenWeixing: false
        });
      } catch (err) {
        uni.hideLoading();
        this.$util.showMsg(err.msg);
      }
    },
    subscribeTemplate() {
      getSpecialTemplateIds(this.pay_type_num, this.special.id).then(
        ({ msg }) => {
          this.templateId = msg;
        }
      );
    },
    getTashUrl(id, isAtn) {
      let path = `/pages/special/details?id=${id}`;
      if (isAtn) {
        path += "#tash";
      }
      return path;
    },
    createPoster() {
      this.createSharePoster("pink", {
        id: this.special.id,
        uid: this.userInfo.uid,
        url: 'pages/special/pink',
        pid: this.pinkT.id,
        oid: this.oid,
        orderId:this.orderId
      });
      // uni.navigateTo({
      //   url: `/pages/special/poster_show?special_id=${this.special_id}&pinkId=${this.pinkT.id}`,
      // });
    },
    show_time() {
      let timer;
      const nowTime = () => {
        var intDiff = this.datatime - Date.parse(new Date()) / 1000;
        var days = 0,
          hour = 0,
          minute = 0,
          second = 0;
        if (intDiff > 0) {
          hour = Math.floor(intDiff / (60 * 60)) - days * 24;
          minute = Math.floor(intDiff / 60) - hour * 60;
          second = Math.floor(intDiff) - hour * 60 * 60 - minute * 60;
          if (hour <= 9) hour = "0" + hour;
          if (minute <= 9) minute = "0" + minute;
          if (second <= 9) second = "0" + second;
          this.hour = hour;
          this.minute = minute;
          this.second = second;
        } else {
          this.hour = "00";
          this.minute = "00";
          this.second = "00";
          clearInterval(timer);
        }
      };
      nowTime();
      timer = setInterval(nowTime, 1000);
    },
    //所有插件回调处理事件
    changeVal(opt) {
      if (typeof opt != "object") opt = {};
      var action = opt.action || "";
      var value = opt.value || "";
      this[action] && this[action](value);
    },
    //打开支付插件,并检测登录状态,没有登录,打开登录插件
    OpenPay(is_pink, n) {
      this.pay_type_num = is_pink;

      this.$util.checkLogin(() => {
        switch (is_pink) {
          case 3:
            this.money = this.special.pink_money;
            this.payDialogOpen = true;
            if (!n) {
              this.pink_id = 0;
            }
            break;
          case 5:
            if (this.is_light) {
              uni.navigateTo({
                url: `/pages/special/single_details?id=${this.special_id}`,
              });
            } else {
              uni.navigateTo({
                url: `/pages/special/details?id=${this.special_id}`,
              });
            }
            break;
        }
      });
    },
    extendOrder(msg) {
      if (typeof msg === "object") {
        if (msg.errMsg === "chooseWXPay:cancel") {
          msg = "微信支付取消";
        } else {
          msg = "支付失败";
        }
      } else {
        msg = "支付失败";;
      }

      this.$util.showMsg(msg);
    },
    successOrder(msg) {
      this.$util.showMsg(msg ? msg : "支付成功");
      setTimeout(() => {
        this.getData();
      }, 500);
    },
    pay_order(data) {
      this.orderId = data.data.result.orderId || "";
      switch (data.data.status) {
        case "PAY_ERROR":
        case "ORDER_EXIST":
          this.payDialogOpen = false;
          this.$util.showMsg(data.msg);
          break;
        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_ROUTINE_PAY":
          this.$util.wechatRoutinePay(data.data.result.jsConfig, this);
          break;
        case "WECHAT_H5_PAY":
          this.payDialogOpen = false;
          this.$util.wechatH5Pay(data.data.result.jsConfig, this);
          break;
        case "SUCCESS":
          this.successOrder(data.msg);
          break;
        case "ZHIFUBAO_PAY":
          this.aliPay(data.data.result, "special")
          break;
      }
    },
    aliPay(msn, type) {
      this.$util.aliPay(msn, type, this)
    },
    wechatPay(config) {
      this.$util.weixinpay(config, this)
    },
    loginClose() {
      this.loginShow = false;
    },
    handleQrcodeCreateSuccess(path) {
      this.x_cb(path ?? 'pages/special/pink');
    },
    renderProductPoster(target,
      id,
      bgPath,
      codePath,
      WIDTH = 600,
      HEIGHT = 723,
      site_name = "知识付费"
    ) {
      return new Promise((resolve, reject) => {
        let context = uni.createCanvasContext(id, target);
        let money = "￥" + this.special.money,
          i = Math.ceil(this.special.title.length / 18),
          pinkWidth;

        context.fillStyle = "#FFFFFF";
        context.fillRect(0, 0, 600, 723);

        context.fillStyle = "#F7F7F7";
        context.fillRect(0, 553, 600, 170);

        context.drawImage(bgPath, 30, 30, 540, 304);
        context.drawImage(codePath, 64, 576, 126, 126);
        context.save();

        context.font = "bold 26px sans-serif";
        context.fillStyle = "#FF6B00";
        context.fillText("￥", 35, 406);

        context.font = "bold 42px sans-serif";
        context.fillText(this.special.pink_money, 56, 406);

        pinkWidth = Math.ceil(
          context.measureText(this.special.pink_money).width
        );

        context.font = "26px sans-serif";
        context.fillStyle = "#999999";
        context.fillText(money, pinkWidth + 65, 406);

        context.moveTo(pinkWidth + 65, 397);
        context.lineTo(
          Math.ceil(context.measureText(money).width) + pinkWidth + 65,
          397
        );
        context.stroke();

        context.font = "22px sans-serif";
        context.fillText("邀您参与拼团课程", 226, 622);
        context.fillText("长按识别参与拼团", 226, 662);

        context.font = "28px sans-serif";
        context.fillStyle = "#282828";

        for (; i--;) {
          context.fillText(
            this.special.title.substr(i * 18, 18),
            35,
            i * 41 + 472
          );
        }

        context.draw(true, () => {
          uni.canvasToTempFilePath(
            {
              canvasId: id,
              fileType: "png",
              destWidth: WIDTH,
              destHeight: HEIGHT,
              success: (res) => {
                resolve(res.tempFilePath);
                context = null;
              },
              fail: (err) => {
                reject(err.errMsg);
                context = null;
              },
            },
            target
          );
        });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.detail-section {
  padding-top: 36rpx;
  border-top: 20rpx solid #f5f5f5;
}

.detail-section .count-wrap {
  margin-bottom: 31rpx;
  font-size: 0;
  text-align: center;
}

.detail-section .count-wrap .text-wrap {
  position: relative;
  display: inline-block;
  padding-right: 50rpx;
  padding-left: 50rpx;
  font-size: 28rpx;
  line-height: 40rpx;
  color: #282828;
}

.detail-section .count-wrap .text-wrap::before {
  content: "";
  position: absolute;
  top: 50%;
  right: 100%;
  width: 110rpx;
  height: 1px;
  background-color: #dddddd;
}

.detail-section .count-wrap .text-wrap::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 100%;
  width: 110rpx;
  height: 1px;
  background-color: #dddddd;
}

.detail-section .count-wrap .time-wrap {
  display: inline-block;
  margin-right: 12rpx;
  margin-left: 12rpx;
  font-weight: bold;
  line-height: 42rpx;
  color: #ff6b00;
}

.detail-section .count-wrap .number {
  display: inline-block;
  width: 42rpx;
  height: 42rpx;
  border-radius: 3rpx;
  margin-right: 6rpx;
  margin-left: 6rpx;
  background-color: #fff5e1;
}

.detail-section .prompt {
  font-weight: bold;
  font-size: 30rpx;
  line-height: 42rpx;
  text-align: center;
  color: #999999;
}

.detail-section .prompt.blue {
  color: #2c8eff;
}

.detail-section .group-wrap {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  padding: 49rpx 64rpx 24rpx;
  font-size: 0;
}

.detail-section .group-wrap .item {
  flex-shrink: 0;
  position: relative;
  padding: 15rpx;
  border-radius: 50%;
}

.detail-section .group-wrap .img {
  display: block;
  width: 94rpx;
  height: 94rpx;
  border: 2rpx solid #cccccc;
  border-radius: 50%;
  box-sizing: border-box;
  pointer-events: none;
}

.detail-section .group-wrap .king {
  position: absolute;
  top: 1px;
  left: 1px;
  z-index: -1;
  width: 51rpx;
  height: 37rpx;
  transform: rotate(-20deg);
}

.detail-section .handle-section {
  padding-right: 64rpx;
  padding-left: 64rpx;
  text-align: center;
}

.detail-section .handle-section .button {
  //   display: block;
  width: 100%;
  height: 86rpx;
  border-radius: 43rpx;
  background-color: #2c8eff;
  font-size: 30rpx;
  color: #ffffff;
}

.detail-section .handle-section .link {
  display: inline-block;
  padding-left: 35rpx;
  margin-top: 25rpx;
  background: url("@/static/icon/close2.png") left center/26rpx 26rpx no-repeat;
  vertical-align: middle;
  font-size: 24rpx;
  line-height: 33rpx;
  color: #282828;
}

.prompt-share {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.initiate-group .header .iconfont {
  margin-left: 14rpx;
  font-size: 102rpx;
  line-height: normal;
  color: #999999;
}

.poster-canvas {
  width: 600px;
  height: 723px;
}
</style>