<template>
    <div class="container pagePay">
      <loadingWrap v-if="loading && checkPriceStatus==8" class="payLoading" :msg="'预定处理中...'"><
        <div slot="loadingInfo">机酒套餐比单买最高立省30%...</div>
      </loadingWrap>
      <section v-else>
        <payInfo :orderInfo="orderInfo"></payInfo>

        <div class="pay-info">
          <div class="pay-way" @click="payWay=0" v-if="payWayObj.wechat">
            <i class="iconfont icon-wxpay"></i>  微信支付 <span class="iconfont" :class="{'icon-gou1':payWay==0}"></span>
          </div>
          <div class="pay-way" @click="payWay=2" v-if="payWayObj.alipay">
            <i class="iconfont icon-zhifubao" style="color:#1aabed;"></i>  支付宝支付 <span class="iconfont" :class="{'icon-gou1':payWay==2}"></span>
          </div>
          <div class="pay-way" @click="payWay=1" v-if="payWayObj.EasyPay">
            <img src="https://file.luckytrip.cn/IBE/img/ys1.png" alt="">  易生支付 <span class="iconfont" :class="{'icon-gou1':payWay==1}"></span>
          </div>

          <a href="javascript:void(0)" class="btn mBtn" @click="toPay">支付</a>
        </div>

        <div class="fixed-wrap" v-show="isPay">
          <i class="iconfont icon-guanbi1 icon-close" @click="isPay=false"></i>
          <div class="weChatCodeImg" id="weChatPayDiv">
            <canvas class="hide" id="canvas"></canvas>
            <div id="weChatCodePayDiv">
            </div>
            <p>长按识别二维码支付</p>
          </div>
        </div>

      </section>
    </div>
