<template>
  <div class="ybOrderRender">
    <div class="container" >
      <p class="title" >*课程教材收货地址</p>
      <div class="content" >
        <van-cell title="收货地址" ref="order" v-if="!open" @click="open=true;buttonClick('按钮点击','友邦点击填写')" value="点击填写" is-link>
        </van-cell>
        <div v-if="open">
           <van-field
            v-model="orderParams.name"
            type="text"
            label="收货人"
            placeholder="请输入收货人"
          />
          <van-field
            v-model="orderParams.mobile"
            type="text"
            label="手机号"
            placeholder="请输入手机号"
          />
          <van-field
            v-model="orderParams.verify_code"
            type="text"
            label="验证码"
            placeholder="请输入短信验证码"
          >
          <van-button slot="button" @click="sendCode();buttonClick('按钮点击','友邦发送验证码')" plain round size="small" v-if="time==0" type="primary">发送验证码</van-button>
          <van-button slot="button"  plain round size="small" disabled v-if="time>0" type="primary">{{time}}s后重新发送</van-button>
          </van-field>
          <van-field
            v-model="addressArea"
            type="text"
            label="所在地区"
            :is-link='link'
            @click="showAddressPicker=true"
            placeholder="请选择"
          />
          <van-field
            v-model="orderParams.address"
            type="text"
            label="详细地址"
            placeholder="请输入详细地址"
          />
        </div>
      </div>
    </div>
    <div class="container" >
      <p class="title" >订单信息</p>
      <div class="content" >
        <div class="top" > 
          <div class='left'>
            <div>唱唱启蒙英语精品课（适合1-5岁）</div>
            <p>课时10天</p>
          </div>
          <div class='right'>
            ￥0
          </div>
        </div>
        <div class="main" >
          <div class='tip'>
            <span>[优惠]</span>限时福利，0元专享10节课
          </div>
          <div class='tip'>
            <span>[赠品]</span>配套教材礼包
          </div>
          <div class="info" >
            <p style="margin-top:6px;" >课程教材（共31件）</p>
            <img class='imgprize' :src="imgprize" alt="">
          </div>
        </div>
      </div>
    </div>
    <div class='bottom'>
      <div class='left'>
        <div>邮费:<span>￥5.0</span></div>
      </div>
      <div class='right'>
        <van-button slot="button" class="pay-btn" @click="payOrder();buttonClick('按钮点击','友邦去支付')"  round size="normal"  type="">去支付</van-button>
      </div>
    </div>
    <my-address
      :showAddressPicker="showAddressPicker"
      @save-address="saveAddress"
      @hide-picker="hidePicker"
      :init="addressArea"
    ></my-address>
    <order-cancel-dialog 
    v-if="orderCancel"
    :orderCancel='orderCancel'
    @cancel='orderCancel=false'
    @payEven='pay'>
    </order-cancel-dialog>
  </div>
</template>

