<template>
  <div>
    <div v-if="isSuccess" class="card">
      <div class="info">
        <cr-image
          width="100px"
          height="100px"
          class="info__image"
          src="https://img.lkbang.net/xcx/pay-success.png"
        />
        <div class="info__desc">
          <p class="info__text">订单支付成功!</p>
          <p v-if="money" class="info__text info__money">实付¥{{ money }}</p>
          <p v-if="freeAmount > 0" class="info__text info__free">已优惠¥{{ freeAmount }}</p>
        </div>
      </div>
      <p class="tips">您可在“我的-我的订单”中查看详情</p>
      <div
        v-if="eventPointInfo"
        class="card-growth-box"
        :style="`background-image: url(${eventPointInfo.icon});`"
      >
        <div>{{ eventPointInfo.text }}</div>
        <div>
          <span class="card-growth-box__value">+{{ eventPointInfo.eventPoint }}</span>
          <span>成长值</span>
        </div>
      </div>
      <div class="actions">
        <cr-button shape="circle" :plain="true" @click="jumpPage(buttonInfo.leftButton)">{{
          (buttonInfo.leftButton && buttonInfo.leftButton.name) || '返回首页'
        }}</cr-button>
        <cr-button
          shape="circle"
          :plain="true"
          type="primary"
          @click="jumpPage(buttonInfo.rightButton)"
        >
          {{ (buttonInfo.rightButton && buttonInfo.rightButton.name) || '查看订单' }}
        </cr-button>
      </div>
    </div>
    <div v-else class="card">
      <div class="info">
        <cr-image
          width="100px"
          height="100px"
          class="info__image"
          src="https://img.lkbang.net/xcx/pay-fail.png"
        />
        <p class="info__text">订单支付失败!</p>
      </div>
      <p class="tips">
        {{ reason }}
      </p>
      <cr-button type="primary" shape="circle" class="info_button" @click="goPage(0)">
        重新支付
      </cr-button>
    </div>
    <div v-if="isSuccess && couponList.length" class="coupon-box">
      <p class="coupon-tip">本单已享以下权益</p>
      <div class="coupon-wrap">
        <CouponCard
          v-for="coupon in couponList"
          :key="coupon.id"
          :value="coupon"
          class="coupon-item"
          @click="goViewCouponDetail"
        />
      </div>
    </div>
    <cr-popup v-model="showGiftCardContext" class="giftCardModalContainer">
      <div class="container">
        <div class="title">恭喜您获得了一张礼品卡</div>
        <div class="content">
          <div class="tag">礼品卡</div>
          <div v-if="cardInfo && cardInfo.denomination" class="price">
            <span>{{ +cardInfo.denomination }}</span>
          </div>
          <div v-if="cardInfo && cardInfo.limitDesc" class="giftcard-desc">
            <p>{{ cardInfo.limitDesc || '礼品卡' }}</p>
            <p v-if="cardInfo && cardInfo.cardValidPeriod">
              有效期至{{ cardInfo.cardValidPeriod }}
            </p>
          </div>
          <div class="buttonArea">
            <button class="buttonArea-btn" @click.stop="toGiftCard">立即查看</button>
          </div>
        </div>
        <div class="desc">
          礼品卡已放入您的账户中，点击“<a @click.stop="toGiftCard">礼品卡</a>”即可查看
        </div>
      </div>
      <cr-icon color="#ffffff" type="close" size="36px" @click="showGiftCardContext = false" />
    </cr-popup>
    <div class="feedbox">
      <div class="feedbox--img">
        <cr-image
          src="https://img.lkbang.net/icon-recommend.465d832f185840eaa.465d832f.png"
          height="29px"
          fit="contain"
        />
      </div>
      <cr-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        offset="100"
        @load="getGoodsFeed"
      >
        <GoodsFeed :goods-list="goodsList" :show-header="false" />
      </cr-list>
    </div>
  </div>