</template>
<script>
  import QRCode from 'qrcode'
  import payInfo from './payInfo.vue'
    export default {
        name: '',
        data () {
            return {
              loading:false,
              isVerificate:false,
              orderNumber:this.$route.params.orderNumber,
              amount:0,
              productDetail:'',
              isPay:false,
              codeImg:'',
              timer:'',
              wechatH5Msg:'',
              payWay:0, // -1没选，0 微信支付，1易生支付，2支付宝
              payWayObj:wxPayWay,
              orderInfo:{
                hotelInfo:{}
              },
              checkPriceStatus:8
            }
        },
        methods: {
          changePayWay(type){
              this.payWay=type;
          },
          toPay(){
            let _this=this;
            if(this.payWay == 0){ //微信
//              var wechatInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i);
//              if(wechatInfo && wechatInfo[1] >= "5.0" ){
//                this.weixinToPay();
//              }else {
//                var mobileAgent = new Array("iphone", "ipod", "ipad", "android", "mobile", "blackberry", "webos", "incognito", "webmate", "bada", "nokia", "lg", "ucweb", "skyfire");
//                var browser = navigator.userAgent.toLowerCase();
//                let isMobile=false;
//                for (var i=0; i<mobileAgent.length; i++){
//                  if (browser.indexOf(mobileAgent[i])!=-1){
//                    isMobile = true;
//                    break;
//                  }
//                }
//                if(isMobile){  //手机浏览器
//                  /*手机h5支付*/
//                  this.getWeChatPayH5Url();
//                }else {
                  this.useqrcode();
//                }
//              }
            }else if(this.payWay ==1) { //易生
              this.getBhecardH5Url();
            }else if(this.payWay==2){  //支付宝
              this.alipayTradeWapPay();
            }

            this.$nextTick(function () {
              if(!_this.isVerificate){
                _this.timer = setInterval(function () {
                  _this.getOrderPayState();
                },3000)
              }else {
                _this.isVerificate = true;
                clearInterval(_this.timer);
              }
            });
          },

          /*支付宝支付*/
          alipayTradeWapPay(){
            alipayTradeWapPay({orderNumber:this.orderNumber}).then(data=>{
              if(data.returnCode==200){
                window.location.href=data.data;
              }else {
                Toast(data.returnMsg);
              }
            });
          },

          /*易生支付h5*/
          getBhecardH5Url(){
            getBhecardH5Url({orderNumber:this.orderNumber}).then(data=>{
              if(data.returnCode==200){
                location.href=data.data;
              }else {
                this.msgInfoAlert();
              }
            })
          },

          /*手机h5支付*/
          getWeChatPayH5Url(){
            getWeChatPayH5Url({orderNumber:this.orderNumber}).then(data=>{
              if(data.returnCode==200){
                location.href=data.data;
              }else {
                this.isVerificate = true;
                this.msgInfoAlert();
                return;
              }
            });
          },

          /*支付超时提示*/
          msgInfoAlert(){
            clearInterval(this.timer);
            MessageBox({message:'<p style="line-height: 22px;font-size: 13px;font-weight: bold">很抱歉，由于您停留时间太长，资源发生变化，订单已关闭</p>',
              confirmButtonText: '重新选择',
              closeOnClickModal:false,
              showCancelButton: false
            }).then(action => {
              let params={
                depCode:this.orderInfo.depCode,
                arrCode:this.orderInfo.arrCode,
                dateType:0, //1灵活，0固定
                isFixiable:false,
                depDate:this.orderInfo.depDate,
                returnDate:this.orderInfo.returnDate,
                minduration:this.orderInfo.lengthOfStay,
                adults:this.orderInfo.adultNumber,
                childages:this.orderInfo.childList.join(","),
                type:this.orderInfo.orderType
              };

              if(this.orderInfo.orderType=='STATIC_PACKAGE'){
                this.$router.push('/wx');
              }else {
                this.$router.push({path: '/wx/productList?'+ urlEncode(params).substr(1)});
                location.reload();
              }
            });
          },

          /*微信公众号支付*/
          weixinToPay(){
            var _this=this;
            if (typeof WeixinJSBridge == "undefined"){
              if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', _this.onBridgeReady, false);
              }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', _this.onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', _this.onBridgeReady);
              }
            }else{
              _this.onBridgeReady();
            }
          },
          /*微信公众号调取支付*/
          onBridgeReady(){
            var _this=this;
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest',
              _this.wechatH5Msg,
              function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok" ){
                  // 使用以上方式判断前端返回,微信团队郑重提示：
                  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                  location.href='/wx/paySuccess/'+_this.orderNumber;
                }
              });
          },

          getWechatH5Msg(){
            getWechatH5Msg({orderNumber:this.orderNumber}).then(data=>{
              if(data.returnCode==200){
                this.wechatH5Msg=data.data;
              }
            })
          },

          /**获取订单信息*/
          getOrderInfo(){
              let _this=this;
            this.loading=true;
            getOrderInfoByOrderNumber({orderNumber:this.orderNumber}).then(data=>{
              if(data.returnCode==200){
                this.orderInfo.orderNumber=data.data.orderNumber;
                this.orderInfo.amount=parseFloat(data.data.orderActualPrice).toFixed(2);
                let depFlightOrder=data.data.flightOrders[0].flightOrderDetail;
                this.orderInfo.depDate=getdate(depFlightOrder[0].depTime);

                if(data.data.flightOrders.length>1){
                  let arrFlightOrder=data.data.flightOrders[data.data.flightOrders.length-1].flightOrderDetail;
                  this.orderInfo.returnDate=getdate(arrFlightOrder[0].depTime);
                }

                this.orderInfo.depCity=depFlightOrder[0].depCity;
                this.orderInfo.arrCity=depFlightOrder[depFlightOrder.length-1].arrCity;

                this.orderInfo.depCode=depFlightOrder[0].depCode;
                this.orderInfo.arrCode=depFlightOrder[depFlightOrder.length-1].arrCode;

                this.orderInfo.orderType=data.data.orderType;

                if(data.data.orderType=='STATIC_PACKAGE'){
                  if(data.data.staticProductOrderList.length>0){
                    let staticProOrder=data.data.staticProductOrderList[0];
                    this.orderInfo.adultNumber=staticProOrder.staticProduct.adultCount;
                    this.orderInfo.childNumber=staticProOrder.staticProduct.childCount;
                    this.orderInfo.hotelCount=staticProOrder.staticProduct.hotelCount;
                    this.orderInfo.product=staticProOrder.staticProduct.product;
                    this.orderInfo.lengthOfStay=staticProOrder.lengthOfStay;
                  }
                }else {
                  this.orderInfo.adultNumber=data.data.adultNumber;
                  this.orderInfo.childNumber=data.data.childNumber;
                  if(data.data.hotelOrders.length>0){
                    this.orderInfo.hotelInfo=data.data.hotelOrders[0];
                    this.orderInfo.lengthOfStay=data.data.hotelOrders[0].hotelOrderDetail.lengthOfStay;
                  }
                }

                this.orderInfo.childList=[];
                data.data.listTicketUser.forEach(item=>{
                  if(item.ageType==1){
                    this.orderInfo.childList.push(getBirthAge(item.birthday))
                  }
                });

                if(data.data.orderStatus==0){
                  this.checkPriceStatus=0;
                  this.loading=false;
                }else if(data.data.orderStatus==4){   //失败
                  this.checkPriceStatus=4;
                  this.loading=false;
                  this.msgInfoAlert();
                }else if(data.data.orderStatus==8){   //继续检查
                  this.timer=setTimeout(function () {
                    _this.getOrderInfo();
                  },2000)
                }else {
                  this.loading=false;
                  this.msgInfoAlert();
                }
              }else if(data.returnCode=='-10003'){
                location.href="/wx/login?redirectUrl="+window.location.href;
              }
            });
          },
          /**微信二维码*/
          useqrcode(){
            var _this = this;
            _this.loading=true;
            var canvas = document.getElementById('canvas');
            document.getElementById("weChatCodePayDiv").innerHTML='';
            getWeChatPayQrCodeByOrderNumber({orderNumber:this.orderNumber}).then(data=>{
              _this.loading=false;
              if(data.returnCode==200){
                this.isPay=true;
                QRCode.toCanvas(canvas, data.data, function (error) {
                  if (error) console.error(error);
                  var image = new Image();
                  image.src=canvas.toDataURL("image/png");
                  image.style.width='100%';
                  document.getElementById("weChatCodePayDiv").appendChild(image);
                  _this.codeImg = canvas.toDataURL("image/png");
                })
              }else {
                this.isVerificate = true;
                clearInterval(this.timer);
                Toast(data.returnMsg);
              }
            });
          },
          getOrderPayState(){
            getOrderPayState({orderNumber:this.orderNumber}).then(data=>{
              if(data.returnCode==200 && data.data){
                this.isVerificate = true;
                this.$router.push('/wx/paySuccess/'+this.orderNumber);
              }
            })
          },

        },
        mounted(){
          this.getOrderInfo();
          if(is_weixn()) {//微信浏览器
            this.getWechatH5Msg();
          }
        },
        components:{
          payInfo
        },
        destroyed: function () {
          clearInterval(this.timer)

        },
    }
