<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;display:flex;align-items: center;">
            <!-- <i class="iconfont icon-yinchenglogo" style="font-size:70px;color:red;position: relative;bottom: 20px;margin-right:10px;"></i> -->
            <img :src="item.AreaIcon" style="width:70px;height:70px;margin-right:10px;">
            <div style="display:inline-block;">
              <span style="display:block;font-size:20px;font-weight:700;width:180px;white-space: initial;">{{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;white-space: normal;">备注:{{item.Remark}}</div>
          <div style="padding:10px 20px;" @click="printPdf(`item${index}`)">下单人:{{item.UserName}}</div>
        </div>
        <div class="print-area" :class="'item_' + item.OrdersId" 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 + item.TableNo}}</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,index)">取消</span>
          <span @click="submit(item.OrdersId,index)">确定</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createNamespacedHelpers, mapState, mapActions } from 'vuex'
import { getLodop } from '@/util/LodopFuncs'
import { formatTimeBySeconds } from '@/util/util'
import { replaceURLParams } from '@/util/ajax'

// const WebSocket = require('ws')
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: '',
      websockets: {},
      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) {
        console.log(this.caseid)
        this.init()
      }
    })
  },
  mounted () {
    setTimeout(window.location.reload, 600 * 1000)
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log(this.websockets)
    Object.keys(this.websockets).forEach((key) => {
      console.log(key, this.websockets[key])
      this.websockets[key].onclose()
    })
    next()
  },
  methods: {
    init () {
      Object.keys(this.websockets).forEach((key) => {
        console.log(key, this.websockets[key])
        this.websockets[key].onclose()
      })
      console.log('init')
      var param = []
      if (!this.caseid) {
        this.$message({
          type: 'info',
          message: '请先选择案场'
        })
        return
      }
      clearInterval(this.interval)
      this.GetOrdersList({ caseid: this.caseid }).then((res) => {
        for (var n = 0; n < (res.list || []).length; n++) {
          if (res.list[n].IsIntimidate === 0) {
            param.push(res.list[n].OrdersId)
          }
        }
        var bool = true
        var timer = setInterval(() => {
          if (param.length && bool) {
            bool = false
            this.printPdf(`item_${param[0]}`)
            this.putPrintGoodsOrder({
              id: param[0]
            }).then(() => {
              param.splice(0, 1)
              bool = true
            })
          } else {
            clearInterval(timer)
          }
        }, 300)
        this.getBusinessStatus(this.caseid).then(() => {
          if (this.businessStatus) {
            this.initWebSocket()
          }
        })
      })
      this.refreshList()
    },
    refreshList () {
      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',
      'putPrintGoodsOrder',
    ]),
    ...mapActions([
      'updateSystemInfo'
    ]),
    submit (id, index) {
      this.$confirm('确定完成此饮品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        this.checkOrder({ id: id }).then(() => {
          this.$message({
            type: 'success',
            message: '确认订单成功'
          })
          this.list.splice(index, 1)
          this.updateList({ list: this.list })
        })
      }).catch((res) => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    cancel (id, index) {
      this.$confirm('确定取消此饮品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        this.cancelOrder({ id: id }).then(() => {
          this.$message({
            type: 'success',
            message: '取消订单成功'
          })
          this.list.splice(index, 1)
          this.updateList({ list: this.list })
        })
      }).catch((res) => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    printPdf (cl) {
      this.CreateOneFormPage(cl)
      LODOP.PRINT()
    },
    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('initWebSocket')
      // console.log(this.user)
      let caseid = this.caseid
      let id = this.userInfo.UserId
      const wsPath = this.$api.system.notify.newGoodsOrders.url
      const wsRealPath = replaceURLParams(wsPath, { grps: caseid, id })
      this.newWebsocket(wsRealPath)
    },
    websocketonmessage (e) {
      // let oldList = this.list
      let newList = JSON.parse(e.data).data.refreshOnlineGoodsOrders
      // let newinfo = newList.filter(x => this.list.filter(item => item.OrdersId === x.OrdersId).length === 0)
      this.updateList({ list: this.list.concat(newList) }).then(() => {
        newList.forEach((it) => {
          // console.log('it:', it)
          this.printPdf(`item_${it.OrdersId}`)
          this.putPrintGoodsOrder({
            id: it.OrdersId
          })
        })
      })
    },
    newWebsocket (wsRealPath) {
      const ws = this.websockets[wsRealPath]
      if (!ws) {
        const url = `${window.location.origin.replace('http', 'ws')}${wsRealPath}?token=${localStorage.getItem('JWT')}`
        this.websockets[wsRealPath] = new WebSocket(url)
        this.websockets[wsRealPath].onopen = console.log
        this.websockets[wsRealPath].onmessage = this.websocketonmessage
        this.websockets[wsRealPath].onclose = console.log
        setInterval(() => this.websockets[wsRealPath].send(10), 120000)
      }
    },
    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>