<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">
        <div class="product-img" @click="toDetail">
          <img class="img" :src="bundle.icon2" alt="">
        </div>
        <div class="product-info">
          <div @click="toDetail">
            <div class="title">{{bundle.name}}</div>
            <div class="desc">{{bundle.tag}}</div>
          </div>
          <div>
            <div class="price">
              ￥{{bundle.price}}
            </div>
          </div>
        </div>
      </div>
      <div class="package-info" v-if="orderBundle.orderFlag === 'PAED'">
        <van-cell-group>
          <!-- <form @submit="formSubmit" class="formId"  report-submit="true">
            <button form-type="submit"></button>
          </form> -->
          <van-cell :title="item.itemName" :label="expiryDate?'过期时间：'+expiryDate:''" 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>
          </van-cell>
        </van-cell-group>
        <div class="package-info-desc">
          请将对应服务的二维码出示给门店进行消费
        </div>
      </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'">
            <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" />
      </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: {},
      coupon: undefined,
      orderBundle: {},
      customerBundleItemList: [],
      formId:null,
      expiryDate: null
    };
  },
  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: {
    // formSubmit (e){
    //   console.log(e)
    //   this.formId = e.target.formId
    //   this.showQRcode(e.target.id)
    // },
    // 核销订阅消息
    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.bundle = res.data.bundle;
          _this.coupon = res.data.coupon;
          _this.orderBundle = res.data.orderBundle;
          _this.customerBundleItemList = res.data.customerBundleItemList;
          _this.expiryDate = res.data.expiryDate ? res.data.expiryDate.substr(0,10) : null
        } 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);
    	  }
    	});
    },
    // 去支付
    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 = {};
    this.coupon = undefined;
    this.orderBundle = {};
    this.customerBundleItemList = [];
  }
};
</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;
}
.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%;
      }
    }

    .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 {
    .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;
    }
  }

  .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;
}

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