<template>
  <view class="pay-order">
    <u-icon name="clock" size="170" :color="primaryColor" />
    <text>支付金额</text>
    <text class="pay-amount">¥{{ payAmount }}</text>
    <!--    <button @click="confirmPay">确认支付</button>-->
    <u-button round type="primary" :custom-style="{ width: '100%', backgroundColor: primaryColor }" @click="confirmPay">
      确认支付
    </u-button>
  </view>
</template>

<script>
import { Request } from '../../index';
import { payOrderByWeixin, payClaim } from '../../mall/api';
import { mapState } from 'vuex';
export default {
  name: 'PayOrder',
  props: {
    xid: {
      type: String,
      default: null,
    },
    payAmount: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    ...mapState({
      primaryColor: state => (state.primaryColor ? state.primaryColor : '#ee0a24'),
    }),
  },
  methods: {
    async confirmPay() {
      const _this = this;
      try {
        const openId = Request.getOpenId();
        const params = {
          openId,
          xid: this.xid,
        };
        const res = await payOrderByWeixin(params);
        if (res.orderPayMeta && res.orderPayMeta.comment) {
          const payComment = JSON.parse(res.orderPayMeta.comment);
          console.log(' payComment --> ', payComment.weixin);
          const { timeStamp, nonceStr, signType, paySign } = payComment.weixin;
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            package: payComment.weixin.package,
            signType: signType,
            paySign: paySign,
            success: async res => {
              console.log('pay success:', res);
              if (res.errMsg === 'requestPayment:ok') {
                await payClaim({ xid: this.xid, isPay: true });
                // uni.redirectTo({
                //   url: `/packageMall/order/paySuccess?payAmount=${_this.payAmount}`,
                // });
                this.$emit('paySuccess', _this.payAmount);
              }
            },
            fail: err => {
              console.log('pay fail:', err);
            },
          });
        }
      } catch (e) {
        console.log('err', e);
        throw e;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.pay-order {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 50px;
  .pay-amount {
    font-size: 40rpx;
  }
  button {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 100rpx;
    background: linear-gradient(to right, #ffac30, #fc3d42);
    font-size: 30rpx;
    color: #fff;
    margin: 30rpx auto 20rpx;
    &:after {
      border: none;
    }
  }
  text {
    line-height: 2;
    color: #333;
  }
}
</style>
