<template>
  <div class="order-detail-container">
    <div class="order-detail-panel page--loading" :class="{'page--finished': finished }">
      <div class="order-status">
        <h3 class="title">{{getTitle}}</h3>
        <span class="desc" v-if="orderBundle.orderFlag == 'CAEL' || orderBundle.orderFlag == 'SYCA' ">取消原因: {{getPayStatusFun}}</span>
      </div>
      <div class="content" @click="toDetail">
        <div class="product-img" >
          <img v-if="bundle.icon2" class="img" :src="bundle.icon2" alt="">
          <div v-else class="center-con">
            <img class="img" src="/static/img/ic_shop_title_06.png" alt="">
          </div>
        </div>
        <div class="product-info">
          <div>
            <div class="title">{{detailData ? detailData.bundleName : ''}}</div>
            <div class="desc">{{bundle.tag ? bundle.tag : ''}}</div>
          </div>
        </div>
      </div>
      <div class="package-info" v-if="orderBundle.orderFlag === 'PAED'">
        <div v-for="item in customerBundleItemList" :key="item.id" :id='item.id' @click="subscribeMessage" class="info-item">
          <div class="item-itemName">
            <div>{{item.itemName}}</div>
            <div class="package-qr">
              <span style="color: #999;">剩余{{item.remainTimes}}次</span>
              <van-icon class="icon-qr" size="1.5em" name="qr" color="#ff5500" />
            </div>
          </div>
          <div style="color: #999;font-size: 12px;">{{(item.expiryDateStr ? item.expiryDateStr  :'') + ( item.expiryTimesStr ?  '（'+item.expiryTimesStr+'）' :'')}}</div>
        </div>
        <!-- <van-cell-group>
          <!-- <form @submit="formSubmit" class="formId"  report-submit="true">
            <button form-type="submit"></button>
          </form> -->
          <!--<van-cell :title="item.itemName" v-for="item in customerBundleItemList" :key="item.id" :id='item.id' is-link @click="subscribeMessage">
            <div class="package-qr">
              <span>剩余{{item.remainTimes}}次</span>
              <van-icon class="icon-qr" size="1.5em" name="qr" color="#ff5500" />
            </div>
            <div class="package-expiryDate">{{(item.expiryDateStr ? item.expiryDateStr :'')+(item.expiryTimesStr? (item.expiryTimesStr):'')}}</div>
          </van-cell>
        </van-cell-group> -->
        <div class="package-info-desc">
          请将对应服务的二维码出示给门店进行消费
        </div>
      </div>
      <!-- 已支付 -->
      <div class="look-record" v-if="orderBundle.orderFlag === 'PAED'" @click="goPage">
        查看使用记录
      </div>
      <div class="order-infos">
        <van-cell-group>
          <van-cell title="订单编号" :value="orderBundle.number" class="order-number">
          </van-cell>
          <van-cell title="下单时间">
            <div style="font-size:0.95em">{{orderBundle.orderDate}}</div>
          </van-cell>
          <van-cell title="车牌号" v-if="orderBundle.vehicleNumber">
            <span>{{orderBundle.vehicleNumber}}</span>
          </van-cell>
          <!-- <van-cell title="支付方式" value="2" /> -->
          <!-- <van-cell title="套餐售价">
            <span class="price">￥{{orderBundle.payedAmount}}</span>
          </van-cell> -->
          <van-cell title="优惠券" v-if="orderBundle.couponAmount > 0">
            <span class="price">￥-{{orderBundle.couponAmount}}</span>
          </van-cell>

          <van-cell title="实付款" v-if="orderBundle.orderFlag === 'PAED'||orderBundle.orderFlag === 'RUND'">
            <span class="price">￥{{orderBundle.payedAmount}}</span>
          </van-cell>
          <van-cell title="待付款" v-else>
            <span class="price">￥{{orderBundle.totalAmount}}</span>
          </van-cell>
        </van-cell-group>
      </div>
      <div class="order-control" v-if="orderBundle.orderFlag === 'UNPA'">
        <van-button class="btn" plain size="large" @click="cancelHandler">取消订单</van-button>
        <!-- <van-button class="btn" size="large" type="danger" :disabled="payLoading" :loading="payLoading" @click="toPay">立即支付</van-button> -->
      </div>
      <!-- <div class="order-control" v-if="orderBundle.orderFlag === 'CAEL' || orderBundle.orderFlag === 'SYCA'">
        <van-button class="btn" size="large" type="danger" @click="rePay">重新购买</van-button>
      </div> -->
      <!-- <div class="order-control" v-if="orderBundle.orderFlag === 'PAED'">
        <van-button class="btn" size="large" type="danger" @click="rePay">再次购买</van-button>
      </div> -->
    </div>
    <van-popup :show="showQRcodePopup" @close="closePopup">
      <div class="qrcode-panel">
        <canvas class="qrcode-img" canvas-id="mycanvas" />
        <p class="qrcode-des">二维码有效期24小时</p>
      </div>
    </van-popup>
  </div>