<script>
import {sendMobileCodeApi,postYoubangApi,payApi,getYoubangApi,getGoodsDetailApi,getwechatParam } from "../../service/api";
import { Cell, Toast,Field } from "vant";
import  orderCancelDialog  from "../buy/orderCancelDialog";
import imgprize from '../../assets/yb/imghh@2x.png'
import MyAddress from "@/components/address-picker/Address.vue";
export default {
  name: "ybOrderRender",
  data() {
    return {
      addressInfo: {},
      open:false,
      link:true,
      orderParams:{
        name:'',
        mobile:'',
        verify_code:'',
        address:''
      },
      showAddressPicker: false,
      addressArea:'',
      time:0,
      invite_code:'',
      this_code:'',
      groupDetail:{},
      orderCancel:false,
      imgprize:imgprize
    };
  },
  components: {
    [Cell.name]: Cell,
    [Field.name]: Field,
    MyAddress,
    orderCancelDialog
  },
  mounted() {
    this.initPage();
  },
  methods: {
    buttonClick(buttonType, buttonName) {
      this.$sa.track("buttonClick", {
        tabTitle: "商品",
        moduleTitle: "详情页",
        buttonType: buttonType,
        buttonName: buttonName
      });
    },
    payOrder(){
      let param = {};
      if (!this.orderParams.name) {
        Toast("收货人不能为空");
        return false;
      } else if (!this.orderParams.mobile) {
        Toast("手机号不能为空");
        return false;
      } else if (!/^1\d{10,12}$/.test(this.orderParams.mobile)) {
        Toast("手机号格式不正确");
        return false;
      }else if (!this.addressArea) {
        Toast("所在地区不能为空");
        return false;
      } else if (!this.orderParams.verify_code) {
        Toast("验证码不能为空");
        return false;
      } else if (!this.orderParams.address) {
        Toast("详细地址不能为空");
        return false;
      }
      let values = this.addressAreaCode.split("-");
      let labels = this.addressArea.split("-");
      // param.deliver_id = this.deliverId;
      param.receive_name = this.orderParams.name;
      param.receive_mobile = this.orderParams.mobile;
      param.address = this.orderParams.address;
      param.province_id = values[0];
      param.province_name = labels[0];
      param.city_id = values[1];
      param.city = labels[1];
      param.area_id = values[2];
      param.area = labels[2];
      param.verify_code = this.orderParams.verify_code;
      console.log(param)
      postYoubangApi(param).then(res =>{
        this.pay()
      })
    },
    pay(){
      this.orderCancel = false
      let json={
            goods_id:50
          };
          if(this.groupDetail.goods_type === 2 && !this.type){
            json.buy_type = 2
          }
          if(this.invite_code){
            json.invite_code = this.invite_code
          }
          if(this.saleObj){
            json.order_coupon_id =this.saleObj.id
          }
          let invite = this.$route.query.invite_code;
          if(window.location.href.indexOf('gdt_vid')>-1){
            json.gdt_vid = this.$route.query.gdt_vid
          }
          console.log(this.$route.query.gdt_vid)
          if(window.location.href.indexOf('cct_user_id')>-1){
            json.cct_user_id = this.$route.query.cct_user_id
          }
          this.orderFlag = false;
          payApi(json).then(res=>{
            // console.log(res)
            if(res.out_trade_no && !res.appId){
                this.$router.push({name:'ybPaySuccess',query:{invite_code:this.invite_code}});
            }else{
              let that = this;
              this.orderNo = res.out_trade_no;
              this.jsApiParameters = res;
              wx.miniProgram.getEnv(function(res) {
                if(res.miniprogram){
                  let payParam = encodeURIComponent(JSON.stringify(json));
                  wx.miniProgram.navigateTo({url: `pages/wxPay/main?payParam=${payParam}`})
                }else if (typeof WeixinJSBridge === 'undefined') {
                  if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', that.jsApiCall, false)
                  } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', that.jsApiCall);
                    document.attachEvent('onWeixinJSBridgeReady', that.jsApiCall)
                  }
                } else {
                  that.jsApiCall()
                }
              })
            }
          }).catch((res)=>{
            // alert(res)
            this.orderFlag = true;
          })
    },
    jsApiCall: function () {
        let that = this;
        let query={}
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          this.jsApiParameters,
          function (res) {
            that.orderFlag = true;
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              //  支付成功后处理
              Toast('支付成功');
              this.$router.push({name:'ybPaySuccess',query:{invite_code:this.invite_code}})
            }
            if (res.err_msg === 'get_brand_wcpay_request:fail') {
            }
            if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              console.log(248)
              that.orderCancel=true
            }
          })
      },
    timeO(){
        if(this.time>0){
          this.time--;
          setTimeout(()=>{
            this.timeO()
          },1000)
        }
      },
    sendCode(){
       let json={
        };
        let mobileCheck = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
        if(this.orderParams.mobile.match(mobileCheck)){
          json.mobile = this.orderParams.mobile
        }else{
          Toast('请正确填写手机号');
          return false
        }
        this.time=30;
        this.timeO();
        this.$sa.track('clickSendcode',{});
        sendMobileCodeApi(json).then(res=>{
          if(res === '操作成功'){
            Toast('验证码已发送');
          }else{
            this.time = 0;
            Toast(res);
          }
        }).catch(res=>{
        })
    },
    hidePicker() {
      // 接受子组件关闭popup事件
      this.showAddressPicker = false;
      console.log(this.showAddressPicker)
    },
    saveAddress(labels, values) {
      console.log(labels);
      console.log(values);
      // 从子组件接受返回所选值 val
      this.addressArea = labels;
      this.addressAreaCode = values;
      this.showAddressPicker = !this.showAddressPicker;
    },
    initPage() {
      let query = {};
      let redeem_code = ''
      if (window.location.href.indexOf("channel_code") > -1) {
        query.channel_code = this.$route.query.channel_code;
      }
      if (window.location.href.indexOf("redeem_code") > -1) {
        query.redeem_code = this.$route.query.redeem_code;
        redeem_code = this.$route.query.redeem_code;
      }
      if (window.location.href.indexOf("invite_code") > -1) {
        query.invite_code = this.$route.query.invite_code;
        this.invite_code = this.$route.query.invite_code;
      }
      getYoubangApi({'redeem_code':redeem_code}).then(res =>{
        if(res.res==1){
          this.$router.push({name:'ybOrderRender',query:query})
        }else if(res.res==2||res.res==4){
          this.$router.push({name:'ybPaySuccess',query:query})
        }else{
          
        }
      })
      getGoodsDetailApi(50).then(res =>{
        this.groupDetail = res
      })
      this.user_id = JSON.parse(localStorage.getItem("userDesc")).user_id;
      this.onShare()
      
    },
    handleInviteCode() {
      if (!this.invite_code) {
        this.this_code = "CC-AIA-" + this.user_id;
      } else {
        let invite_code = this.invite_code.split("-");
        let code = `${invite_code[0]}-${invite_code[1]}`;
        this.this_code = `${code}-${this.user_id}`;
      }
    },
    onShare: function(type) {
      this.handleInviteCode();
      let URL = `${process.env.BUY_URL}invite_code=${this.this_code}`;
      this.enableShare({
        product_title: '【免费领】价值498元亲子早教英语启蒙训练课',
        desc: '友邦助您启蒙宝贝快乐家庭',
        shareIcon: '',
        shareUrl: URL
      });
    },
    enableShare: function(option) {
      let that = this;
      getwechatParam({
        api_list: "onMenuShareAppMessage,onMenuShareTimeline",
        url: window.location.href.split("#")[0]
      }).then(wechatRes => {
        wx.config({
          debug: false,
          appId: wechatRes.appId,
          timestamp: parseInt(wechatRes.timestamp),
          nonceStr: wechatRes.nonceStr,
          signature: wechatRes.signature,
          jsApiList: wechatRes.jsApiList
        });
        wx.ready(function() {
          wx.onMenuShareTimeline({
            title: option.product_title, // 分享标题
            desc: option.desc, // 分享描述
            link: option.shareUrl, // 分享链接
            imgUrl:
              option.shareIcon ||
              "https://cdn.singsingenglish.com/singsing/recommend/logo-refer.png", // 分享图标
            success: function() {
              console.log("分享成功");
            },
            cancel: function() {
              // alert("失败")
              console.log("分享失败");
            }
          });
          wx.onMenuShareAppMessage({
            title: option.product_title, // 分享标题
            desc: option.desc, // 分享描述
            link: option.shareUrl, // 分享链接
            imgUrl:
              option.shareIcon ||
              "https://cdn.singsingenglish.com/singsing/recommend/logo-refer.png", // 分享图标
            success: function() {},
            cancel: function() {}
          });
        });
      });
    },
    
  }
};
</script>

