<template>
  <div class="pay-code">
    <div class="paymount">
      扫码付款：<span class="exp">￥</span><span class="price">{{ data.payAmount | formatPrice }}</span>
    </div>
    <el-image v-loading="isLoading" :src="payUrl" class="qrcode" />
    <div class="pay-tip">
      <i class="icon-wechat" />
      <span>使用微信扫码</span>
    </div>
  </div>
</template>

<script>
import qrcode from 'qrcode'
export default {
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isLoading: false,
      payUrl: '',
      timer: null
    }
  },
  created() {
    this.drawQrcode()
  },
  beforeDestroy() {
    this.stopPayCheck()
  },
  methods: {
    // 绘制支付二维码
    drawQrcode() {
      // const wxPayUri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx91c4152b60ca91a3&redirect_uri=${process.env.VUE_APP_BASE_SERVER}/pay/wechatpay.html&response_type=code&scope=snsapi_base&state=${JSON.stringify(this.data)}#wechat_redirect`
      // const wxPayUri = `https://www-b.caimei365.com/wxcode.html?orderInfo=${encodeURIComponent(
      //   JSON.stringify(this.data)
      // )}`
      const wxPayUri = `${process.env.VUE_APP_BASE_SERVER}/wxcode.html?orderInfo=${encodeURIComponent(
        JSON.stringify(this.data)
      )}`

      console.log(wxPayUri)
      qrcode
        .toDataURL(wxPayUri, { width: 180, margin: 0, errorCorrectionLevel: 'H', type: 'image/jpeg', scale: 1 })
        .then((url) => {
          this.payUrl = url
          this.checkedPayConfirm()
        })
        .catch((err) => {
          console.error(err)
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    stopPayCheck() {
      clearInterval(this.timer)
    },
    // 验证确认支付
    checkedPayConfirm() {
      this.timer = setInterval(() => {
        this.$emit('pay-confirm', {
          type: 'WEIXIN',
          data: {
            ...this.payData,
            ...this.data
          }
        })
      }, 3000)
    }
  }
}
</script>

<style scoped lang="scss">
.pay-code {
  .paymount {
    margin-bottom: 16px;
    font-size: 16px;
    color: #101010;

    .exp,
    .price {
      color: #ff6d6d;
    }

    .exp {
      font-size: 14px;
    }

    .price {
      font-size: 20px;
      font-weight: bold;
    }
  }

  .qrcode {
    width: 180px;
    height: 180px;
    border: 1px solid #1890ff;
    box-sizing: border-box;
    padding: 8px;
  }

  .pay-tip {
    width: 180px;
    margin-top: 12px;
    font-size: 14px;
    color: #101010;
    line-height: 25px;
    text-align: center;
  }

  .icon-alipay,
  .icon-wechat {
    display: inline-block;
    width: 25px;
    height: 25px;
    vertical-align: middle;
    margin-right: 10px;
  }

  .icon-wechat {
    background: url(~@/assets/pay/icon-wechat.png) no-repeat center;
    background-size: 25px;
  }

  .icon-alipay {
    background: url(~@/assets/pay/icon-alipay.png) no-repeat center;
    background-size: 25px;
  }
}
</style>
