<template>
  <div class="subPage">
    <div class="system-table-search">
      <div class="flex-h">
        <div class="flex-item flex-h">
          <el-button size="mini" v-if="!businessStatus" type="danger" @click="open">营业</el-button>
          <el-button size="mini" v-else type="submit" @click="close">歇业</el-button>
        </div>
        <ul>
          <li>
            <el-select v-model="caseid" placeholder="请选择案场">
              <el-option
                v-for="item in cases"
                :key="item.CaseId"
                :label="item.CaseName"
                :value="item.CaseId">
              </el-option>
            </el-select>
          </li>
        </ul>
        <el-button
          size="mini"
          type="primary" @click="init">搜索</el-button>
      </div>
      <div class="moreFilter"></div>
    </div>
    <div class="order-list-box">
      <div style='position:relative;' v-for="(item,index) in list" :key="index">
        <div>
          <div style="padding:25px 20px 5px;border-bottom:2px solid #cccccc;">
            <i class="iconfont icon-yinchenglogo" style="font-size:70px;color:red;position: relative;bottom: 20px;margin-right:10px;"></i>
            <div style="display:inline-block;">
              <span style="display:block;font-size:20px;font-weight:700;">{{item.AreaName + item.TableNo}}</span>
              <span style="display:block;margin-top:10px">下单时间：{{toolClass.dateFormat(item.CreateDate)}}</span>
              <span style="display:block;margin-top:10px">已等待：<span style="color:red;font-weight:700;">{{leftTimes[item.OrdersId]}}</span></span>
            </div>
          </div>
          <div style="padding:10px 20px 5px;border-bottom:1px solid #cccccc;" v-for='(item1,index1) in item.Goods' :key='index1'>
            <div style="display:flex;justify-content: space-between;align-items: center;padding-right: 10px;"><span>{{item1.GoodsName}}</span><span style="display:inline-block;width:20%;text-align:right" v-if='!item1.SpecName'>× {{item1.Number}}</span></div>
            <div style="margin-top:8px;" v-if='item1.SpecName'>
              <span style="display:inline-block;width:75%;text-align:left;color:#cccccc">{{item1.SpecName}}</span>
              <span style="display:inline-block;width:20%;text-align:right">× {{item1.Number}}</span>
            </div>
          </div>
          <!-- <div style="padding:10px 20px;border-bottom:1px solid #cccccc">备注：{{item.Remark}}</div> -->
          <div style="padding:10px 20px;" @click="printPdf(`item${index}`)">下单人：{{item.UserName}}</div>
        </div>
        <div class="print-area" :class="'item' + index" style="width:180px;">
          <div style="padding:0px 10px 5px;border-bottom:2px solid #cccccc;">
            <div style="display:inline-block;">
              <img class="topIcon" style="display:block;width:60%;margin:0 0 20px 0px;" src="http://jingcheng-resourceplat.oss-cn-shanghai.aliyuncs.com/upload/111101940020.png" alt="">
              <span style="display:block;font-size:20px;font-weight:700;text-align: center;"> <img width='25px' height="25px" :src='item.AreaIconWhite' alt=""> {{item.AreaName}}</span>
            </div>
          </div>
          <div style="padding:10px 10px 5px;border-bottom:1px solid #cccccc;" v-for='(item1,index1) in item.Goods' :key='index1'>
            <div style="font-size:12px;"><span style="display:inline-block;width:75%;text-align:left;">{{item1.GoodsName}}</span><span style="display:inline-block;width:22%;text-align:right;font-size:12px;" v-if='!item1.SpecName'>× {{item1.Number}}</span></div>
            <div style="margin-top:8px;" v-if='item1.SpecName'>
              <span style="display:inline-block;width:75%;text-align:left;color:#cccccc;font-size:12px;">{{item1.SpecName}}</span>
              <span style="display:inline-block;width:20%;text-align:right;font-size:12px;">× {{item1.Number}}</span>
            </div>
          </div>
          <div style="padding:10px 10px 5px;border-bottom:1px solid #cccccc;">
            <div style="font-size:12px;">下单人：{{item.UserName}}</div>
            <span style="display:block;margin-top:10px;font-size:12px;">下单时间：{{toolClass.dateFormat(item.CreateDate)}}</span>
          </div>
          <!-- <div style="padding:10px 10px;font-size:12px;">备注：{{item.Remark}}</div> -->
          <div style="text-align: right;font-size: 12px;">城的空间.诚咖啡</div>
          <div style="height:10px"></div>
        </div>
        <div class="btns">
          <span @click="cancel(item.OrdersId)">取消</span>
          <span @click="submit(item.OrdersId)">确定</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createNamespacedHelpers, mapState, mapActions } from 'vuex'

import { getLodop } from '@/util/LodopFuncs'

import { formatTimeBySeconds } from '@/util/util'

const { mapState: mapOrderState, mapActions: mapOrderActions } = createNamespacedHelpers('goodsorder')

