<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="tel"
            label="手机号"
            placeholder="请输入手机号"
          />
          <van-field
            v-model="orderParams.verify_code"
            maxlength=4
            type="number"
            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>
          <div style="position:relative;" >
            <van-field
            v-model="addressArea"
            type="text"
            label="所在地区"
            :is-link='link'
            placeholder="请选择"/>
          <div  @click="showAddressPicker=true" class="clickItem" ></div>
          </div>
          <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="line"></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,getNewestAddressListAPi,getUserAdressApi } 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";
import addressList from "../address-picker/addr";
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,
      deliverDetail:{},
      query:{}
    };
  },
  components: {
    [Cell.name]: Cell,
    [Field.name]: Field,
    MyAddress,
    orderCancelDialog
  },
  mounted() {
    this.initPage();
  },
  methods: {
    test(){
      this.showAddressPicker = tr
    },
    buttonClick(buttonType, buttonName) {
      this.$sa.track("buttonClick", {
        tabTitle: "商品",
        moduleTitle: "详情页",
        buttonType: buttonType,
        buttonName: buttonName
      });
    },
    getAddressCode() {
      let provinceName = this.addressData.province_name;
      let cityName = this.addressData.city_name;
      let areaName = this.addressData.area_name;
      let provinceCode, cityCode, areaCode;
      for (let i = 0, len = addressList.length; i < len; i++) {
        let item = addressList[i];
        if (cityName == item.label) {
          provinceCode = item.value;
          let secondArr = item.children;
          for (let j = 0, long = secondArr.length; j < long; j++) {
            let secondItem = secondArr[j];
            if (cityName == secondItem.label) {
              cityCode = secondItem.value;
              let thirdArr = secondItem.children;
              for (let k = 0, l = thirdArr.length; k < l; k++) {
                if ((areaName = thirdArr[k].label)) {
                  areaCode = thirdArr[k].value;
                  break;
                }
              }
            }
          }
        }
      }
      this.addressAreaCode = provinceCode + "-" + cityCode + "-" + areaCode;
    },
    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
          }
          if (window.location.href.indexOf("redeem_code") > -1) {
            json.redeem_code = this.$route.query.redeem_code;
          }
          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){
              console.log(214)
              console.log(this)
              console.log(this.$router)
              console.log(this.invite_code)
              this.$router.push({name:'ybPaySuccess',query:that.$route.query});
            }else{
              console.log(220)
              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 () {
      console.log(246)
        let that = this;
        let query={}
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          this.jsApiParameters,
          function (res) {
            that.orderFlag = true;
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              console.log(254)
              //  支付成功后处理
              Toast('支付成功');
              that.$router.push({name:'ybPaySuccess',query:that.$route.query})
            }
            if (res.err_msg === 'get_brand_wcpay_request:fail') {
            }
            if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              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() {
      this.invite_code = this.$route.query.invite_code
      getYoubangApi({'redeem_code':this.$route.query.redeem_code}).then(res =>{
        if(res.res==1){
          this.$router.push({name:'ybOrderRender',query:this.$route.query})
        }else if(res.res==2||res.res==4){
          this.$router.push({name:'ybPaySuccess',query:this.$route.query})
        }else{
          window.location.href=`https://sit.tohours.com/salesplus/goodstart/singing-English-Index.action?parentId=${this.$route.query.parentId}&agentId=${this.$route.query.agentId}`
        }
      })
      // getUserAdressApi().then(res=>{
      //     this.addressObj = res
      //   });
      getUserAdressApi().then(res=>{
          let addressData = res;
          console.log(this.addressArea,374)
          this.addressData = addressData;
          this.orderParams.name = addressData.receive_name;
          this.orderParams.mobile = addressData.receive_mobile;
          this.orderParams.address = addressData.address;
          this.deliverId = addressData.id;
          this.addressArea =
            addressData.province_name +
            "-" +
            addressData.city +
            "-" +
            addressData.area;
            this.getAddressCode()
      })
      
      let invite = this.invite_code;
      getGoodsDetailApi(50).then(res =>{
        this.groupDetail = res
        this.$sa.track("ViewDetailPageAIA", {
          goodsID: this.groupDetail.id.toString(),
            courseCate:
              this.groupDetail.course_type === 1 ? "体验课" : "正式课",
            lessonNumber: this.groupDetail.watch_num,
            goodsName: this.groupDetail.name,
            coursePrice: Number(this.groupDetail.original_price / 100),
            discountPrice: Number(this.groupDetail.current_price / 100),
            courseID: this.groupDetail.course_id,
            courseName: "",
            salesType: invite ? invite.split("-")[1] : "null",
            salesID: invite ? Number(invite.split("-")[2]) : 0
        });
      })
      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.API_URL}#/ybNav?parentId=${this.$route.query.parentId}&agentId=${this.$route.query.agentId}`;
      this.enableShare({
        product_title: '【免费领】价值498元亲子早教英语启蒙训练课',
        desc: '友邦助您启蒙宝贝快乐家庭',
        shareIcon: 'https://cdn.singsingenglish.com/new-sing/6c51175a99f73ee3a410ea9fbf66123f9f49f0f6.png',
        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: '【庆百年 友惊喜】暑期亲子礼︱价值498元唱唱启蒙英语线上课程免费领', // 分享描述
            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: '【庆百年 友惊喜】暑期亲子礼', // 分享标题
            desc: '价值498元唱唱启蒙英语线上课程免费领', // 分享描述
            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;
      .clickItem{
        position:absolute;top: 0;
        width: 100%;
        height: 44 * @toVw;
      }
      .top{
        background: white;
        padding: 15px;
        display:flex;
        font-size: 15 * @toVw;
        // border-bottom: 0.5*@toVw solid #E2E2E2;
        .left{
          margin: 0;
          p{
            color:#999999;
            font-size:13 * @toVw;
            margin-top: 2px;
          }
        }
        .right{
          margin-right: 0;
        }
      }
      .line{
        border-bottom:1px solid #E2E2E2; 
        transform: scaleY(.5);
      }
      .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>