</script>
<style>
  .msgInfoAlert{
    width: 80%;
  }
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" scoped>
@import "../../assets/stylus/colorConfig"
.fixed-wrap{
  background rgba(0, 0, 0, 0.37)
  .icon-close{
    position absolute
    top 20%
    right 10%
    font-size 26px
    color #ffffff
  }
  .weChatCodeImg{
    position absolute
    width 240px
    height 240px
    left 50%
    top 45%
    border-radius 3px
    box-sizing border-box
    transform translate(-50%,-50%)
    background #ffffff
    text-align center
    #weChatCodePayDiv{
      width 100%
      margin auto
      img{
        width 100%
      }
    }
    img{
      display inline-block
      width 200px
      height 200px
    }
    #canvas{
      width 200px!important
      height 200px!important
      background #eee
    }
    p{
      margin-top 20px
      font-size 13px
      color #fff
    }
  }
}

.pagePay{
  position absolute
  width 100%
  height 100%
  top: 0
  left 0
  background #f7f7f7
}
.pay-info{
  padding 20px
  .pay-way{
    background #ffffff
    line-height 50px
    margin-bottom 10px
    padding 0 10px
    font-size 16px
    i{
      margin-right 6px
      font-size 24px
      color #3bae33
    }
    span{
      float right
      color mainColor
    }
    img{
      position relative
      display inline-block
      width 28px
      top 8px
    }
  }
}

</style>
