<template>
  <div class="group-buy">
    <div class="address-block" v-if="groupDetail.is_real === 1">
      <div class="add-address" v-if="!addressObj" @click="buttonClick('功能','添加收货地址');showAdd()">
        +请输入收件人地址
      </div>
      <div class="address-content" v-if="addressObj" @click="buttonClick('功能','编辑收货地址');showAdd()">
        <div class="hf">姓名：{{addressObj.receive_name}}</div>
        <div class="hf">联系电话：{{addressObj.receive_mobile}}</div>
        <div>收货人：{{addressObj.province_name}}{{addressObj.city}}{{addressObj.area}}{{addressObj.address}}</div>
      </div>
    </div>
    <div class="shop-block" v-if="groupDetail.goods_desc">
      <div class="shop">
        <div class="img-block">
          <img :src="groupDetail.goods_desc.img[0].url">
        </div>
        <div>
          <div class="title">
            {{groupDetail.name}}
          </div>
          <div class="content">
            {{groupDetail.goods_desc.desc}}
          </div>
          <div class="price" v-if="!type">
            价格 ￥{{groupDetail.current_price/100}}
          </div>
          <div class="price" v-if="type">
            价格 ￥{{groupDetail.original_price/100}}
          </div>
        </div>
      </div>
    </div>
    <div class="you-block" v-if="groupDetail.goods_type !== 4" @click="buttonClick('功能','显示优惠券');showSale()">
      优惠券<img :src="youHuiUrl">
      <div class="you-content">
        <span v-if="!saleObj && !canSale">暂无可用</span>
        <span v-if="!saleObj && canSale" style="color: #F83534">有可用优惠</span>
        <span v-if="saleObj" style="color: #F83534">-{{saleObj.money | price}}</span>
        >
      </div>
    </div>
    <footer>
      <!--<div v-if="groupDetail.is_real !== 1" class="phone-block">-->
        <!--<input placeholder="请输入手机号" class="phone-input" v-model="mobile"/>-->
      <!--</div>-->

      <div class="sub-block">
      合计金额：
      <span>￥{{priceTotal}}</span>

      <div class="pay-btn" @click="payOrder(orderFlag)">提交订单</div>
      </div>
    </footer>
    <transition name="slide-fade">
        <sale-div :salePop="salePop" @chooseSale="chooseSale"></sale-div>
    </transition>
    <transition name="slide-fade">
      <div v-if="addressPop" class="address-pop">
        <addAddress @closeAdd="closeAdd"></addAddress>
      </div>
    </transition>
  </div>
</template>

<script>
  import { Toast, MessageBox } from 'mint-ui'
  import {getUserAdressApi,getGoodsDetailApi,payApi,getwechatParam,getStatusWechatApi,getCouponListApi,getUserDetailApi} from "../../service/api";
  import addAddress from './address'
  import youHuiUrl from '../../assets/shop/youHui.png'
  import saleDiv from './sale'
  export default {
    name: "buy",
    components:{
      addAddress,
      saleDiv
    },
    data(){
      return{
        youHuiUrl:youHuiUrl,
        addressPop:false,
        groupDetail:false,
        popupVisible:true,
        orderFlag:false,
        shopId:'',
        salePop:{
          show:false,
          id:''
        },
        saleObj:null,
        // mobile:'',
        group_order_id:null,
        addressObj:false,
        price:'',
        invite_code:'',
        type:this.$route.query.type,
        jsApiParameters:'',
        orderNo:'',
        canSale:false,
      }
    },
    mounted(){
      this.initPage()
    },
    filters:{
      price(value){
        return (value/100).toFixed(2)
      }
    },
    computed:{
      priceTotal(){
        let priceT = 0;
        if(this.type){
          priceT = this.groupDetail.original_price
        }else{
          priceT = this.groupDetail.current_price
        }
        if(this.saleObj){
          priceT = priceT - this.saleObj.money
        }
        priceT = ( priceT/100 ).toFixed(2)
        return priceT
      }
    },
    methods:{
      jsApiCall: function () {
        let that = this;
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          this.jsApiParameters,
          function (res) {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              //  支付成功后处理
              Toast('支付成功');
              if(that.groupDetail.goods_type === 2 && !that.type){
                setTimeout(function () {
                  that.$router.push({name:'success',query:{out_trade_no:that.orderNo,invite_code:that.invite_code}});
                },1000)
              }else if(that.groupDetail.goods_type === 4){
                setTimeout(function () {
                  that.$router.push({name:'saleSuccess',query:{out_trade_no:that.orderNo,invite_code:that.invite_code}});
                },1000)
              }else{
                setTimeout(function () {
                  that.$router.push({name:'buySuccess',query:{out_trade_no:that.orderNo,invite_code:that.invite_code}});
                },1000)
              }

            }
            if (res.err_msg === 'get_brand_wcpay_request:fail') {
            }
            if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              Toast('取消购买')
            }
          })
      },
      chooseSale(data){
        this.saleObj = data;
      },
      showSale(){
        this.salePop.id = this.shopId;
        this.salePop.show = true
      },
      buttonClick(buttonType,buttonName){
        this.$sa.track('buttonClick',{
          tabTitle:'商品',
          moduleTitle:'购买页',
          buttonType:buttonType,
          buttonName:buttonName
        });
      },
      payOrder(){
        let json={
          goods_id:Number(this.shopId)
        };
        if(this.groupDetail.is_real === 1 && !this.addressObj){
          Toast('请填写地址');
          return false
        }

        if(this.groupDetail.goods_type === 2 && !this.type){
          json.buy_type = 2
        }
        if(this.group_order_id){
          json.group_order_id = this.group_order_id
        }
        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;
        this.$sa.track('placeOrder',{
          buyType:this.groupDetail.goods_type === 2 && !this.type ? '团购' : '直购',
          couponAmount:this.saleObj ? this.saleObj.money : 0,
          paymentAmount:Number(this.priceTotal),
          goodsID:this.shopId.toString(),
          salesType:invite?invite.split('-')[1]:'null',
          salesID:invite?Number(invite.split('-')[2]):0
        });
        if(window.location.href.indexOf('gdt_vid')>-1){
          json.gdt_vid = this.$route.query.gdt_vid
        }
        if(window.location.href.indexOf('cct_user_id')>-1){
          json.cct_user_id = this.$route.query.cct_user_id
        }
        payApi(json).then(res=>{
            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()
              }
            })
        })
      },
      closeAdd(data){
        this.addressPop = data;
        this.initPage()
      },
      showAdd(){
        this.addressPop = true
      },
      initPage(){
        getUserDetailApi().then(res=>{
          if(!res.mobile|| res.mobile === ''){
            this.$router.push({name:'bindMobile',query:{retUrl:this.$route.fullPath}})
          }else{
            getwechatParam({api_list:'chooseWXPay'}).then(res=>{
              wx.config({
                debug: false,
                appId: res.appId,
                timestamp: parseInt(res.timestamp),
                nonceStr: res.nonceStr,
                signature: res.signature,
                jsApiList: res.jsApiList
              });
            });

            getUserAdressApi().then(res=>{
              this.addressObj = res
            });
            this.shopId = this.$route.query.shopId;
            this.group_order_id = this.$route.query.group_order_id;
            getCouponListApi(this.shopId).then(res=>{
              if(res.length>0){
                this.canSale = true
              }
            });
            getStatusWechatApi({goods_id:this.shopId}).then(res=>{
              if(res.out_trade_no){
                if(res.has_buy_goods_info.goods_type ===  2){
                  this.$router.push({name:'success',query:{out_trade_no:res.out_trade_no}});
                }else if(res.has_buy_goods_info.goods_type ===  4){
                  this.$router.push({name:'saleSuccess',query:{out_trade_no:res.out_trade_no}});
                }else if(res.has_buy_goods_info.goods_type !==  5){
                  this.$router.push({name:'buySuccess',query:{out_trade_no:res.out_trade_no}});
                }
              }
            });
            getGoodsDetailApi(this.shopId).then(data=>{
              data.desc = JSON.parse(data.desc);
              data.goods_desc = JSON.parse(data.goods_desc);
              data.share_desc = JSON.parse(data.share_desc);
              this.groupDetail = data;
              this.invite_code = this.$route.query.invite_code;
              if(this.type && this.type === 0){
                this.price=data.single_price/100
              }else{
                this.price = data.group_price/100
              }
            });
            this.orderFlag = true
          }
        });
      }
    }
  }