</template>
<script>
import cookies from '@/service/cookieStorage.service';
import CouponCard from './components/CouponCard.vue';
import GoodsFeed from '@/components/goodsCard.vue';
import { getResultInfo, getPayResultBtn, getGoodsList } from '@/api/pay.api';
import localStorage from '@/service/localStorage.service';
import { sStorage } from '@/service/sessionStorage.service';
import { smTrackEvent } from '@/service/shumei.service';
import { goUrlExtends } from './extends';
export default {
  components: {
    GoodsFeed,
    CouponCard
  },
  extends: goUrlExtends,
  data() {
    return {
      money: '00.00',
      orderNo: null,
      isSuccess: false,
      freeAmount: 0,
      payStatus: '',
      couponList: [],
      goodsList: [],
      payStatusName: '',
      payMethodName: '',
      payTrackInfo: {},
      skuID: '',
      cardInfo: null,
      eventPointInfo: null,
      showGiftCardContext: false,
      buttonInfo: {},
      loading: false,
      finished: false,
      pageNo: 0,
      sceneSource: 0
    };
  },
  created() {
    localStorage.remove('inPay');
    const { orderNo, reason, payType } = this.$route.query;
    const { success, smStatus } = this.$route.meta;
    console.log('success :>> ', success);
    const amount = cookies.get('amount') || {};
    this.payTrackInfo = cookies.get('payTrackInfo') || {};
    this.skuID = String(cookies.get('skuID')) || '';
    this.money = amount.finalAmt;
    this.orderNo = orderNo?.split('?')[0];
    this.reason = reason || '';
    this.isSuccess = success || false;
    this.freeAmount = amount.freeAmount;
    this.payStatus = success ? '订单支付成功' : '订单支付失败';
    this.payStatusName = success ? '支付成功' : '支付失败';
    this.$track?.registeredEvents('h5_RechargeResultPageExposure', {
      pay_status: this.payStatus
    });
    this.$track?.registeredEvents('H5_2BPaymentPageExposure', {
      order_no: orderNo,
      pay_result: this.payStatus,
      vcc_state: this.payTrackInfo.vcc_state,
      pay_method: this.payTrackInfo.pay_method,
      pay_amount: amount.finalAmt
    });
    if (smStatus) {
      // 支付中无数美对应状态，仅支付成功和失败后进行上报
      smTrackEvent({
        eventId: 'finishOrder',
        orderId: orderNo,
        orderResult: smStatus,
        passThrough: {
          payErrorReason: reason || ''
        }
      });
    }
    if (success) {
      this.getResultInfos(payType);
      // this.queryGiftCardInfo(payType);

      // 获取订单来源的场景值
      const sceneSource = sStorage.getItem('sceneSource');
      console.log('sStorage.getItem(sceneSource) :>> ', sStorage.getItem('sceneSource'));
      if (sceneSource != null) {
        this.sceneSource = +sceneSource;
        this.getPayResultButton(sceneSource || 0);
      }
    }

    this.payMethod();
    this.getGoodsFeed();
  },
  methods: {
    payMethod() {
      const name = this.payTrackInfo.pay_method;
      switch (name) {
        case 1:
          this.payMethodName = '享花卡';
          break;
        case 2:
          this.payMethodName = '微信';
          break;
        case 3:
          this.payMethodName = '支付宝';
          break;
        default:
          '';
      }
    },
    goPage(type) {
      const name = type ? '查看订单' : '重新支付';
      this.$track?.registeredEvents('H5_2B_PaymentResultPageBtnClick', {
        commodity_id: this.skuID,
        order_number: this.orderNo,
        pay_method: this.payMethodName,
        pay_status: this.payStatusName,
        buttons_name: name
      });
      if (type == 1) {
        this.$router.replace({ name: 'orderList', params: { state: 0 } });
      } else {
        this.$router.replace({ name: 'pay', query: { orderNo: this.orderNo } });
      }
    },
    // 获取支付结果信息
    async getResultInfos(payType) {
      const [data] = await getResultInfo({ orderNo: this.orderNo, paySuccess: true, payType });
      if (data) {
        // 本单已享以下权益
        this.couponList = data.couponList || [];
        // 礼品卡
        this.cardInfo = data.cardInfo || null;
        this.showGiftCardContext = !!this.cardInfo;
        // 成长值
        this.eventPointInfo = data.eventPointInfo || null;
      }
    },
    // 获取按钮信息
    async getPayResultButton(sceneSource) {
      const [data] = await getPayResultBtn({
        orderNo: this.orderNo,
        sceneSource, // 场景来源: 0-普通订单(未传递，默认普通订单), 1-vcc到MAX场景, 2-电商MAX场景, 3-电商普通会员场景
        payResultStatus: this.isSuccess ? 2 : 1
      });
      if (data) {
        this.buttonInfo = data;
      }
    },
    otherPage() {
      if (this.sceneSource) {
        switch (+this.sceneSource) {
          case 3:
            this.goMemberCenter(this.payStatus);
            break;
          case 2:
            this.goMaxMember(this.payStatus);
            break;
          default:
            this.$router.back();
            break;
        }
      } else {
        this.$router.back();
      }
    },
    // 按钮跳转：1-返回首页；2-返回上一级页面（查看max会员页、返回卡包首页）；3-重新支付；4-跳转链接(查看订单)
    jumpPage(btnInfo) {
      switch (+btnInfo.jumpType) {
        case 1:
          this.goHome(this.payStatus);
          break;
        case 3:
          this.goPage(0);
          break;
        case 4:
          this.goPage(1);
          break;
        default:
          this.otherPage();
          break;
      }
    },
    goViewCouponDetail() {
      this.$router.push('/');
    },
    toGiftCard() {
      this.$router.replace({ name: 'giftCardList' });
    },
    async getGoodsFeed() {
      this.loading = true;
      this.pageNo++;
      const [res] = await getGoodsList({
        pageNo: this.pageNo,
        pageSize: 10,
        pageType: 4
      });
      this.loading = false;
      if (!res || !res.hasNext) {
        this.finished = true;
      }
      if (!res) {
        return;
      }
      this.goodsList = [...this.goodsList, ...res.goodsList];
    }
  }
};
</script>
<style lang="less" scoped>
.card {
  margin: @padding-sm;
  background-color: @white;
  border-radius: @border-radius-sm;
  padding: 28px @padding-sm @padding-sm @padding-sm;

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

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

    &__text {
      .text-size(16);
      margin-left: @padding-md;
    }

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

    &__money {
      margin-top: @padding-xs;
    }
    &__free {
      .text-size(13);
      margin-top: @padding-xs;
      color: @font-color-light;
    }
  }

  .tips {
    .text-size(12);
    text-align: center;
    margin-top: @padding-lg;
    color: @font-color-light;
  }

  &-growth-box {
    margin-top: 9px;
    height: 44px;
    border-radius: 8px;
    // background-image: url('https://img.lkbang.net/icon-growth-value.7c5466cf30222be1.7c5466cf.png');
    background-repeat: no-repeat;
    background-size: 30px;
    background-position: 4px;
    background-color: #fffbf2;
    padding: 0 10px 0 40px;
    font-size: 12px;
    color: #282828;
    display: flex;
    justify-content: space-between;
    align-items: center;
    &__value {
      color: #ffa130;
      margin-right: 4px;
    }
  }
  .actions {
    display: flex;
    flex-direction: row;
    margin-top: @padding-lg;
    justify-content: space-between;
    &__back {
      color: @cherry-color-error;
      border: 1px solid @cherry-color-error;
    }

    &__order {
      @primary-bg();
      margin-left: @padding-sm;
    }

    button {
      // flex: 1;
      .text-size(17);
      width: 161px;
    }
  }
  .info_button {
    width: 100%;
  }
}
.coupon-box {
  box-sizing: border-box;
  margin: @padding-sm;
  background-color: @white;
  border-radius: @border-radius-sm;
  padding: @padding-sm;
  height: 150px;
  overflow: hidden;
}
.coupon-tip {
  .text-size(14);
  font-family: PingFangSC-Medium;
  .text-size(14);
  color: #ff4735;
  letter-spacing: 0;
  margin-bottom: @padding-unit;
}
.coupon-wrap {
  display: flex;
  flex-direction: row;
  height: 120px;
  width: 327px;
  padding: 0;
  overflow: hidden;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}
