<template>
  <div class="card">
    <div class="info">
      <cr-image
        width="63px"
        height="63px"
        class="info__image"
        src="../../assets/images/pay/paying.png"
      />
      <div v-if="init" class="info__desc">
        <p class="info__text">
          <span v-if="time">（{{ time }}s）支付中...</span>
          <span v-else>系统处理中</span>
        </p>
      </div>
    </div>
    <p class="tips">努力返回支付结果中，请留心查看！</p>
    <div class="actions">
      <cr-button
        class="actions__back"
        :plain="true"
        type="primary"
        shape="circle"
        @click="goHome('正在支付')"
        >返回首页</cr-button
      >
      <cr-button shape="circle" type="primary" @click="goOrderDetail('正在支付')"
        >查看订单</cr-button
      >
    </div>
  </div>
</template>
<script>
import { queryPayStatus } from '@/api/pay.api';
import cookies from '@/service/cookieStorage.service';
import localStorage from '@/service/localStorage.service';
import { goUrlExtends } from './extends';
import { isIOS } from '@/service/validation.service';
import { IS_THIRD_PAY } from './STATIC_DATA';

export default {
  components: {},
  extends: goUrlExtends,
  data() {
    return {
      orderNo: null,
      timer: null,
      time: 10,
      init: false,
      isWx: false
    };
  },

  created() {
    this.orderNo = this.$route.query.orderNo || cookies.get('orderNo')?.orderNo;
    this.orderNo = this.orderNo?.split('?')[0];
    this.isWx = this.$route.query.isWx;
    if (!localStorage.get('isAppInner') && this.$config.xincheng) {
      const schema = isIOS ? 'xincheng://' : 'app://xincheng/splash';
      setTimeout(() => {
        window.location.href = schema;
      }, 2000);
    }
  },
  mounted() {
    localStorage.remove('inPay');
    this.$track?.registeredEvents('h5_RechargeResultPageExposure', {
      pay_status: '正在支付'
    });
    const amount = cookies.get('amount') || {};
    const payTrackInfo = cookies.get('payTrackInfo') || {};
    this.$track?.registeredEvents('H5_2BPaymentPageExposure', {
      order_no: this.orderNo,
      pay_result: '正在支付',
      vcc_state: payTrackInfo.vcc_state,
      pay_method: payTrackInfo.pay_method,
      pay_amount: amount.finalAmt
    });
    this.query('first');
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    loop() {
      this.query();
      this.timer = setInterval(() => {
        this.time -= 1;
        if (this.time % 2 === 0) {
          this.query();
        }
        if (this.time < 1) {
          clearInterval(this.timer);
        }
      }, 2000);
    },
    goSuccess(payType) {
      clearInterval(this.timer);
      // 支付成功
      if (this.$config.channelId && localStorage.get('vccChannel') == this.$config.channelId.id) {
        this.$router.replace({ name: 'paySuccess', query: { orderNo: this.orderNo, payType } });
      } else {
        this.$router.push({ name: 'paySuccess', query: { orderNo: this.orderNo, payType } });
      }
    },
    goPay() {
      // 兼容之前的xincheng，通过customize文件里面配，挂载到全局$config
      if (!this.$config.xincheng) {
        // const payByThirdPartyCashierUrl = localStorage.get('payByThirdPartyCashierUrl') || '';
        // location.replace(payByThirdPartyCashierUrl);
        this.$router.replace({ name: 'pay', query: { orderNo: this.orderNo } });
        return;
      }
      if (this.isWx) {
        this.$router.go(-2);
        return;
      }
      this.$router.go(-1);
    },
    async query(pay) {
      const [data, error] = await queryPayStatus({ orderNo: this.orderNo });
      if (error || !data) {
        this.$router.replace({
          name: 'payFail',
          query: { reason: error.message, orderNo: this.orderNo }
        });
        return;
      }
      if (+data?.payStatus === 3) {
        this.goSuccess(data.payMethod);
        return;
      } else if (pay === 'first') {
        if (IS_THIRD_PAY(+data?.payMethod)) {
          this.$dialog({
            message: '请确认订单已完成支付',
            confirmButtonText: '已完成支付',
            cancelButtonText: '重新支付',
            confirmButtonColor: '#EC1500',
            onCancel: () => {
              this.$track?.registeredEvents('h5_RechargeResultPageClick', {
                pay_status: '正在支付',
                buttons_name: '重新支付'
              });
              this.query('repeatPay');
            },
            onConfirm: () => {
              this.init = true;
              this.loop();
            }
          });
        } else {
          this.init = true;
          this.loop();
        }
      }
      if (this.time === 0) {
        this.$router.replace({
          name: 'payFail',
          query: { reason: '支付失败', orderNo: this.orderNo }
        });
        return;
      }
      if (pay === 'repeatPay') {
        this.goPay();
      }
    }
  }
};
</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;
  }

  .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 {
      .text-size(17);
      width: 161px;
    }
  }
  .info_button {
    width: 100%;
  }
}
</style>
