<template>
  <div class="container place-order-panel page--loading" :class="{'page--finished': finished }">
    <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>
      <div class="info-list">
        <van-cell-group>
          <van-cell :value="couponInfo" @click="openCoupon">
            <div slot="title" class="cell-title">
              优惠券 <span class="text-red" v-if="selectCoupon.id">(已选择1张)</span>
            </div>
          </van-cell>
          <van-cell title="手机号码" :value="userPhone" />
          <van-cell v-if="specialCoupon" title="车牌号">
            <div @click="showCarNum = true">
              {{carNum || '请选择车牌号'}}
            </div>
          </van-cell>
        </van-cell-group>
      </div>
    </div>

    <van-submit-bar custom-class="price-bar" :price="price" button-text="去付款" :loading="payLoading" @submit="toPay"></van-submit-bar>

    <van-action-sheet overlay :show="showCoupons" @close="showCoupons = false">
      <div class="title-bar">
        <div class="not-use-coupon" @click="notUseCouponHandle()">不使用优惠券</div>
        <div class="title-text">选择优惠券</div>
        <div @click="showCoupons = false">
          <van-icon name="close" />
        </div>
      </div>
      <div class="select-coupon-tab">
        <van-tabs :active="activeVal" animated v-if="showCoupons">
          <van-tab title="可用优惠券">
            <scroll-view scroll-y class="tab-content">
              <div class="coupon-item" v-for="item in couponList.canUse" :key="item.id">
                <v-coupon :options="item" @use="useCoupon" :canUse="true" />
              </div>
              <div class="noData-con" v-if="couponList.canUse.length==0">
                <img class="logo-img" src="/static/img/empty-icon.png">
                <p>暂无数据</p>
              </div>
            </scroll-view>
          </van-tab>
          <van-tab title="不可用优惠券">
            <scroll-view scroll-y class="tab-content">
              <div class="coupon-item" v-for="item in couponList.notUse" :key="item.id">
                <v-coupon :options="item" @use="useCoupon" :status="false" />
              </div>
              <div class="noData-con" v-if="couponList.notUse.length==0">
                <img class="logo-img" src="/static/img/empty-icon.png">
                <p>暂无数据</p>
              </div>
            </scroll-view>
          </van-tab>
        </van-tabs>
      </div>
    </van-action-sheet>
    <car-num v-if="showCarNum" :code="carNum" @cancel="cancelCarNum" @ok="okCarNum"></car-num>
  </div>
</template>