</template>

<script>
import QR from '@/utils/qrcode';
import { orderDetail, getQRCode, cancelOrder, wxPay, getPayStatus } from '@/api/bundle';
import { subscribePayMessage, subscribeHxMessage } from '@/utils/index.js';
export default {
  components: {},
  name: 'package',
  data() {
    return {
      payLoading: false,
      finished: false,
      showQRcodePopup: false,
      bundle: {
        icon2: null,
        name: '',
        tag: null,
        price: 0
      },
      coupon: undefined,
      orderBundle: {},
      customerBundleItemList: [],
      formId:null,
      detailData: null,
      bundleType:'',  // 0： 套餐 1：非套餐
	  itemBundleId:'' // 套餐id
    };
  },
  computed: {
    getPayStatusFun() {
      const dict = {
        'UNPA': '未支付',
        'INPA': '支付中',
        'PAED': '已支付',
        'CAEL': '用户手动取消',
        'SYCA': '超时未支付'
      };
      return dict[this.orderBundle.orderFlag];
    },
    getTitle() {
      const dict = {
        'UNPA': '未支付',
        'INPA': '支付中',
        'PAED': '已支付',
        'CAEL': '已取消',
        'SYCA': '已取消',
        'RUND': '已退款'
      };
      return dict[this.orderBundle.orderFlag];
    }
  },
  methods: {
    // 套餐查看详情
    toDetail(){
      console.log(this.itemBundleId,'this.itemBundleId','----------套餐id')
      if(this.bundleType==0){
        wx.navigateTo({
          url: `/pages/bundleDetail/main?id=${this.itemBundleId}`
        })
      }
    },
    // 核销订阅消息
    subscribeMessage(e){
      console.log(e)
      this.formId = ''
      this.showQRcode(e.currentTarget.id)
      // 发起订阅
      subscribeHxMessage(function(){})
    },
    cancelHandler() {
      const { id } = this.$mp.query;
      const _this = this;
      cancelOrder({
        id: id
      }).then(res => {
        if (res.status === '200') {
          _this.getOrderInfo(id);
        }
      });
    },
    closePopup() {
      console.log(1111)
      const { id } = this.$mp.query;
      this.showQRcodePopup = false;
      this.getOrderInfo(id);
    },
    showQRcode(itemId) {
      const { bundle } = this;
      const _this = this;
      const _size = this.setCanvasSize();

      getQRCode({
        'bundleId': bundle.id,
        'customerBundleItemId': itemId,
        'formId': this.formId
      }).then(res => {
        if (res.status === '200') {
          _this.showQRcodePopup = true;
          // QR.api.draw('123123', 'mycanvas', 300, 300);
          QR.api.draw(res.data, 'mycanvas', _size.w, _size.h);
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2500
          });
        }
      });
    },
    setCanvasSize: function() {
      var size = {};
      const res = wx.getSystemInfoSync();
      const width = res.windowWidth * 0.75;
      const height = width; // canvas画布为正方形
      size.w = width;
      size.h = height;
      return size;
    },
    getOrderInfo(id) {
      const _this = this;
      orderDetail({ id: id}).then(res => {
        if (res.status === '200') {
          _this.detailData = res.data || null
          _this.bundle = res.data.bundle || {icon2: null, name: '', tag: null, price: 0};
          _this.coupon = res.data.coupon;
          _this.orderBundle = res.data.orderBundle;
          _this.bundleType=res.data.freeChoiceFlag
		  _this.itemBundleId=res.data.bundleId
          res.data.customerBundleItemList.map(item => {
            if((item.expiryDate && (item.expiryDate.substr(0,10) != '2099-01-01')) && item.cycleFlag== 0){
              item.expiryDateStr = '过期时间：' + item.expiryDate
            }
            if(item.expiryTimes && item.expiryTimes!=0){
              item.expiryTimesStr='已过期'+item.expiryTimes+'次'
            }
            // if(item.expiryDate && (item.expiryDate.substr(0,10) != '2099-01-01') && item.cycleFlag== 0){
            //   item.expiryDateStr = '过期时间：' + item.expiryDate
            // }else{
            //   item.expiryDateStr = '过期时间：' + '--'
            // }
          })
          _this.customerBundleItemList = res.data.customerBundleItemList
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 2500
          });
        }
        _this.finished = true;
        wx.hideLoading();
      });
    },
    rePay() {
      wx.navigateTo({
        url: `/pages/bundleDetail/main?id=${this.orderBundle.bundleId}`
      });
    },
    // 查询支付状态
    queryPayStatus (tradeNo,id){
    	getPayStatus({ tradeNo: tradeNo }).then(result => {
        wx.hideLoading()
    	  if (result.status === '200') {
    	    this.getOrderInfo(id);
    	  }
    	});
    },
    //  查看使用记录
    goPage(){
      wx.navigateTo({
        url: `/pages/pagesA/usageRecord/main?billNo=${this.detailData.orderBundleNo}`
      })
    },
    // 去支付
    toPay() {
      let _this = this
      if(this.payLoading){return}
      const { id } = this.$mp.query;
      this.payLoading = true
      // 订阅支付消息
      subscribePayMessage(function(res){
		  wx.showLoading({title:'正在支付中...'})
		  wxPay({
		    id: id
		  }).then(res => {
		    if (res.status === '200') {
		      setTimeout(function(){
		        _this.queryPayStatus(res.tradeNo,id)
		      },500)
		    } else {
		      wx.showToast({
		        title: res.message,
		        icon: 'none',
		        duration: 2500
		      });
		    }
		    _this.payLoading = false
		  }).catch(err => {
		    let message = '支付失败!';
		    if (err.errMsg === 'requestPayment:fail cancel') {
		      message = '您取消了支付';
		    }
		    wx.showToast({
		      title: message,
		      icon: 'none',
		      duration: 2500
		    });
		    _this.payLoading = false
		  });
	  })
    }
  },
  onShow() {
    wx.showLoading({
      mask: true,
      title: '加载中'
    });
    const { id } = this.$mp.query;
    this.getOrderInfo(id);
  },
  onUnload() {
    wx.hideLoading();
    this.finished = false;
    this.showQRcodePopup = false;
    this.bundle = {
      icon2: null,
      name: '',
      tag: null,
      price: 0
    };
    this.coupon = undefined;
    this.orderBundle = {};
    this.customerBundleItemList = [];
    this.detailData = null
  }
};
</script>

