<template>
  <div class="mainPage flex-v">
    <div class="flex-item flex-v">
      <div class="banner">
        <img :src="banner" class="centerLabel cover" alt="">
        <div class="bannerInfo flex-h">
          <div class="flex-item">
            <div>
              <span>项目名称：{{caseName}}</span>
            </div>
          </div>
          <span>{{userInfo.customer.RealName ? userInfo.customer.RealName : userInfo.customer.Name}}您好！</span>
        </div>
      </div>
      <div class="tableInfo flex-h">
        <div class="flex-item">
          <div>
            <span>桌号：{{tableNo}}</span>
            <span v-if="userInfo.customer.MapUser !== ''">本月已用：{{caseTotal.monthtotal}}杯</span>
          </div>
        </div>
        <a @click="reback">返回选择桌号</a>
      </div>
      <div class="content flex-item flex-h">
        <div class="slideMenus">
          <div>
            <ul>
              <li v-for="(item,index) in menuList" :key="index" :class="{'active': slideMenusActive == index}" @click="cutMenu(index)">
                <span>{{item.value}}</span>
                <span>{{item.eValue}}</span>
              </li>
            </ul>
          </div>
        </div>
        <div class="flex-item">
          <div>
            <swiper :options="swiperOption" ref="mySwiper">
              <swiper-slide class="swiper-slide" v-for="(item,index) in menuList" :key="index">
                <div class="flex-v">
                  <h4>{{item.value + ' ' + item.eValue}}</h4>
                  <div class="flex-item">
                    <div>
                      <swiper :options="subSwiperOption" ref="mySubSwiper">
                        <swiper-slide class="swiper-slide" v-for="(subItem,subIndex) in item.list" :key="subIndex">
                          <orderItem :data="subItem" @returnData="calcMenus" @selectSpec="selectSpec"></orderItem>
                        </swiper-slide>
                      </swiper>
                    </div>
                  </div>
                </div>
              </swiper-slide>
            </swiper>
          </div>
        </div>
      </div>
    </div>
    <div class="flex-h">
      <div class="flex-item">
        <div>
          <span>总计</span>
          <span>{{sumNum}}</span>
          <span>杯</span>
          <span>共</span>
          <span>{{sumPrice}}</span>
          <span>元</span>
          <!-- <i class="iconfont" :class="{'icon-jiantou-up': !showCalcMenu,'icon-jiantou-down': showCalcMenu}" @click="showCalcMenu = true"></i> -->
        </div>
      </div>
      <a @click="toPlaceOrder">下单</a>
    </div>
    <orderPopup :show="showPopup" :data="currentSpec" @closePopup="closePopup" @returnData="calcMenus"></orderPopup>
    <calcMenu :show="showCalcMenu" :totalNum="sumNum + caseTotal.total" :data="selGoods" @returnData="calcMenus" @emptyMenus="emptyMenus" @closeCalcMenu="closeCalcMenu" @placeOrder="placeOrder"></calcMenu>
    <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>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: caseTableActions } = createNamespacedHelpers('placeOrderForCoffee')
const { mapState: mapCaseState, mapActions: mapCaseActions } = createNamespacedHelpers('case')
import orderItem from '../../../components/orderItem/index'
import orderPopup from '../../../components/orderPopup/index'
import calcMenu from '../../../components/calcMenu/index'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'

