<template id='Pay'>
  <div>
    <van-nav-bar title="电量充值" left-arrow @click-left="back">
      <span @click="go" class="iconfont" slot="right">&#xe646;</span>
    </van-nav-bar>
    <div class="fyycontent fyypay">
      <van-cell-group>
        <van-cell>
          <span class="iconfont color-red fyy-icon">&#xe640;</span>
          <span v-html="area.name"></span>
          <span class="m-left10" v-html="building.name"></span>
          <span class="m-left10" v-html="room.name">601</span>
        </van-cell>
        <div class="fyyinput">
          <input type="number" placeholder="请输入要充值的电量度数" v-model="kwh"/>
          <span class="input-right">度</span>
        </div>
        <p class="fyy-h6">价格标准：<span v-html="price"></span>元/度</p>
      </van-cell-group>
      <van-cell-group>
        <van-cell>
          <span class="iconfont color-red fyy-icon">&#xe648;</span>
          选择支付方式
        </van-cell>
        <van-radio-group v-model="payType" class="fyyradio-pay">
          <van-cell-group>
            <van-cell clickable @click="payType = 'weipay'">
              <img src="@/assets/img/weixin.png" />
              <van-radio slot="right-icon" name='weipay'/>
            </van-cell>
            <van-cell clickable @click="payType = 'alipay'">
              <img src="@/assets/img/zhifubao.png" />
              <van-radio slot="right-icon" name='alipay'/>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </van-cell-group>
    </div>
    <div class="fyyfooter">
      <p class="fyy-h5">
        核计：
        <span class="fyy-h3 color-red" v-html="total"></span>元
      </p>
      <router-link to="/Pay">
        <van-button type="bigred" @click="pay" :loading="paying">支付</van-button>
      </router-link>
    </div>

    <van-dialog
      v-model="showAlipay"
      title="支付宝扫码支付"
      overlay
      confirm = "paying = false"
    >
      <div ref="qrcodeDiv" class="qrcode"></div>
    </van-dialog>
  </div>
</template>

<script>
import remoteApi from '@/api/remoteApi'
import QRCode from 'qrcodejs2'
import Cookies from 'js-cookie'

export default {
  data() {
    return {
      paying: false,
      area:{},
      building:{},
      room:{},
      price:0,
      roomId : null,
      kwh : 0,
      payType: 'weipay',
      showAlipay: false,
      qrCodeUrl: ''
    }
  },
  methods: {
    go() {
      this.$router.push("/Paylist")
    },
    back() {
      this.$router.push("/")
    },
    pay() {
      var self = this
      self.paying = true

      self.$toast.loading({
        message: '处理中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 10000
      });

      if(self.payType=='weipay'){
        //首先要获取openid
        remoteApi.prepareWXPay(self.roomId,self.payType,self.kwh,self.total).then(resp=>{
          self.$toast.clear()

          if(resp.result) {
            var appId = resp.data.appId
            var redirectUri = encodeURIComponent(window.location.href.split('#')[0] + '#WXPay')
            var state = resp.data.recordId

            var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`
            
            window.location.href = url
          }
          else{
            self.paying = false
            self.$toast.fail(resp.message)
          }
        });
      }
      else if(self.payType=='alipay') {
        remoteApi.prepareAliPay(self.roomId,self.payType,self.kwh,self.total).then(resp=>{
          if(resp.result){
            var recordId = resp.data.recordId;
            return remoteApi.tradePrecreatePay(recordId);
          }
          else{
            self.paying = false
            self.$toast.fail(resp.message)
          }
        }).then(resp=>{          
          self.$toast.clear()

          if(resp==null){
            return;
          }

          console.log(resp);

          if(resp.result) {
            self.showAlipay = true;

            //对话框显示后才能正常获取到$refs.qrcodeDiv
            self.$nextTick(()=>{
              var qrcode = new QRCode(self.$refs.qrcodeDiv, {
                text: resp.data,
                width: 200,
                height: 200,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
              })
            })
          }
          else{            
            self.paying = false
            self.$toast.fail(resp.message)
          }
        });
      }
    }
  },
  computed: {
    total (){
      return (this.kwh * this.price).toFixed(2);
    }
  },
  mounted () {
    // 当前页面是否获取到了openid?
    this.roomId = this.$route.query.roomId;

    if(this.roomId==null || this.roomId.length==0){
      this.roomId = Cookies.get("selectedRoomId");
    }

    this.$toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
      duration: 10000
    });

    var self = this;

    remoteApi.queryRoomDetail(this.roomId).then((resp)=>{
      console.log(resp);

      this.$toast.clear();

      if(resp.result){
        //self.$toast.success('查询成功!')

        var jsonData = resp.data
        self.area = jsonData.area
        self.building = jsonData.building
        self.room = jsonData.room
        self.price = parseFloat(jsonData.price)
      }
      else {
        self.$toast.fail(resp.message)
      }
    });
  }
}
</script>

<style lang="scss" scoped>

</style>