<style scoped lang="less">
@import "../../util/public";
.ybOrderRender {
  background: #F8F8F8;
  padding-bottom: 80 * @toVw;
  .van-cell:not(:last-child)::after{
    right: 15px;
  }
  .van-button{
    color:#1890FF;
    border: 1px solid #1890FF;
  }
  .container{
    .title{
      font-size:13 * @toVw;
      color: #999999;
      height: 28 * @toVw;
      line-height: 28 * @toVw;
      text-indent:15* @toVw;
    }
    .content{
      font-size: 15 * @toVw;
      .top{
        background: white;
        padding: 15px;
        display:flex;
        font-size: 15 * @toVw;
        border-bottom: 1*@toVw solid #E2E2E2;
        .left{
          margin: 0;
          p{
            color:#999999;
            font-size:13 * @toVw;
            margin-top: 2px;
          }
        }
        .right{
          margin-right: 0;
        }
      }
      .main{
        padding: 15px;
        background: white;
        .tip{
          margin-bottom: 4*@toVw;
          span{color:#FF7D77;}
        }
        .info{
            font-size:13 * @toVw;
            color:#999999;
            line-height: 24 * @toVw;
            .imgprize{
              width: 207 * @toVw;
              margin-top: 16 * @toVw;
            }
        }
      }
    }
  }
  .bottom{
    display: flex;
    position:fixed;
    bottom: 0;
    background: white;
    width: 100%;
    padding: 5px 15px;
    box-sizing: border-box;
    box-shadow:0px 0px 5px 0px rgba(169,169,169,0.5);
    .right{
      margin-right: 0;
      .pay-btn{
      width: 120 * @toVw;
      background: #FF7D77;
      border: none;
      color:white;
      font-size:17 * @toVw;
      font-weight:bold;
     }
    }
    .left{
      margin-left: 0;
      div{
        color:#666666;
        font-size:13 * @toVw;
        span{
          color: #D6433D;
          font-size:22 * @toVw;
          font-weight:bold;
        }
      }
    }
  }
}
@media screen and (orientation: landscape) {

}
</style>
<style>
  .van-field__label{
    max-width: 80px;
  }
  .van-cell{
    padding: 10px 20px;
  }
</style>