export default {
  name: '',
  data () {
    const _self = this
    return {
      ajaxOff: true,
      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: [],
        coupon: [],
      },
      tableNo: decodeURI(this.$route.query.tableno),
      tableId: decodeURI(this.$route.query.tableid),
      areaId: decodeURI(this.$route.query.areaid),
      areaName: decodeURI(this.$route.query.areaname),
      caseName: decodeURI(this.$route.query.casename),
      caseId: decodeURI(this.$route.query.caseid),
      totalCupNum: 0, // 共计使用杯数
      showCalcMenu: false, // 显隐已点菜单弹窗
      currentSpec: null, // 当前选择规格
      showPopup: false, // 显隐选规格弹窗
      totalNum: 0, // 总杯数
      totalPrice: 0, // 总价格
      settlementList: [], // 商品选择清单
      slideMenusActive: 0, // 左侧菜单选中索引值
      menuList: [],
      banner: 'https://jingcheng-h5temp.oss-cn-shanghai.aliyuncs.com/spaceofchengGoodsbanner.png',
      swiperOption: {
        observer: true,
        direction: 'vertical',
        on: {
          transitionEnd () {
            _self.slideMenusActive = this.activeIndex
          },
        }
      },
      subSwiperOption: {
        observer: true,
        direction: 'vertical',
        nested: true,
        slidesPerView: 'auto',
        freeMode: true,
        freeModeMomentumVelocityRatio: 2,
      },
      selGoods: [],
      showSuccessPopup: false
    }
  },
  computed: {
    ...mapState({
      userInfo: x => x.userCenter.userInfo,
      goodsTypeList: x => x.placeOrderForCoffee.goodsTypeList,
      goodsList: x => x.placeOrderForCoffee.goodsList
    }),
    ...mapCaseState({
      caseTotal: x => x.caseTotal,
    }),
    MySwiper () {
      return this.$refs.mySwiper.swiper
    },
    MySubSwiper () {
      return this.$refs.mySubSwiper.swiper
    },
    sumNum () {
      let num = 0
      this.selGoods.map(x => {
        num += x.num
      })
      return num
    },
    sumPrice () {
      let price = 0
      this.selGoods.map(x => {
        price += x.price * x.num - 0
      })
      return Math.ceil((price) * 100) / 100
    }
  },
  components: {
    swiper,
    swiperSlide,
    orderItem,
    orderPopup,
    calcMenu,
  },
  created () {
    this.getGoodsTypeList({
      caseid: this.caseId,
    }).then((res) => {
      // console.log(JSON.stringify(res))
      this.getGoodsList({
        caseid: this.caseId,
      }).then((res) => {
        // console.log(JSON.stringify(res))
        this.mapArr()
      })
      if (this.userInfo.customer.MapUser !== '') {
        this.getCaseTotal({
          caseid: this.caseId
        })
      }
    })
  },
  methods: {
    ...caseTableActions([
      'getGoodsTypeList',
      'getGoodsList',
      'toPay',
    ]),
    ...mapCaseActions([
      'getCaseTotal',
    ]),
    toPlaceOrder () { // 下单 
      if (this.selGoods.length) {
        if (this.userInfo.customer.MapUser === '') {
          this.$router.push({ name: 'placeOrderDetail', query: { info: JSON.stringify(this.selGoods), caseid: encodeURI(this.caseId), areaid: encodeURI(this.areaId), areaname: encodeURI(this.areaName), areaid: encodeURI(this.areaId), tableid: encodeURI(this.tableId), tableno: encodeURI(this.tableNo) } })
        } else {
          this.showCalcMenu = true
        }
      } else {
        this.$toast('您还没有选择商品哦~')
      }
    },
    mapArr () { // 匹配商品规格
      var aArr = (this.goodsTypeList || []), bArr = (this.goodsList || [])
      for (var n = 0; n < aArr.length; n++) {
        aArr[n].list = []
        for (var a = 0; a < bArr.length; a++) {
          if (aArr[n].TypeId === bArr[a].TypeId) {
            aArr[n].list.push(bArr[a])
          }
        }
      }
      this.menuList = []
      for (var x = 0; x < aArr.length; x++) {
        this.menuList.push({
          value: aArr[x].TypeName,
          eValue: aArr[x].EnglishName,
          id: aArr[x].TypeId,
          status: aArr[x].Status,
          list: []
        })
        for (var y = 0; y < aArr[x].list.length; y++) {
          this.menuList[x].list.push({
            img: aArr[x].list[y].Images,
            name: aArr[x].list[y].GoodsName,
            id: aArr[x].list[y].GoodsId,
            spec: [],
            status: aArr[x].list[y].Status,
            price: aArr[x].list[y].Price,
            num: 0,
          })
          if (aArr[x].list[y].Specs !== null) {
            for (var z = 0; z < aArr[x].list[y].Specs.length; z++) {
              this.menuList[x].list[y].spec.push({
                value: aArr[x].list[y].Specs[z].SpecName,
                id: aArr[x].list[y].Specs[z].SpecId,
                num: 0,
                status: aArr[x].list[y].Specs[z].Status,
                price: aArr[x].list[y].Specs[z].GoodsPrice,
              })
            }
          }
        }
      }
    },
    reback () { // 返回桌位选择
      this.$dialog.confirm({
        message: '返回页面将清空当前选择的商品，确定要返回吗?'
      }).then(() => {
        // this.$router.push({ name: 'coffeeIndex' })
        // window.history.go(-1)
        this.$router.go(-1)
      })
    },
    placeOrder (Remark) { // 下单
      if (this.ajaxOff) {
        this.ajaxOff = false
        this.postData.info.OrgId = this.orgId
        this.postData.info.UserId = this.userInfo.CustomerId
        this.postData.info.UserName = this.userInfo.customer.CustomerName
        this.postData.info.PayType = 'sys user'
        this.postData.info.Remark = Remark
        this.postData.from = sessionStorage.getItem('from') ? sessionStorage.getItem('from') : ''
        var orderInfo = this.selGoods
        this.postData.detail = []
        var amount = 0
        var num = 0
        for (var n = 0; n < orderInfo.length; n++) {
          this.postData.detail.push({
            GoodsId: orderInfo[n].id,
            GoodsName: orderInfo[n].name,
            SpecId: orderInfo[n].spec,
            SpecName: orderInfo[n].specname,
            Number: orderInfo[n].num - 0,
            Price: String(orderInfo[n].price - 0),
          })
          amount += (orderInfo[n].price - 0) * orderInfo[n].num
          num += orderInfo[n].num - 0
        }
        this.postData.info.Amount = String(amount)
        this.postData.info.OrdersNum = num
        // console.log(JSON.stringify(this.postData))
        this.toPay({
          info: JSON.stringify(this.postData.info),
          detail: JSON.stringify(this.postData.detail),
          customercouponid: JSON.stringify(this.postData.coupon) || '',
          from: this.postData.from
        }).then((res) => {
          this.ajaxOff = true
          this.showCalcMenu = false
          this.showSuccessPopup = true
          // this.$dialog.alert({
          //   message: '下单成功！',
          //   confirmButtonText: '返回等待'
          // }).then(() => {

          // })
        })
      }
    },
    popBack () {
      this.showSuccessPopup = false
      this.$router.push({ name: 'orderList' })
    },
    closeCalcMenu () { // 关闭已选菜单
      this.showCalcMenu = false
    },
    emptyMenus () { // 清空菜单
      this.settlementList = []
    },
    closePopup () { // 关闭规格弹窗
      this.showPopup = false
      this.currentSpec = null
    },
    selectSpec (val) { // 选规格
      this.currentSpec = val
      this.showPopup = true
    },
    cutMenu (index) { // 切换菜单
      this.MySwiper.slideTo(index, 300)
    },
    calcMenus (val) { // 计算清单
      var ishas = false
      const _that = this
      this.selGoods.map((goods, inx) => {
        if (goods.id === val.id && goods.spec === (val.spec || '')) {
          ishas = true
          _that.selGoods[inx].num = val.defaultNum
        }
      })
      if (!ishas) {
        this.selGoods.push({
          id: val.id,
          price: val.defaultPrice,
          num: val.defaultNum,
          name: val.name,
          spec: (val.spec || ''),
          specname: (val.specname || ''),
        })
      } else {
        if (val.defaultNum === 0) {
          this.selGoods.splice(this.selGoods.findIndex(item => item.id === val.id && item.spec === (val.spec || '')), 1)
        }
      }
    },
    calcTotalNum () { // 计算总数量、价格
      var num = 0, price = 0
      if (!this.settlementList.length) {
        this.totalNum = 0
        this.totalPrice = 0
        return
      }
      for (var n = 0; n < this.settlementList.length; n++) {
        if (this.settlementList[n].specId === null) {
          num += this.settlementList[n].defaultNum
          price += this.settlementList[n].defaultPrice * this.settlementList[n].defaultNum
        } else {
          num += this.settlementList[n].num
          price += this.settlementList[n].price * this.settlementList[n].num
        }
      }
      this.totalNum = num
      this.totalPrice = price
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import 'page.scss';
</style>

<style>
.van-dialog__message {
  text-align: center;
}
</style>
