<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">
      <print-list :print-list="printList" v-if="printList.length>0" @printed="clearPrintList" />
      <div style='position:relative;' v-for="(item,index) in ordersList" :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;">下单人：{{item.UserName}}</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 { formatTimeBySeconds } from '@/util/util'
import { replaceURLParams } from '@/util/ajax'
import XWebSocket from '@/util/websocket'

// const WebSocket = require('ws')
const { mapState: mapOrderState, mapActions: mapOrderActions } = createNamespacedHelpers('goodsorder')

export default {
  name: '',
  components: {
    'print-list': () => import('./print'),
  },
  data () {
    return {
      ws: null,
      wsID: '',
      printList: [],

      total: 0,
      postData: { // 表格搜索条件
        phone: '', // 手机号
        page: 1, // 当前页码
        pagesize: 10, // 请求数据量
      },
      leftTimes: {},
      business: false,
      caseid: '',
      websockets: {},
      interval: () => { },
      needReload: true
    }
  },
  computed: {
    ...mapOrderState({
      ordersList: x => x.ordersList,
    }),
    ...mapOrderState({
      businessStatus (state) {
        return state.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(() => {
      console.log(this.CaseId)
      if (this.CaseId) {
        this.init()
      }
    })

    this.ws = new XWebSocket({
      message: this.receviedNewOrders.bind(this),
      delay: 10,
      autoConnect: true,
    })
  },
  beforeRouteLeave (to, from, next) {
    this.wsID = ''
    this.ws.close()
    this.updateList([])
    next()
  },
  methods: {
    init () {
      // 必须选案场
      if (!this.CaseId) {
        this.$message({
          type: 'info',
          message: '请先选择案场'
        })
        return
      }

      // 获取新单
      this.GetOrdersList({ caseid: this.CaseId }).then(list => {
        // 打印新单
        if (list) {
          this.printList = list.filter(x => x.IsIntimidate === 0)
          this.printList.map(orders => {
            this.putPrintGoodsOrder({id: orders.OrdersId})
          })
        }

        // 开张, 则实时监控新单
        this.getBusinessStatus(this.CaseId).then((businessStatus) => {
          this.caseChange()
        })

        // 页面倒计时
        clearInterval(this.interval)
        this.refreshList()
      })
    },
    caseChange () {
      if (!this.businessStatus) {
        this.ws.close()
      }
      if (this.businessStatus && (this.wsID !== this.CaseId) && this.CaseId) {
        this.ws.close()
        this.initWebSocket()
        this.wsID = this.CaseId
      }
    },
    refreshList () {
      this.interval = setInterval(() => {
        const now = (new Date()).valueOf()
        this.leftTimes = (this.ordersList || []).reduce((acc, it) => {
          const showDT = now - ((new Date(it.CreateDate)).valueOf())
          return { ...acc, [`${it.OrdersId}`]: formatTimeBySeconds(showDT) }
        }, {})
      }, 1000)
    },
    clearPrintList () {
      this.printList = []
    },
    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.updateList(this.ordersList.filter(x => x.OrdersId !== id))
        })
      }).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.updateList(this.ordersList.filter(x => x.OrdersId !== id))
        })
      }).catch((res) => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    initWebSocket () {
      let caseid = this.CaseId
      let id = this.userInfo.UserId
      const wsPath = this.$api.system.notify.newGoodsOrders.url
      const wsRealPath = replaceURLParams(wsPath, { grps: caseid, id })
      const wsURL = `${window.location.origin.replace('http', 'ws')}${wsRealPath}?token=${localStorage.getItem('JWT')}`
      this.ws.connect(wsURL)
    },
    receviedNewOrders (e) {
      const newOrders = JSON.parse(e.data).data.refreshOnlineGoodsOrders
      if (!newOrders || !newOrders.length) return

      // 放入待制作队列
      this.updateList(this.ordersList.concat(newOrders))

      // 放入待打队列
      const ps = newOrders.filter(x => x.IsIntimidate === 0).map((orders) => {
        return new Promise((resolve, reject) => {
          if (orders.IsIntimidate === 0) {
            // 先远程更新掉打单状态字段
            this.putPrintGoodsOrder({id: orders.OrdersId}).then(() => {
              resolve(orders)
            })
          } else {
            resolve()
          }
        })
      })

      Promise.all(ps).then((its) => {
        this.printList = this.printList.concat((its || []).filter(x => x))
      })
    },
    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.wsID = ''
      this.ws.close()
      this.closeBusiness(this.CaseId)
    }
  }
}
</script>

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