<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="top_border">
      <contact-box :limit="count"></contact-box>
    </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 ContactBox from './component/ContactBox.vue'
export default {
  name: 'ServiceCheckOrder',
  data () {
    return {
      date: '',
      period: '',
      count: 1,
      checked: false,
      useCard: '',
      orderDetail: '',
      selectCombo: '',//当前套餐信息
      showCourseData: '',//当前课程的信息
      selectCombo: '',//已选择的套餐
      userInfo: '',//支付用
    }
  },
  mounted () {
    let userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      this.userInfo = JSON.parse(userInfo);
    }

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

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

    // 如果有优惠券,就展示
    let useCard = localStorage.getItem('useCard')
    let showCourseData = localStorage.getItem('showCourseData')
    if (useCard) {
      this.useCard = JSON.parse(useCard)
    }
    if (showCourseData) {
      this.showCourseData = JSON.parse(showCourseData)
    }
    //判断是否为支付会跳,查询订单状态
    let outTradeNo = localStorage.getItem('outTradeNo')
    if (outTradeNo) {
      this.getOrderStatus(outTradeNo)
    }
  },
  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' })
    },
    // 创建订单
    createOrder () {
       // 出行人数量判断
      let selectedContactArr = localStorage.getItem('selectedContactArr');
      selectedContactArr = JSON.parse(selectedContactArr);
      if (selectedContactArr.length != this.count) {
        this.$toast.fail('请选择与购买商品数量相同的出行人数');
        return;
      }

      // 协议勾选
      if (!this.checked) {
        this.$toast.fail('请先阅读并同意用户协议');
        return;
      }

      // 出行人字段格式
      let selectedContact = []
      for (let i in selectedContactArr) {
        selectedContact.push(selectedContactArr[i].travelerNum)
      }
      selectedContact = selectedContact.join(',')
      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,
        },
        onSuccess: res => {
          if (res.data.data) {
            if (this.paymoney == 0) {
              // 使用后移除优惠券,防止返回继续使用
              localStorage.removeItem('useCard')
              this.$router.push({ name: 'ServiceOrderXST', query: { active: 1, showChatGroupUrl: 1 } })

            } else {
              // 使用后移除优惠券,防止返回继续使用
              localStorage.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) {
      const sUserAgent = window.navigator.userAgent.toLowerCase()
      const Jupiter = sUserAgent.indexOf("Jupiter") > -1
      if (Jupiter) {
        alert('App')
        // console.log('App')
        // this.mgop({
        //   api: 'mgop.sz.hswsy.appPay', // 必须
        //   host: 'https://mapi.zjzwfw.gov.cn/',
        //   dataType: 'JSON',
        //   type: 'POST',
        //   appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        //   headers: {
        //     //   'isTestUrl': '1'
        //   },
        //   data: {
        //     "appid": "2021002189681626",
        //     "attach": "string1",
        //     "body": "string23",
        //     "notify_url": "http://47.110.50.251:9091/api/alipay/pay",
        //     "outTradeNo": new Date().getTime(),
        //     "payType": 0,
        //     "payWay": 0,
        //     "productId": "11",
        //     "quit_url": location.href,
        //     "subject": "string",
        //     "totalFee": "0.01",
        //   },
        //   onSuccess: res => {
        //     console.log(res)
        //     this.BridgePay(res.data.message)
        //   },
        //   onFail: err => {
        //     console.log('err', err)
        //   }
        // });
      } else {
        // alert('H5')
        console.log('h5')
        this.mgop({
          api: 'mgop.sz.hswsy.mobilePay', // 必须
          host: 'https://mapi.zjzwfw.gov.cn/',
          dataType: 'JSON',
          type: 'POST',
          appKey: 'fuxgnukl+2001895516+edccpx', // 必须
          headers: {
            //   'isTestUrl': '1'
          },
          data: {
            "appid": "2021002189681626",
            "attach": this.showCourseData.course_name + '_' + this.date,
            "body": this.showCourseData.course_name + '_' + this.date,
            "notify_url": "https://yanxue.myjxt.com/api/Manage/AlipayBackInfo",
            "outTradeNo": data.trade_no,
            "payType": 0,
            "payWay": 0,
            "productId": this.showCourseData.id, //商品id
            "quit_url": location.href,
            "subject": this.showCourseData.course_name + '_' + this.date,
            "totalFee": this.selectCombo.actualPrice * 1000 * this.count / 1000
          },
          onSuccess: res => {
            console.log(res)
            localStorage.setItem('outTradeNo', data.trade_no)
            // this.BridgePay(res.data.message)
            let divForm = document.getElementsByTagName('divform')
            if (divForm.length) {
              document.body.removeChild(divForm[0])
            }
            const div = document.createElement('divform')
            div.innerHTML = res.data.message // res.data就是sb支付宝返回给你的form
            document.body.appendChild(div)
            // document.forms[0].setAttribute('target', '_blank') // 加了_blank可能出问题所以我注释了
            document.forms[0].submit()
          },
          onFail: err => {
            console.log('err', err)
          }
        });
      }
    },
    // 支付API
    // BridgePay (credential) {
    //   var payMsg = {
    //     platform: 1,
    //     arg: {
    //       "credential": credential,
    //       "inSandBox": false
    //     }
    //   };
    //   ZWJSBridge.pay(payMsg).then((result) => {

    //     alert('支付成功!');
    //     console.log('#### ZWJSBridge.pay() result:' + result);

    //   }).catch((error) => {
    //     var errorMsg = JSON.stringify(error);
    //     alert('支付失败:' + errorMsg);
    //     console.log('#### ZWJSBridge.pay() error:' + error);
    //   });
    // },
    //判断是否为支付会跳,查询订单状态
    getOrderStatus (outTradeNo) {
      console.log('getOrderStatus')
      this.$toast.loading()
      this.mgop({
        api: 'mgop.sz.hswsy.IsPayByTradNo', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "tradNo": outTradeNo,
        },
        onSuccess: res => {
          console.log(res)
          this.$toast.clear()
          localStorage.removeItem('outTradeNo')
          // 如果已支付就跳转
          if (res.data.data) {
            localStorage.removeItem('selectedContactArr')
            this.$router.push({ name: 'ServiceOrderXST', query: { active: 1, showChatGroupUrl: 1 } })
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });
    }
  },
  components: {
    ContactBox
  }
}
</script>
<style lang="scss" scoped>
#checkOrder {
  padding-bottom: 260px;
  .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>
<style lang="scss">
.elder {
  #checkOrder {
    .goods_data {
      .top {
        img {
          width: 200px;
          height: 200px;
        }
        div {
          width: 470px;
        }
        .goods_title {
          font-size: 40px;
        }
        .package_name {
          font-size: 36px;
        }
        .count {
          font-size: 36px;
        }
      }
      .bottom {
        .time {
          font-size: 36px;
        }
        .price {
          font-size: 36px;
          span {
            font-size: 32px;
          }
        }
      }
    }
    .card {
      font-size: 40px;
    }
    .protocol {
      font-size: 36px;
    }
    .Collection {
      .box1 p {
        font-size: 56px;
        span {
          font-size: 40px;
        }
        del {
          font-size: 40px;
        }
      }
      .box > span {
        font-size: 44px;
      }
    }
  }
}
</style>