<script>
import Coupon from '@/components/Coupon';
import { objToUrl } from '@/utils/index';
import { bundleById, wxPay, getPayStatus } from '@/api/bundle';
import { getCouponList } from '@/api/coupon';
import { getUserPhone } from '@/api/login';
import carNumCom from '@/components/LicensePlatNum';
import { subscribePayMessage, subscribeHxMessage } from '@/utils/index.js';
export default {
  components: { 'v-coupon': Coupon, 'car-num': carNumCom },
  name: 'packageDetail',

  computed: {
    couponInfo() {
      let { selectCoupon } = this;
      if (selectCoupon.id) {
        const id = Math.round(selectCoupon.id);
        if (id === 900015 || id === 900009) {
          return selectCoupon.typeName;
        } else {
          return `已经优惠${selectCoupon.amount}元`;
        }
      } else {
        return `共${this.couponList.canUse.length}张优惠券可用`;
      }
    },
    specialCoupon() {
      let { selectCoupon } = this;
      return Math.round(selectCoupon.id) === 900009;
    }
  },
  data() {
    return {
      payLoading: false,
      finished: false,
      showCarNum: false,
      carNum: '',
      list: {},
      bundle: {},
      activeVal: 0,
      couponList: {
        canUse: [],
        notUse: []
      },
      showCoupons: false,
      selectCoupon: {
        id: ''
      },
      customerCouponId: '',
      price: 0,
      userPhone: ''
    };
  },
  methods: {
    // 查询支付状态
    queryPayStatus (tradeNo){
        let _this = this
        getPayStatus({ tradeNo: tradeNo }).then(result => {
          wx.hideLoading();
          if (result.status === '200') {
            wx.redirectTo({ url: `/pages/paySuccess/main?` + objToUrl(result.data) });
          }else{
            setTimeout(function(){
              _this.queryPayStatus(tradeNo)
            },1000)
          }
        });
    },
    toPay() {
	    let _this = this
      const { id } = this.$mp.query;
      if (this.specialCoupon && !this.carNum) {
        wx.showToast({
          title: '请输入车牌号',
          icon: 'none',
          duration: 2500
        });
        return;
      }
      if (!this.specialCoupon) {
        this.carNum = '';
      }
      _this.payLoading = true
      //订阅消息
      subscribePayMessage(function(){
        wx.showLoading({
          mask: true,
          title: '加载中'
        });
        wxPay({
          'bundleId': id,
          'customerCouponId': _this.customerCouponId,
          'vehicleNumber': _this.carNum
        }).then(res => {
          if (res.status === '200') {
            _this.carNum = '';
            setTimeout(function(){
              _this.queryPayStatus(res.tradeNo)
            },500)
          } else {
            wx.hideLoading();
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 5000
            });
          }
          _this.payLoading = false
        }).catch(err => {
          console.log(err)
          let message = '请重新下单或联系客服处理!';
          if (err.errMsg === 'requestPayment:fail cancel') {
            message = '您取消了支付';
          }
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2500
          });
          wx.navigateTo({
            url: `/pages/orderDetail/main?id=${err.orderBundleId}`
          });
          _this.payLoading = false
        });
      })
    },
    useCoupon(obj) {
      this.customerCouponId = obj.id;
      this.selectCoupon = obj.coupon;
      this.computePrice();
      this.showCoupons = false;
    },
    notUseCouponHandle() {
      this.selectCoupon = {
        id: ''
      };
      this.customerCouponId = '';
      this.computePrice();
      this.showCoupons = false;
    },
    computePrice() {
      const { selectCoupon } = this;
      const id = Math.round(selectCoupon.id);
      if (id === 900015 || id === 900009) {
        this.price = selectCoupon.amount * 100;
      } else {
        if (selectCoupon.amount) {
          this.price = (this.bundle.price - selectCoupon.amount) * 100;
        } else {
          this.price = this.bundle.price * 100;
        }
      }
    },
    inputCarNo(val) {
      this.carno = val.mp.detail;
    },
    cancelCarNum() {
      this.showCarNum = false;
    },
    okCarNum(val) {
      this.carNum = val;
      this.showCarNum = false;
    },
    openCoupon() {
      this.activeVal = 0;
      this.showCoupons = true;
    }
  },

  onShow() {
    // 处理支付取消后返回默认选中优惠券显示问题
    this.selectCoupon = { id: '' };
    this.customerCouponId = '';
    wx.showLoading({
      mask: true,
      title: '加载中'
    });
    const _this = this;
    const { id, couponId, customerCouponId } = this.$mp.query;
    Promise.all([bundleById({ id }), getCouponList({
      bundleId: id,
      status: '1'
    }), getUserPhone({})]).then(res => {
      const bundleRes = res[0];
      const couponRes = res[1];
      const phoneRes = res[2];
      if (bundleRes.status === '200' && couponRes.status === '200' && phoneRes.status === '200') {
        _this.bundle = bundleRes.data;
        _this.price = _this.bundle.price * 100;
        _this.couponList.canUse = couponRes.data.filter(item => item.useEnableFlag === '1');
        if (_this.couponList.canUse.length && couponId) {
          let _coupon = '';
          if (customerCouponId) {
            _coupon = _this.couponList.canUse.find(item => item.id + '' === customerCouponId + '');
          } else {
            _coupon = _this.couponList.canUse.find(item => item.couponId + '' === couponId + '');
          }
          if (_coupon) {
            _this.useCoupon(_coupon);
          }
        }
        _this.couponList.notUse = couponRes.data.filter(item => item.useEnableFlag !== '1');
        _this.userPhone = phoneRes.data;
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2500
        });
      }
      _this.finished = true;
      wx.hideLoading();
    });
  },
  onUnload() {
    this.finished = false;
    this.showCarNum = false;
    this.carNum = '';
    this.list = {};
    this.bundle = {};
    this.activeVal = 0;
    this.showCoupons = false;
    this.selectCoupon = {};
    this.customerCouponId = '';
    this.price = 0;
    this.userPhone = '';
    this.couponList = {
      canUse: [],
      notUse: []
    };
  }
};
</script>

<style lang="stylus" >
.container {
  height: 100%;
  overflow: hidden;
}

.place-order-panel {
  .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: 10%;
      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;
      }
    }
  }

  .price-bar {
    box-shadow: 0 0 2rpx rgba(0, 0, 0, 0.1);
  }

  .info-list {
    font-size: 1.4em;

    .cell-title {
      display: flex;
    }

    .text-red {
      color: #ff5500;
    }
  }

  .tab-content {
    height: calc(60vh - 65px);
    width: 100vw;
    overflow: auto;
    box-sizing: border-box;

  }
  .noData-con{
    margin-top: 70rpx;
    text-align center;
    font-size: 26rpx;
    img{
      display: inline-block;
      width: 196rpx;
      height: 128rpx;
      margin: 20rpx 0 10rpx;
    }
  }
  .select-coupon-tab {
    height: 60vh;
  }

  .coupon-item {
    width: 100%;
    padding: 15rpx 20rpx;
    box-sizing: border-box;
  }

  .title-bar {
    display: flex;
    justify-content: space-between;
    align-content: center;
    padding: 25rpx;

    .not-use-coupon {
      font-size: 0.8em;
      color: #2d8cf0;
      text-decoration: underline;
      box-sizing: border-box;
    }

    .title-text {
      position: absolute;
      left: 0;
      right: 0;
      text-align: center;
      z-index: -1;
    }
  }
}
</style>
