<template>
  <div id="checkOrder">
    <div class="goods_data top_border">
      <div class="top">
        <img src="@/assets/service/school_bg.png" alt="">
        <div>
          <p class="goods_title">{{showCourseData.course_name}}</p>
          <p class="package_name">套餐名称：{{selectCombo.comboName}}</p>
          <p class="count">数量：x{{count}}</p>
        </div>
      </div>
      <div class="bottom">
        <p class="time">使用时间： {{date}}</p>
        <p class="price"><span>¥</span>{{selectCombo.actualPrice*1000*count/1000}}</p>
      </div>
    </div>
    <div class="card top_border" v-if="selectCombo.actualPrice>0" @click="openCardBox">
      <p>可用优惠券</p>
      <div>
        <span class="use_card" v-if="useCard">已使用红包抵扣{{useCard.couponPrice}}</span>
        <van-icon name="arrow" />
      </div>
    </div>
    <div class="card top_border" v-if="selectedContactArr.length==0" @click="enterSelectContact">
      <p>出行人</p>
      <span style="color:#999;font-weight:normal;">*请添加活动出行人</span>
    </div>
    <div class="card top_border" v-for="(item,index) in selectedContactArr" :style="index>0?'border-top:0':''" :key="index" @click="enterSelectContact">
      <p>{{index==0?'出行人':''}}</p>
      <span style="color:#999;font-weight:normal;">{{item.travelerName}} {{item.travelerMobile}}</span>
    </div>
    <div class="card top_border">
      <p>服务承诺和保障</p>
      <van-icon name="arrow" />
    </div>
    <div class="protocol">
      <van-checkbox v-model="checked" shape="square" icon-size="16px">我已阅读并同意 </van-checkbox>
      <span style="text-decoration: underline;" @click="goPayneed">购买须知</span> <span style="text-decoration: underline;" @click="goProtocol">用户协议</span>
    </div>
    <div class="Collection">
      <div class="box box1">
        <p><span>¥</span>{{paymoney}} <del>{{selectCombo.productPrice*1000*count/1000}}</del></p>
        <p class="coupon" v-if="useCard">优惠券已抵用：{{useCard.couponPrice}}</p>
      </div>
      <div class="box box2" v-if="userInfo">
        <span @click="createOrder()">支付</span>
      </div>
    </div>
  </div>