var LODOP
export default {
  name: '',
  data () {
    return {
      total: 0,
      postData: { // 表格搜索条件
        phone: '', // 手机号
        page: 1, // 当前页码
        pagesize: 10, // 请求数据量
      },
      currentList: [],
      leftTimes: {},
      business: false,
      caseid: '',
      interval: () => { }
    }
  },
  computed: {
    ...mapOrderState({
      list: x => (x.ordersList || {}).list || [],
      businessStatus: x => x.businessStatus
    }),
    ...mapState({
      cases: x => x.app.cases.list,
      defaultCaseId: x => x.app.cases.default,
      userInfo: x => x.app.user
    }),
    CaseId: {
      get () {
        return this.caseid || this.defaultCaseId
      },
      set (val) {
        this.caseid = val
      }
    }
  },
  created () {
    this.updateSystemInfo().then(() => {
      if (this.caseid) {
        this.init()
      }
    })
  },
  methods: {
    init () {
      if (!this.caseid) {
        this.$message({
          type: 'info',
          message: '请先选择案场'
        })
        return
      }
      clearInterval(this.interval)
      this.GetOrdersList({ caseid: this.caseid }).then(() => {
        this.getBusinessStatus(this.caseid).then(() => {
          if (this.businessStatus) {
            this.initWebSocket()
          }
        })
        this.interval = setInterval(() => {
          const now = (new Date()).valueOf()
          this.leftTimes = this.list.reduce((acc, it) => {
            const showDT = now - ((new Date(it.CreateDate)).valueOf())
            return { ...acc, [`${it.OrdersId}`]: formatTimeBySeconds(showDT) }
          }, {})
        }, 1000)
      })
    },
    timeOut (c) {
      let cTime = new Date(c).valueOf()
      let time = new Date().valueOf()
      let s = parseInt((time - cTime) / 1000)
      let m = parseInt(s / 60)
      s = s - m * 60
      m = m < 10 ? '0' + m : m
      s = s < 10 ? '0' + s : s
      return `${m} : ${s}`
    },
    ...mapOrderActions([
      'GetOrdersList',
      'openBusiness',
      'closeBusiness',
      'checkOrder',
      'cancelOrder',
      'getBusinessStatus',
      'updateList'
    ]),
    ...mapActions([
      'updateSystemInfo'
    ]),
    submit (id) {
      this.$confirm('确定完成此饮品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        this.checkOrder({ id: id }).then(() => {
          this.$message({
            type: 'success',
            message: '确认订单成功'
          })
          this.init()
        })
      }).catch((res) => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    cancel (id) {
      this.$confirm('确定取消此饮品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        this.cancelOrder({ id: id }).then(() => {
          this.$message({
            type: 'success',
            message: '取消订单成功'
          })
          this.init()
        })
      }).catch((res) => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    printPdf (cl) {
      this.CreateOneFormPage(cl)
      LODOP.PRINT()
      // LODOP.PREVIEW()
    },
    CreateOneFormPage (cl) {
      LODOP = getLodop()
      LODOP.PRINT_INIT('订单')
      LODOP.SET_PRINT_PAGESIZE(3, 480, 40, '')
      LODOP.ADD_PRINT_HTM(0, 0, document.getElementsByClassName(cl)[0].offsetWidth, document.getElementsByClassName(cl)[0].offsetHeight, document.getElementsByClassName(cl)[0].innerHTML)
    },
    initWebSocket () {
      console.log(this.user)
      let caseid = this.caseid
      let id = this.userInfo.UserId
      const wsuri = `${window.location.origin.replace('http', 'ws')}/api/common/MQ/websocket/${caseid}/${id}`
      // const wsuri = `ws://192.168.0.11/api/guest/MQ/websocket/${caseid}/${id}`
      try {
        this.websock = new WebSocket(wsuri)
      } catch (e) {
        console.log(e)
      }
      this.websock.onopen = console.log
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = console.log
    },
    websocketonmessage (e) {
      console.log(e)
      let lengthOld = this.list.length
      let lengthNew = JSON.parse(e.data).data.refreshOnlineGoodsOrders.length
      let newData = JSON.parse(e.data).data.refreshOnlineGoodsOrders.slice(lengthOld - lengthNew)
      this.updateList(JSON.parse(e.data).data.refreshOnlineGoodsOrders).then(() => {
        for (let i = 0; i < newData.length; i++) {
          let index = newData[i].indexOf(this.list)
          this.printPdf(`item${index}`)
        }
      })
    },
    open () {
      if (!this.caseid) {
        this.$message({
          type: 'info',
          message: '请先选择案场'
        })
        return
      }
      this.openBusiness(this.caseid).then(() => {
        this.init()
      })
    },
    close () {
      if (!this.caseid) {
        this.$message({
          type: 'info',
          message: '请先选择案场'
        })
        return
      }
      this.closeBusiness(this.caseid)
    }
  }
}
</script>

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