<template>
  <div class="mainPage">
    <div class="content">
      <h2>确认下单信息</h2>
      <div class="list flex-h">
        <div class="flex-item">
          <ul>
            <li class="flex-h" v-for="(item,index) in orderInfo" :key="index">
              <div class="flex-item">
                <div><span>{{item.name}}</span></div>
              </div>
              <div class="flex-item">
                <div><span>{{item.specname}}</span></div>
              </div>
              <div class="flex-item">
                <div><span>x{{item.num}}</span></div>
              </div>
              <div class="flex-item">
                <div><span>￥{{item.price * item.num}}</span></div>
              </div>
            </li>
            <li class="flex-h">
              <div class="flex-item">
                <div><span>选择商品券</span></div>
              </div>
              <a class="active" v-if="getCouponOff && couponList.length" @click="showSelectCouponLayer = true">
                <span>{{postData.customercouponid === '' ? '有' + couponList.length + '张优惠券可选' : '已选择优惠券'}}</span>
                <i class="iconfont icon-jiantou-right"></i>
              </a>
            </li>
          </ul>
        </div>
      </div>
      <h6>添加备注</h6>
      <div class="remark flex-h">
        <div class="flex-item flex-h">
          <div class="flex-h">
            <textarea class="flex-item" cols="30" rows="6" v-model="postData.info.Remark"></textarea>
          </div>
        </div>
      </div>
      <span>下单人：{{userInfo.customer.CustomerName}} {{userInfo.customer.Phone}}</span>
      <div class="bottom">
        <a @click="cancel">取消</a>
        <a @click="toPayer">确定</a>
        <div style="width: 100%;position: absolute;left: 0;bottom: 0;top: 0;" v-if="!ajaxoff"></div>
      </div>
    </div>
    <div class="selectCouponLayer" :class="{'show': showSelectCouponLayer}">
      <div class="flex-v">
        <div>
          <i class="iconfont icon-guanbi" @click="showSelectCouponLayer = false"></i>
        </div>
        <div class="flex-item">
          <div class="flex-h">
            <div class="flex-item" style="margin: 0 .2rem;">
              <ul>
                <li v-for="(item,index) in couponList" :key="index" @click="selectCouponItem(item)" :class="{'active':item.select}">
                  <i class="iconfont icon-gouxuan"></i>
                  <discounts :data="item"></discounts>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <a @click="sureSelectCoupon">确定</a>
      </div>
    </div>
    <div class="successPopup" v-if="showSuccessPopup">
      <div>
        <i class="iconfont icon-gou"></i>
        <div class="text">出单成功</div>
        <div class="back" @click="popBack">返回等待</div>
      </div>
    </div>
    <!-- <div class="layerBg" :class="{'active': !ajaxoff}"></div> -->
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: caseTableActions } = createNamespacedHelpers('placeOrderForCoffee')
import discounts from '../../../components/discounts/discounts'
export default {
  name: '',
  data () {
    var _self = this
    return {
      ajaxoff: true,
      showSelectCouponLayer: false,
      getCouponOff: false,
      couponList: [], // 优惠券列表
      showSuccessPopup: false,
      postData: {
        info: {
          CaseId: decodeURI(_self.$route.query.caseid),
          AreaId: decodeURI(_self.$route.query.areaid),
          AreaName: decodeURI(_self.$route.query.areaname),
          TableId: decodeURI(_self.$route.query.tableid),
          TableNo: decodeURI(_self.$route.query.tableno),
          Amount: 0, // 订单金额
          OrdersNum: 0,
          Remark: '',
        },
        detail: [],
        customercouponid: ''
      },
      ticketList: [{
        value: '优惠券1',
        id: '1',
      }, {
        value: '优惠券2',
        id: '2',
      }, {
        value: '优惠券3',
        id: '3',
      }],
      orderInfo: JSON.parse(_self.$route.query.info) || []
    }
  },
  components: {
    discounts,
  },
  computed: {
    ...mapState({
      userInfo: x => x.userCenter.userInfo,
      orgId: x => x.app.orgId,
    })
  },
  created () {
    this.getCouponList().then((res) => {
      // console.log(JSON.stringify(res))
      var id = JSON.parse(this.$route.query.info)[0].id, arr = [], nowDate = Date.now()
      res = res || []
      for (var n = 0; n < res.length; n++) {
        res[n].Coupon.Targets = res[n].Coupon.Targets || []
        if (res[n].Coupon.CouponType === 'goods' && res[n].Status === 1) {
          if (res[n].Coupon.IsAll && nowDate >= new Date(res[n].StartDate).getTime() && nowDate < new Date(res[n].EndDate).getTime() && res[n].CaseId === this.$route.query.caseid) {
            this.couponList.push({
              title: res[n].Coupon.CouponName,
              desc: res[n].Coupon.Share.UseRule,
              time: this.toolClass.dateFormat(res[n].EndDate),
              useType: '未使用',
              tag: '商品',
              id: res[n].CustomerCouponId,
              select: false,
            })
          } else {
            for (var a = 0; a < res[n].Coupon.Targets.length; a++) {
              if (res[n].Coupon.Targets[a].TargetId === id && nowDate >= new Date(res[n].StartDate).getTime() && nowDate < new Date(res[n].EndDate).getTime()) {
                this.couponList.push({
                  title: res[n].Coupon.CouponName,
                  desc: res[n].Coupon.Share.UseInstruction,
                  time: this.toolClass.dateFormat(res[n].EndDate),
                  useType: '未使用',
                  tag: '商品',
                  id: res[n].CustomerCouponId,
                  select: false,
                })
              }
            }
          }
        }
      }
      this.getCouponOff = true
      // console.log(JSON.stringify(this.couponList))
    })
  },
  methods: {
    ...caseTableActions([
      'toPay',
      'getCouponList',
    ]),
    sureSelectCoupon () {
      var bool = false
      for (var n = 0; n < this.couponList.length; n++) {
        if (this.couponList[n].select) {
          bool = true
          this.postData.customercouponid = this.couponList[n].id
        }
      }
      if (!bool) {
        this.postData.customercouponid = ''
      }
      this.showSelectCouponLayer = false
    },
    selectCouponItem (item) { // 选择优惠券
      // item.select = !item.select
      if (!item.select) {
        for (var n = 0; n < this.couponList.length; n++) {
          this.couponList[n].select = false
        }
        item.select = true
      } else {
        item.select = false
      }
    },
    returnAmount () { // 返回总金额  
      var amount = 0, num = 0, info = JSON.parse(this.$route.query.info)
      for (var n = 0; n < info.length; n++) {
        if (info[n].defaultPrice === null) {
          amount += info[n].price * info[n].num
          num += info[n].num
        } else {
          amount += info[n].defaultPrice * info[n].defaultNum
          num += info[n].defaultNum
        }
      }
      return [amount, num]
    },
    toPayer () { // 下单
      if (this.ajaxoff) {
        this.ajaxoff = false
        this.toPay({
          id: this.$route.query.ordersid,
          remark: this.postData.info.Remark,
          customercouponid: this.postData.customercouponid
        }).then((res) => {
          this.showSuccessPopup = true
          // this.$dialog.alert({
          //   message: '下单成功！'
          // }).then(() => {
          //   window.history.go(-2)
          // })
        }).catch(() => {
          this.ajaxoff = true
        })
      }
    },

    popBack () {
      this.showSuccessPopup = false
      // window.history.go(-2)
      this.$router.push({name: 'coffeeIndex'})
    },
    cancel () {
      // window.history.go(-1)
      this.$router.push({name: 'coffeeIndex'})
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import 'page.scss';
.layerBg{
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 100;
  display: none;
  &.active{
    display: block;
  }
}
</style>