.coupon-item {
  display: inline-flex;
}
.goods {
  background-color: #fff;
  box-sizing: border-box;
  // width: 100%;
  margin: @padding-sm;
  padding: @padding-sm;
}

.giftCardModalContainer {
  width: 336px;
  height: 390px;
  background: transparent;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .container {
    box-sizing: border-box;
    width: 336px;
    height: 337px;
    background: url('https://img.lkbang.net/giftcard-bg.1ac982ad.png');
    background-repeat: no-repeat;
    background-size: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 44px 0 0 0;
    box-sizing: border-box;
    .title {
      font-size: 22px;
      color: #e11500;
      text-align: center;
    }
    .content {
      width: 287px;
      height: 83px;
      flex-grow: 0;
      flex-shrink: 0;
      background: @white;
      border-radius: 6px;
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 @padding-xs 0 @padding-xs;
      box-sizing: border-box;
      margin: 0 auto;
      .tag {
        position: absolute;
        top: 0;
        left: 0;
        background-image: linear-gradient(90deg, #fbe9c0 2%, #d59b6e 98%);
        border-radius: 4px 0 4px 0;
        font-size: 10px;
        color: @white;
        width: 44px;
        height: 16px;
        text-align: center;
        line-height: 1px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .price {
        width: 80px;
        flex-shrink: 0;
        box-sizing: border-box;
        padding-right: @padding-unit;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 30px;
        color: @red;
        text-align: center;
        &::before {
          content: '¥';
          display: inline-block;
          font-size: 16px;
        }
      }
      .giftcard-desc {
        width: 120px;
        flex-shrink: 0;
        padding-right: @padding-unit;
        box-sizing: border-box;
        p {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          &:first-child {
            font-size: 14px;
            color: @black;
            font-weight: bold;
          }
          &:last-child {
            font-size: 12px;
            color: @gray-5;
            margin-top: @padding-x;
          }
        }
      }
      .buttonArea {
        width: 68px;
        flex-shrink: 0;
        button {
          display: block;
          width: 68px;
          height: 25px;
          background: #ff2f28;
          border-radius: 12.5px;
          color: @white;
          font-size: 12px;
          padding: 0;
        }
      }
    }
    .desc {
      font-size: 12px;
      color: @white;
      text-align: center;
      height: 44px;
      line-height: 44px;
      a {
        color: @white;
        font-size: 12px;
        text-decoration: underline;
      }
    }
  }
}
.feedbox {
  padding: 0 12px 16px;
  /deep/ .cr-loading--text {
    color: #999;
  }
  &--img {
    height: 30px;
    text-align: center;
  }
}
</style>