<style lang="stylus" scoped>
.order-detail-container {
  min-height: 100vh;
  background-color: #f8f8f9;
}
.formId{
  margin-bottom: 10px;
  display: block;
}
.formId button{
  background:none;
  border:none;
  padding:0;
}
.look-record{
  margin: 10rpx 0;
  font-size: 28rpx;
  font-weight: bold;
  background-color: #fff;
  line-height: 72rpx;
  text-align center;
}
.order-detail-panel {
  font-size: 30rpx;

  .order-status {
    text-align: center;
    margin-bottom: 10rpx;
    background-color: #fff;
    padding: 15rpx 0;

    .title {
      color: #ff5500;
      font-weight: bold;
      font-size: 1.2em;
      padding-bottom: 10rpx;
    }

    .desc {
      color: #80848f;
      font-size: 0.85em;
    }
  }

  .content {
    display: flex;
    width: 100%;
    height: 250rpx;
    box-sizing: border-box;
    padding: 25rpx 20rpx;
    background-color: #fff;

    .product-img {
      width: 35%;

      img {
        width: 100%;
        height: 100%;
      }
      .center-con{
        text-align: center;
        height: 100%;
        img{
          display: inline-block;
          width: 204rpx;
          height: 100%;
        }
      }
    }

    .product-info {
      padding-left: 1em;
      box-sizing: border-box;
      font-size: 25rpx;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .title {
        font-size: 1.2em;
        padding: 10rpx 0;
      }

      .desc {
        color: #80848f;
        font-size: 0.85em;
      }

      .price {
        font-size: 1.2em;
        font-weight: bold;
      }
    }
  }

  .package-info, .order-infos {
    padding: 0 20rpx;
    background-color: #fff;
  }

  .package-info {
    .info-item{
      padding :15rpx 0;
      border-bottom :1px solid #eee
      .item-itemName{
        display :flex;
        justify-content :space-between;
        align-items :center
        .package-qr {
          display: flex;
          align-items: flex-start;
          justify-content: flex-end;

          .icon-qr {
            margin: 0 20rpx;
            position: relative;
            top: 1px;
          }
        }
      }
    }
    .package-info-desc {
      font-size: 25rpx;
      background-color: #fff;
      text-align: center;
      padding: 25rpx 0;
    }
    .package-expiryDate{
      text-align :start
    }
  }

  .order-infos {
    margin-top: 10rpx;

    .price {
      color: #ff5500;
      font-weight: bold;
    }
  }

  .order-control {
    display: flex;
    margin-top: 30rpx;
    padding: 0 20rpx;

    .btn {
      flex: 1;
    }

    .btn + .btn {
      margin-left: 20rpx;
    }
  }
}

.qrcode-img {
  width: 75vw;
  height: 75vw;
  background-color: #fff;
}
.qrcode-des{
  text-align: center;
  font-size: 26rpx;
  padding: 25rpx 0;
  background-color: #f4f4f5;
}

.order-number {
  /deep/ .van-cell__value {
    overflow: visible !important;
  }
}
</style>