</script>

<style scoped lang="less">
  @import "../../util/public";
  .slide-fade-enter-active {
    transition: all .5s ease;
  }
  .you-block{
    line-height: 40 * @toVw;
    height: 40 * @toVw;
    padding: 0 15 * @toVw;
    img{
      width: 16 * @toVw;
      vertical-align: middle;
      margin-left: 8 * @toVw;
    }
    .you-content{
      float: right;
      color: #999999;
      font-size: 14 * @toVw;
    }
  }
  .slide-fade-leave-active {
    transition: all .5s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }
  .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
    transform: translateX(10px);
    opacity: 0;
  }
  .phone-block{
    padding: 10 * @toVw;
    text-align: center;
    background: #f8f8f8;

  }
  .phone-input{
    width: 280 * @toVw;
    height: 30*@toVw;
    border-radius: 8 * @toVw;
    outline: none;
    padding:0 10 * @toVw;
    border: 1px solid #e8e8e8;
    text-align: center;
  }
  .group-buy{
    .address-block{
      background: #f0f0f0;
      padding: 10/7.5vw 0;
      .add-address{
        background: white;
        height: 90/7.5vw;
        line-height: 90/7.5vw;
        margin: 20/7.5vw 20/7.5vw;
        text-align: center;
        border-radius: 100px;
        font-size: 16px;
        color: #666666;
      }
      .address-content{
        padding: 20/7.5vw;
        background: white;
        line-height: 1.6em;
      }
    }
    .shop-block{
      .shop{
        padding: 20/7.5vw;
        border-bottom: 1px solid #d8d8d8;
        position: relative;
        &:after{
          content:'';
          display: block;
          clear: both;
        }
        .img-block{
          float: left;
          margin-right: 20/7.5vw;
          img{
            width: 250/7.5vw;
          }
          min-height: 120px;
        }

        .title{
          font-size: 18px;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          color: #333333;
          margin-bottom: 5/7.5vw;
        }
        .content{
          font-size: 12px;
          line-height: 1.4em;
          color: #CCCCCC;
          height: 4.2em;
          overflow: hidden;

        }
        .price{
          font-size: 18px;
          color: #FF001F;
          position: absolute;
          right: 20/7.5vw;
          bottom: 20/7.5vw;
        }
      }
    }
    footer{
      position: fixed;
      bottom: 0;
      width: 100%;
      .sub-block{
        border-top: 1px solid #d8d8d8;
        padding-left: 20/7.5vw;
        line-height: 100/7.5vw;
      }
      span{
        font-size: 20px;
        color: #F83534;
      }
      .pay-btn{
        width: 300/7.5vw;
        text-align: center;
        float: right;
        height: 100/7.5vw;
        background: #F83534;
        color: white;
      }
    }
    .address-pop{
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      position: fixed;
      background: white;
    }
  }


</style>
