<template>
  <likeGood :page-type="4">
    <view class="card">
      <view class="info">
        <image class="info__image" src="https://img.lkbang.net/paying.eu72a2f.png" />
        <view class="info__desc">
          <text v-if="time" class="info__text">（{{ time }}s）支付中...</text>
          <text v-else class="info__text">系统处理中!</text>
        </view>
      </view>
      <view class="tips">
        <text>稍后返回支付结果，请留心查看！</text>
      </view>
      <view class="actions">
        <button
          class="actions__back"
          plain="true"
          hover-class="none"
          type="primary"
          @click="goHome"
        >
          返回首页
        </button>
        <button
          class="actions__order"
          plain="true"
          hover-class="none"
          type="primary"
          @click="setSubMsg"
        >
          查看订单
        </button>
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <view v-if="showDivert && guideUrl" class="priv-divert" @click="navToDivert">
      <image class="priv-divert-img" :src="guideUrl" mode="widthFix" />
    </view>
    <!-- #endif -->
  </likeGood>
</template>
<script>
import { guideStream } from "@/api/pay.api.js";
import likeGood from "@/components/likeGood";
import { queryPayStatus } from "@/api/pay.api.js";
import { saTrackEvent } from "@/utils/sa";
import { getVaildSubTmplIds } from "@/api/home.api";
import cfg from "@/config/index";
import { h5Mixin } from "@/utils/h5Mixin";
import { getVaildTmplIds, submitSubcribeInfo, getAcceptList } from "@/utils/subscribe";
import { redirectLocation, isHundredGroup } from "./payRedirect.js";
const tmplIds = [
  cfg.SUB_MSG_LIST.SELLER_SHIP,
  cfg.SUB_MSG_LIST.ORDER_RECEIPT,
  cfg.SUB_MSG_LIST.COUPON_RECEIPT
];
let vaildTmplIds = [];
export default {
  components: {
    likeGood
  },
  mixins: [h5Mixin()],
  data() {
    return {
      orderNo: null,
      timer: null,
      time: 10,
      init: false,
      amount: 0,
      freeAmount: 0,
      payType: 0,
      showDivert: false,
      guideUrl: "",
      jumpUrl: ""
    };
  },
  async onLoad({ amount, orderNo, freeAmount, payType }) {
    this.showDivert = uni.getStorageSync("tenantId") == 560761 ? true : false; // 羊小咩租户展示私域导流入口
    this.amount = amount;
    this.freeAmount = freeAmount;
    this.payType = payType;
    this.orderNo = orderNo;
    this.init = true;
    this.loop();

    // #ifdef MP-WEIXIN
    const [data, err] = await guideStream({
      payType: payType || 1,
      paySuccess: false,
      orderNo: orderNo
    });
    if (!err) {
      const [guideItem] = (data?.guideList || []).filter(item => item.type === 1);
      if (guideItem) {
        this.guideUrl = guideItem.image;
        this.jumpUrl = guideItem.jumpUrl || "";
      }
    }
    vaildTmplIds = await getVaildSubTmplIds(tmplIds);
    // #endif
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    navToDivert() {
      const activityType = this.jumpUrl.split("activityType=")[1];
      uni.navigateTo({
        url: `/pages/activity/divertPrivDomain?activityType=${activityType}`
      });
    },
    goHome() {
      uni.switchTab({
        url: "/pages/index/index"
      });
    },
    setSubMsg() {
      if (!this.$config("yxm")) {
        this.goOrderDetail();
        return;
      }
      // #ifdef MP-WEIXIN
      // 非羊小咩不触发订阅消息
      if (!vaildTmplIds.length) return;
      wx.requestSubscribeMessage({
        tmplIds: vaildTmplIds,
        success: res => {
          this.submitInfo(res);
          this.goOrderDetail();
          const vaildIds = getVaildTmplIds(res);
          saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
            trigger_node: "点击支付成功页查看订单",
            check_content: vaildIds,
            buttons_name: "允许"
          });
        },
        fail: err => {
          console.error("requestSubscribeMessage", err);
          this.goOrderDetail();
          saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
            trigger_node: "点击支付成功页查看订单",
            check_content: "商家发货通知,优惠券到账通知,优惠券过期通知",
            buttons_name: "取消"
          });
        }
      });
      // #endif
      /* #ifndef MP-WEIXIN */
      this.goOrderDetail();
      saTrackEvent("MINI_MessageSubscriptionPopupBtnClick", {
        trigger_node: "点击支付成功页查看订单",
        check_content: [],
        buttons_name: "允许"
      });
      /* #endif */
    },
    submitInfo(res) {
      const acceptList = getAcceptList(res);
      submitSubcribeInfo(acceptList);
    },
    goOrderDetail() {
      saTrackEvent("PD_YXMMAEC_UserClickCashierCheckOrderBtn", {
        order_id: this.orderNo
      });
      uni.reportAnalytics("c_cashiercheckorderbtn", {
        order_id: this.orderNo
      });
      this.isGotoGroup();
    },
    loop() {
      this.query();
      this.timer = setInterval(() => {
        this.time -= 1;
        if (this.time % 2 === 0) {
          this.query();
        }
        if (this.time < 1) {
          clearInterval(this.timer);
        }
      }, 2000);
    },
    async isGotoGroup() {
      /* #ifdef MP-WEIXIN */
      if (await isHundredGroup(this.orderNo)) {
        const url = `${cfg.groupBuyHost}/orderList/0?vccToken={token}`;
        uni.redirectTo({
          url: `/pages/groupbuy/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
        return;
      }
      /* #endif */
      uni.redirectTo({
        url: `/pages/order/orderList?state=0`
      });
    },
    async payResult(type, error) {
      // eslint-disable-next-line prettier/prettier
      if (await redirectLocation(this.orderNo, error, this.amount, this.freeAmount, this.payType)) return;
      uni.redirectTo({
        url: `/pages/pay/pay${type}?amount=${this.amount}&reason=${error}&orderNo=${this.orderNo}&freeAmount=${this.freeAmount}&payType=${this.payType}`
      });
    },
    async query() {
      const [data, error] = await queryPayStatus({ orderNo: this.orderNo });
      if (error) {
        this.payResult("Fail", error.msg);
        return;
      }
      if (+data?.payStatus === 3) {
        this.payResult("Success");
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.card {
  margin: $uni-spacing-col-md;
  background-color: white;
  border-radius: $uni-border-radius-lg;
  padding: 56rpx $uni-spacing-row-base $uni-spacing-row-base $uni-spacing-row-base;

  .info {
    display: flex;
    justify-content: center;
    align-items: center;

    &__image {
      width: 100px;
      height: 100px;
    }

    &__text {
      margin-left: $uni-spacing-row-lg;
      font-size: $font-lg;
    }

    &__desc {
      display: flex;
      flex-direction: column;
    }

    &__money {
      margin-top: $uni-spacing-col-base;
    }
    &__free {
      color: $font-color-light;
      font-size: $font-md;
      margin-top: $uni-spacing-col-base;
    }
  }

  .tips {
    margin-top: $uni-spacing-col-lg;
    text-align: center;
    font-size: $font-sm;
    color: $font-color-light;
  }

  .actions {
    display: flex;
    flex-direction: row;
    margin-top: 42rpx;

    &__back {
      border: 1px solid $uni-text-color-grey;
      color: $uni-text-color-grey;
    }

    &__order {
      margin-left: $uni-spacing-row-base;
      color: #ec1500;
      border: 1px solid #ec1500;
    }

    button {
      flex: 1;
      border-radius: $uni-border-radius-xl;
      font-size: $line-height-md;
    }
  }
}
.priv-divert {
  padding: 0 20rpx;
  margin-bottom: 10rpx;
  &-img {
    border-radius: 16rpx;
    overflow: hidden;
    width: 100%;
  }
}
</style>