</template>
<script>
import Axios from 'axios';
import wx from 'weixin-js-sdk';
export default {
  name: 'ServiceCheckOrder',
  data () {
    return {
      date: '',
      period: '',
      count: 1,
      checked: false,
      useCard: '',
      orderDetail: '',
      selectCombo: '',//当前套餐信息
      showCourseData: '',//当前课程的信息
      selectCombo: '',//已选择的套餐
      publicName: '',
      userInfo: '',//支付用
      appId: '',
      selectedContactArr: [],//选择的出行人
      selectedContact: '',
    }
  },
  mounted () {
    let publicName = sessionStorage.getItem('publicName');
    if (publicName) {
      this.publicName = publicName
      if (publicName == 'SXYX') {
        this.appId = 'wx1305e88d2bc74073'
      } else if (publicName == 'XST') {
        this.appId = 'wx1c630c8773c482f1'
      } else if (publicName == 'KQ') {
        this.appId = 'wx1305e88d2bc74073'
      }
    }
    let userInfo = sessionStorage.getItem('userInfo');
    if (userInfo) {
      this.userInfo = JSON.parse(userInfo);
    }

    // 选择的出行人
    let selectedContactArr = sessionStorage.getItem('selectedContactArr');
    if (selectedContactArr) {
      selectedContactArr = JSON.parse(selectedContactArr);
      this.selectedContactArr = selectedContactArr
      let selectedContact = []
      for (let i in selectedContactArr) {
        selectedContact.push(selectedContactArr[i].travelerNum)
      }
      this.selectedContact = selectedContact.join(',')
    }

    this.date = this.$route.query.date;
    this.count = this.$route.query.count;
    this.period = this.$route.query.period;

    // 套餐
    let selectCombo = sessionStorage.getItem('selectCombo')
    if (selectCombo) {
      this.selectCombo = JSON.parse(selectCombo)
    }

    // 如果有优惠券，就展示
    let useCard = sessionStorage.getItem('useCard')
    let showCourseData = sessionStorage.getItem('showCourseData')
    if (useCard) {
      this.useCard = JSON.parse(useCard)
    }
    if (showCourseData) {
      this.showCourseData = JSON.parse(showCourseData)
    }
  },
  computed: {
    paymoney () {
      let paymoney = (this.selectCombo.actualPrice * 1000 * this.count - (this.useCard.couponPrice * 1000 || 0)) / 1000;
      if (paymoney < 0) paymoney = 0;
      return paymoney
    }
  },
  methods: {
    // 进入选择优惠券
    openCardBox () {
      this.$router.push({ name: 'ServiceCardSelect' })
    },
    //购买须知
    goPayneed () {
      this.$router.push({ name: 'payneed' })
    },
    // 前往查看协议
    goProtocol () {
      this.$router.push({ name: 'protocol' })
    },
    // 选择联系人
    enterSelectContact () {
      this.$router.push({ name: 'SelectContact', query: { limit: this.count } })

    },
    // 创建订单
    createOrder () {
      if (this.selectedContactArr.length != this.count) {
        this.$toast.fail('请选择与购买商品数量相同的出行人数');
        return;
      }
      if (!this.checked) {
        this.$toast.fail('请先阅读并同意用户协议');
        return;
      }
      this.mgop({
        api: 'mgop.sz.hswsy.AddOrderPay', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "courseId": this.showCourseData.id,
          "payway": 2,
          "paymoney": this.paymoney,//时段个数*单价*人数-优惠券
          "userId": this.userInfo?.centerNo,//升学汇和其他端接口字段不同
          "orderCount": this.count,//人数
          "orderTime": this.date,//时段集合 2018-10-15 
          "comboId": this.selectCombo.id,
          "dateBindComboId": this.selectCombo.dateBindComboId,
          "unionId": this.userInfo?.centerNo,
          "price": this.selectCombo.actualPrice * 1000 * this.count / 1000,//商品减掉优惠券之前的价格
          "travelNum": this.selectedContact,//出行人编号
          "couponId": this.useCard?.id || 0,
          "appId": this.appId
        },
        onSuccess: res => {
          if (res.data.data) {
          if (this.paymoney == 0) {
            // 使用后移除优惠券，防止返回继续使用
            sessionStorage.removeItem('useCard')
              this.$router.push({ name: 'ServiceOrderXST', query: { active: 1, showChatGroupUrl: 1 } })

          } else {
            // 使用后移除优惠券，防止返回继续使用
            sessionStorage.removeItem('useCard')
            this.openPay(res.data.data);
            this.orderId = res.data.data.orderId;
          }
        } else {
          this.$toast.fail(res.data?.result);
        }

        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },
    openPay (data) {
      let that = this;
      alert('支付')
      return;

      Axios({

        url: 'https://proxy.shunzhi.net/prod/api/wx/pay/' + this.appId + '/1614900216',
        method: 'post',
        headers: { 'Content-Type': 'application/json;charset=UTF-8' },
        data: {
          notify_url: `https://yanxue.myjxt.com/api/Manage/WxBackInfo`,
          body: this.showCourseData.course_name + '_' + this.date,
          openId: this.openId, //'oHHbojor4C_gR96lxxFUeYTrY0Uc'
          outTradeNo: data.trade_no, //订单号
          productId: this.showCourseData.id, //商品id
          totalFee: this.paymoney * 100, //钱
          subject: '研学产品'
          // comeType: 9999
        }
      }).then((res) => {          //这里使用了ES6的语法
        console.log('微信支付配置：', res.data.data)
        let obj = res.data.data
        wx.config({
          "debug": false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          "appId": obj.appId, // 必填，公众号的唯一标识
          "timestamp": obj.timeStamp, // 必填，生成签名的时间戳
          "nonceStr": obj.nonceStr, // 必填，生成签名的随机串
          "signature": obj.paySign, // 必填，签名，见附录1
          "jsApiList": ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(function () {
          console.log('ready')
          wx.chooseWXPay({
            "timestamp": obj.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
            "nonceStr": obj.nonceStr, // 支付签名随机串，不长于 32 位
            // "package": obj.packageValue, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
            "package": 'prepay_id=' + obj.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
            "signType": obj.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
            "paySign": obj.paySign, // 支付签名
            success: function (res) {
              // 支付成功后的回调函数
              console.log('成功回调函数:'.error)
              // if (that.useCard) {
              //   that.useCoupon()
              // } else {
              sessionStorage.removeItem('selectedContactArr')

              // 此处应跳转我的订单
              if (that.publicName == 'SXYX' || that.publicName == 'XST' || that.publicName == 'KQ') {
                that.$router.push({ name: 'ServiceOrderXST', query: { active: 1, showChatGroupUrl: 1 } })
              } else {
                that.$router.push({ name: 'ServiceOrderPublic' })
              }
              // }

            },
            fail: function (error) {
              //失败回调函数
              console.log('失败回调函数:'.error)
              that.$toast.fail(error.message);
            }
          });
        });
        wx.error(function (res) {
          console.log('err', res)
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
          this.$toast.fail('config信息验证失败');
        });
      }).catch((error) => {
        console.log(error)      //请求失败返回的数据
      })
    },
  }
}
</script>
<style lang="scss" scoped>
#checkOrder {
  .top_border {
    border-top: 16px solid #f6f7fa;
  }
  .goods_data {
    padding: 0 22px;
    .top {
      padding: 20px 0;
      img {
        display: inline-block;
        width: 124px;
        height: 124px;
        border-radius: 8px;
      }
      div {
        vertical-align: top;
        display: inline-block;
        margin-left: 20px;
        width: 560px;
      }
      p {
        margin: 0;
      }
      .goods_title {
        font-size: 28px;
        font-weight: bold;
      }
      .package_name {
        font-size: 24px;
        margin-top: 18px;
      }
      .count {
        font-size: 24px;
      }
    }
    .bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 28px 0;
      border-top: 2px solid #f2f4f9;
      .time {
        font-size: 28px;
      }
      .price {
        font-size: 32px;
        font-weight: bold;
        span {
          font-size: 20px;
        }
      }
    }
  }
  .card {
    padding: 0 22px;
    height: 98px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28px;
    font-weight: bold;
    .use_card {
      font-size: 26px;
      color: #f64c37;
      // padding: 2px 24px;
      // background: #ffecc0;
      // border-radius: 8px;
      margin-right: 10px;
      font-weight: normal;
    }
  }
  .protocol {
    display: flex;
    align-items: center;
    padding: 0 22px;
    font-size: 24px;
    span {
      color: #3f92ff;
      margin: 0 4px;
    }
  }
  .Collection {
    background-color: white;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 28px 22px;
    box-sizing: border-box;
    padding-bottom: 50px;
    z-index: 500;
    box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.34);

    .box {
      display: inline-block;
      vertical-align: middle;
      color: #666666;
      .icon {
        display: inline-block;
        width: 45%;
        text-align: center;
        font-size: 24px;
        p {
          // margin: 0;
          color: #999999;
          margin-top: 8px;
        }
        i {
          font-size: 48px;
          color: rgb(45, 45, 45);
          font-weight: bold;
        }
      }

      > span {
        display: inline-block;
        width: 100%;
        line-height: 92px;
        box-sizing: border-box;
        border-radius: 100px;
        color: white;
        font-size: 32px;
        background: #4092ff;
        text-align: center;
        box-shadow: 0px 10px 40px 0px #a0c9ff;
        b {
          display: inline-block;
          vertical-align: middle;
          margin-left: 20px;
          color: white;
        }
        i {
          vertical-align: middle;
          font-size: 44px;
          font-weight: bold;
        }
      }
    }
    .box1 {
      width: 40%;
      p {
        font-size: 49px;
        font-weight: bold;
        color: #f64c37;
      }
      span {
        font-size: 32px;
      }
      del {
        font-size: 20px;
        color: #999;
      }
      .coupon {
        font-size: 24px;
        color: #999;
      }
    }
    .box2 {
      width: 60%;
    }
  }
}
::v-deep .van-calendar__bottom-info {
  color: #f95555;
}
::v-deep .van-calendar__selected-day {
  background: #ecf2fc !important;
  border: 4px solid #79abff;
  box-sizing: border-box;
  color: #333;
}
.van-checkbox {
  display: inline-flex;
}
</style>