<template>
  <a-card :bordered="false" class="card-pd">
    <a-tabs v-model="tabPosTypeId" @change="tabPosTypeChange">
      <a-tab-pane
        :key="item.id"
        :tab="item.name"
        v-for="item in posTypeList"
      ></a-tab-pane>
    </a-tabs>
    <div style="display: flex; height: calc(100vh - 350px)">
      <a-card style="width: 30%;">
        <a href="#" @click="remarkModal"> <a-icon type="edit" />整单备注</a>
        &nbsp;&nbsp;<a-icon type="user" />
        <spn v-if="posTableId !=''">桌台: {{ posTableName }}</spn>
        <span v-if="selectRoomOrder && selectRoomOrder.roomName">
          房间：{{ selectRoomOrder.roomName }},姓名:{{
            selectRoomOrder.customerName
          }}
        </span>
        <a-table
          bordered
          :columns="columns"
          :data-source="selectGoodsList"
          :row-selection="rowSelection"
          rowKey="id"
          style=" overflow-y: scroll;"
        >
          <template slot="num" slot-scope="text, record, index">
            <div style="text-align: center">
              <a-input-number
                v-if="record.detailId == null"
                v-model="record.num"
                style="width: auto; "
                :max="record.inventory"
                @change="(event) => numChange(event, index)"/>
              <span v-else>{{ record.num }}</span>
            </div>
          </template>
          <template slot="required" slot-scope="text, record, index">
            <div>
              <a-switch v-model="record.required" />
            </div>
          </template>

          <span slot="action" slot-scope="text, record, index">
            <a @click="handleDelete(index)">删除</a>
          </span>
        </a-table>
        <p>数量：{{ sum }}</p>
        <div v-if="this.posTableState === 1">
          <a-button @click="placeOrder" :disabled="btnDisabled">下单</a-button>
          <a-button @click="unionStation('联台','5')" style="margin-left: 10px;">联台</a-button>
          <a-button v-if="!btnDisabled && selectGoodsList.length !== 0" @click="unionStation('转菜','2')" :disabled="transferDishesList.length == 0"  style="margin-left: 10px;">转菜</a-button>
          <a-button @click="unionStation('换台','0')" style="margin-left: 10px;">换台</a-button>
          <!--          <a-button @click="addClear" :disabled="btnDisabled">清空新加</a-button>-->
        </div>
        <div v-else style="display: flex; gap: 5px; flex-flow: wrap">
          <a-button @click="clean" :disabled="btnDisabled">清空</a-button>
          <!-- <a-button @click="handleAdd" :disabled="btnDisabled">备注</a-button> -->
          <!-- <a-button :disabled="btnDisabled">退货</a-button> -->
          <div v-if="posTableId === ''">
            <a-button v-if="!btnDisabled" @click="pendingOrder">挂单</a-button>
            <a-button v-else @click="handlePickingGoodsOrder">取单</a-button>
          </div>
          <div>
            <a-button v-if="!btnDisabled" @click="unionStation('联台','5')" style="margin-left: 10px;">联台</a-button>
            <a-button v-if="!btnDisabled && selectGoodsList.length !== 0" @click="unionStation('转菜','2')" :disabled="transferDishesList.length == 0"  style="margin-left: 10px;">转菜</a-button>
            <a-button v-if="!btnDisabled" @click="unionStation('换台','0')" style="margin-left: 10px;">换台</a-button>
            <a-button v-if="isUnionStation" @click="unlink" style="margin-left: 10px;">取消联台</a-button>
            
            <!-- <a-button @click="pendingOrder">挂单</a-button> -->
            <!-- <a-button v-else @click="handlePickingGoodsOrder">取单</a-button> -->
          </div>
          <a-button
            v-if="selectRoomOrder && selectRoomOrder.roomName && !btnDisabled"
            @click="handleToRoomFeePayment"
          >确定挂房帐</a-button
          >
          <a-button
            v-else
            @click="handleSelectCheckInRoomOrder">
            挂房帐
          </a-button
          >
          <a-button
            :disabled="btnDisabled"
            type="danger"
            @click="handlePayment"
          >结账￥{{ amount.toFixed(2) }}</a-button
          >
          <a-button :disabled="btnDisabled" @click="refundChange">退货</a-button>
        </div>
      </a-card>
      <a-card style="width: 75%; position: relative">
        <a-tabs v-model="tabgoodsTypeId" @change="tabGoodsTypeChange">
          <a-tab-pane key="1" tab="全部"></a-tab-pane>
          <a-tab-pane
            :key="item.id"
            :tab="item.name"
            v-for="item in goodsTypeList"
          ></a-tab-pane>
        </a-tabs>
        <a-row :gutter="[5, 5]">
          <a-col
            v-for="item in dataSource"
            :key="item.id"
            :span="3"
            @click.stop="itemClick(item)"
          >
            <div class="room-item check">
              <div class="select-cell"></div>
              <template v-if="item.id != '0'">
                <div>{{ item.name }}</div>
                <div style="margin-top: 10px; color: red">
                  ￥{{ item.sellingPrice.toFixed(2) }}
                </div>
                <div style="margin-top: 10px">库{{ item.inventory }}</div>
<!--                <div-->
<!--                  v-if="item.isSellClear"-->
<!--                  style="display: flex; justify-content: right">-->
<!--                  <a-tag color="#f50"> 沽清 </a-tag>-->
<!--                </div>-->
                <div
                    v-if="item.inventory <= 0"
                    style="display: flex; justify-content: right">
                  <a-tag color="#f50"> 沽清 </a-tag>
                </div>
              </template>
              <template v-else>
                <div style="font-weight: 800; text-align: center">＋临时菜</div>
              </template>
            </div>
          </a-col>
          <a-col
            v-for="item in dataSource2"
            :key="item.id"
            :span="3"
            @click.stop="itemClick2(item)"
          >
            <div class="room-item check">
              <div class="select-cell"></div>
              <div style="display: flex">
                <a-tag color="#506fee"> 套 </a-tag>
              </div>
              <div>{{ item.name }}</div>
              <div style="margin-top: 10px; color: red">
                ￥{{ item.sellingPrice.toFixed(2) }}
              </div>
            </div>
          </a-col>
        </a-row>
        <a-row style="margin-top: 30px">
          <a-space>
            <a-input
              v-if="!isSaoma"
              placeholder="输入名称、简拼、条码"
            ></a-input>
            <a-input v-else placeholder="请扫描条码"></a-input>
            <a-button v-if="!isSaoma">查询</a-button>
            <a-button
              @click="isSaoma = !isSaoma"
            >切换为{{ isSaoma ? "查询" : "扫码" }}模式</a-button
            >
          </a-space>
        </a-row>
      </a-card>
      <a-modal v-model="unionOpen" width="1200px" :title="unionTitle" @ok="handleOk">
          <a-tabs v-model="tabPosRegionId" @change="tabRegionChange">
            <a-tab-pane key="1" tab="全部"></a-tab-pane>
            <a-tab-pane
              :key="item.id"
              :tab="item.name"
              v-for="item in regionList"
            ></a-tab-pane>
        </a-tabs>
        <a-row :gutter="[5, 5]">
              <a-col
                v-for="item in uniteDataSource"
                :key="item.id"
                :span="2"
                @click="orderMeal(item)"
              >
              <template>
                <div :style="item.state == '1' ? 'backgroundColor: #00a0e9;border: 2px solid #000;color: #fff;' : 'backgroundColor: #0a7a72;border: 2px solid #000;color: #fff;'" :class="{'active': model.reserveTableList.some(t => t.id == item.id) }">
                <div>{{ item.name }}</div>
                <div style="margin-top: 10px">
                  <div v-if="item.state == '2'">￥{{ item.posOrderGoods ? item.posOrderGoods.money : 0 }}</div>
                  <div v-else>待下单</div>
                </div>
                <div
                  style="
                    margin-top: 10px;
                    display: flex;
                    justify-content: space-between;
                  "
                >
                  <div>
                    <a-icon type="user" />{{ item.userNum }}/{{ item.num }}人
                  </div>
                  <div>
                    <a-icon type="clock-circle" />{{ hours(item.orderTime) }}
                  </div>
                </div>
                </div></template
              >
              </a-col>
            </a-row>
      </a-modal>
    </div>
    <payment-modal ref="modalPaymentForm" @ok="modalFormOk" @close="modalFormClose"></payment-modal>
    <goods-modal ref="modalGoodsForm" @ok="modalFormOk2"></goods-modal>
    <picking-goods-order-modal
      ref="modalPickingGoodsOrderForm"
      @ok="modalPickingGoodsOrderFormOk"
    ></picking-goods-order-modal>
    <select-check-in-room-order-modal
      ref="modalSelectCheckInRoomOrderModal"
      @ok="modalSelectCheckInRoomOrderFormOk"
    ></select-check-in-room-order-modal>

    <!-- 整单备注弹窗 -->
    <a-modal
      @cancel="isRemarkModal = false"
      :visible="isRemarkModal"
      title="添加备注"
      @ok="remarkModalOk"
    >
      <a-form-model>
        <a-form-model-item label="备注">
          <a-input v-model="remark" type="textarea" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 退货弹窗 -->
    <a-modal
      @cancel="isRefund = false"
      :visible="isRefund"
      title="退货"
      @ok="refundModalOk"
    >
      <a-form-model>
        <a-form-model-item label="备注">
          <a-input v-model="refundRemark" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
// import { JeecgListMixin } from "@/mixins/JeecgListMixin";
// import PosRegionModal from "./modules/PosRegionModal";
import { filterObj } from '@/utils/util'
import { getAction, postAction, deleteAction } from '@/api/manage'
import PaymentModal from './modules/PaymentModal.vue'
import goodsModal from './modules/goodStock/goodsModal.vue'
import PickingGoodsOrderModal from './modules/PickingGoodsOrderModal.vue'
import SelectCheckInRoomOrderModal from './modules/SelectCheckInRoomOrderModal.vue'
import { computed } from 'vue'
import { tree } from '@/api/good'
const columns = [
  {
    title: '商品名称',
    dataIndex: 'name',
    width: '50%'
  },
  {
    title: '数量',
    dataIndex: 'num',
    width: '25%',
    scopedSlots: {
      customRender: 'num'
    }
  },
  {
    title: '售价',
    dataIndex: 'sellingPrice',
    width: '25%'
  }
]
export default {
  name: 'MemberList',
  components: {
    PaymentModal,
    goodsModal,
    PickingGoodsOrderModal,
    SelectCheckInRoomOrderModal
  },
  props: {
    tableId: {
      type: String,
      default: ''
    },
    tableState: {
      type: Number,
      default: -1
    },
    tableName: {
      type: String,
      default: ''
    },
    orderId: {
      type: String,
      default: ''
    },
    isUnionStation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    tableId: function (newValue, oldValue) {
      this.posTableId = this.tableId
      this.posTableState = this.tableState
      this.posTableName = this.tableName
      if (this.tableId !== '' && this.tableState === 2) {
        this.getOrderByTableId(this.tableId)
      }
    }
  },
  data() {
    return {
      posTableId: '',
      posTableState: -1,
      posTableName: '',
      tableState2: -1,
      isRemarkModal: false,
      isSaoma: false,
      remark: '',
      columns,
      isRefund: false,
      refundRemark: '',
      sellClear: 0,
      queryParam: {},
      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 99999,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/pos/posSellClearGoods/list',
        delete: '/pos/posSellClearGoods/delete',
        deleteBatch: '/pos/posSellClearGoods/deleteBatch',
        exportXlsUrl: '/pos/posSellClearGoods/exportXls',
        importExcelUrl: 'pos/posSellClearGoods/importExcel'
      },
      dictOptions: {},
      superFieldList: [],
      selectedRowKeys: [],
      selectedRows: [],
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      treeData: [],
      selectGoods: {},
      posTypeList: [],
      tabPosTypeId: '',
      selectGoodsList: [],
      goodsTypeList: [],
      tabgoodsTypeId: '1',
      dataSource: [],
      dataSource2: [],
      oldSelectGoodsList: [],
      selectOrderInfo: {},
      selectRoomOrder: {},
      // 联台显示隐藏
      unionOpen: false,
      // 联台id
      tabPosRegionId: '1',
      // 联台房间tab
      regionList: [],
      // 列表数据
      uniteDataSource: [],
      model: {
        reserveTableList: []
      },
      // 联台弹框标题文本
      unionTitle: '',
      // 转菜储存数组
      transferDishesList: []
    }
  },
  provide() {
    return {
      treeData: computed(() => this.treeData)
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(
            `selectedRowKeys: ${selectedRowKeys}`,
            'selectedRows: ',
            selectedRows
          )
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          this.transferDishesList = this.selectedRows.filter(item => {
            return ('id' in item)
          })
          console.log(this.transferDishesList);
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name
          }
        })
      }
    },
    sum() {
      return this.selectGoodsList.reduce(function (total, item) {
        return total + item.num
      }, 0)
    },
    amount() {
      console.log(this.selectGoodsList)
      return this.selectGoodsList.reduce(function (total, item) {
        return total + item.sellingPrice * item.num
      }, 0)
    },
    btnDisabled() {
      console.log(this.selectGoodsList);
      var res = this.selectGoodsList && this.selectGoodsList.length >= 0
      return !res
    }
  },
  created() {
    console.log(this.tableId);
    console.log(this.tableState);
    console.log(this.tableName);
    console.log(this.orderId);
    this.dataSource = [
      {
        id: '0'
      }
    ]
    getAction('/pos/posType/list', {
      pageNo: 1,
      pageSize: 99
    }).then((res) => {
      if (res.success) {
        this.posTypeList = res.result.records
        if (this.posTypeList && this.posTypeList.length > 0) {
          this.tabPosTypeId = this.posTypeList[0].id
          this.loadGoodsType()
        }
      }
    })
    this.loadTree()
  },
  methods: {
    // 处理小时
    hours(start) {
      var beginDate = new Date(start);
      var endDate = new Date();
      let hours = parseInt((endDate - beginDate) / (1000 * 60 * 60));
      let leave1 =
        (endDate.getTime() - beginDate.getTime()) % (24 * 3600 * 1000);
      let leave2 = leave1 % (3600 * 1000);
      let minutes = Math.floor(leave2 / (60 * 1000));
      // return minutes == 0 ? hours : hours + 1;
      return hours.toString().padStart(2, "0") + ":" + minutes.toString().padStart(2, "0");
    },
    getStatusColor(status) {
      var find = this.statusColorList.find((t) => t.status == status);
      return find ? find.color : "#fff";
    },
    loadTree() {
      var that = this;
      tree().then((res) => {
        if (res.success) {
          this.treeData = res.result;
        }
      });
    },
    /** 通过桌号查询订单 */
    getOrderByTableId(tableId) {
      getAction('/pos/posOrderGoods/getOrderByTableId', { tableId }).then(resp => {
        console.log(resp);
        if (resp.success) {
          this.selectOrderInfo = resp.result
          this.selectGoodsList = resp.result.posOrderGoodsDetailList
          this.selectGoodsList.forEach(e => {
            this.$set(e, 'sellingPrice', e.money)
            this.$set(e, 'name', e.goodsName)
          })
          this.oldSelectGoodsList = JSON.parse(JSON.stringify(this.selectGoodsList))
        } else {
          this.$message.warning('查询订单失败')
        }
      })
    },
    remarkModal() {
      if (!this.selectGoodsList || this.selectGoodsList.length <= 0) {
        this.$message.warning('请先选择商品')
        return
      }
      this.isRemarkModal = true
    },
    refundModalOk() {

    },

    /**
     * 退货
     */
    refundChange() {
      this.$message.warning('未下单餐品不支持退菜,请重新选择')
      return
      if (this.selectedRows.length == 0) {
        this.$message.warning('请先选择菜品')
      }
      this.isRefund = true
    },

    remarkModalOk() {
      this.handleAdd()
      this.remark = ''
      this.isRemarkModal = false
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    loadTree() {
      var that = this
      tree().then((res) => {
        if (res.success) {
          this.treeData = res.result
        }
      })
    },
    modalFormOk() {
      this.clean()
      this.loadGoods()
    },
    /** 不支付，关闭弹窗，要刷新选中的商品表  */
    modalFormClose() {
      getAction('/pos/posOrderGoodsDetail/getDetailByOrderId', {
        orderId: this.selectOrderInfo.code
      }).then((res) => {
        if (res.success) {
          this.selectGoodsList = res.result;
          res.result.forEach((t) => {
            t.sellingPrice = t.payMoney
            t.name = t.goodsName
            t.id = t.goodsId
          })
          this.selectGoodsList = res.result
        }
      });
    },
    clean() {
      this.selectGoodsList = []
      this.selectOrderInfo = {}
      this.selectRoomOrder = {}
    },
    modalFormOk2(e) {
      console.log(e)
      var good = JSON.parse(JSON.stringify(e))
      this.$set(good, 'num', 1)
      this.selectGoodsList.push(good)
    },
    modalSelectCheckInRoomOrderFormOk(e) {
      console.log(e)
      this.selectRoomOrder = e
    },
    modalPickingGoodsOrderFormOk(e) {
      console.log(e)
      if (e && e.orderDetailList && e.orderDetailList.length > 0) {
        this.selectOrderInfo = e.orderInfo
        e.orderDetailList.forEach((t) => {
          t.sellingPrice = t.payMoney
          t.name = t.goodsName
          t.detailId = t.id
          t.id = t.goodsId
        })
        this.selectGoodsList = e.orderDetailList
      }
    },
    numChange(e, index) {
      console.log(e)
      if (e <= 0) {
        this.selectGoodsList.splice(index, 1)
      }
    },
    addClear() {
      let findList = this.selectGoodsList.filter(e => e.id != null)
      this.selectGoodsList = findList
      // this.selectOrderInfo = {};
    },
    handleClear() {
      this.selectGoodsList = []
      // this.selectOrderInfo = {};
    },
    tabPosTypeChange(e) {
      this.loadGoodsType()
    },
    tabGoodsTypeChange(e) {
      this.loadGoods()
    },
    loadGoodsType() {
      getAction('/rooms/cesStockType/getTopTypesByPosType', {
        posType: this.tabPosTypeId
      }).then((res2) => {
        if (res2.success) {
          this.goodsTypeList = res2.result
          if (this.goodsTypeList && this.goodsTypeList.length > 0) {
            this.loadGoods()
          }
        }
      })
    },
    loadGoods() {
      var ids = []
      if (this.tabgoodsTypeId === '1') {
        this.goodsTypeList.forEach((t) => {
          ids.push(t.id)
        })
      } else {
        ids.push(this.tabgoodsTypeId)
      }
      this.dataSource = [
        {
          id: '0'
        }
      ]
      getAction('/pos/posSellClearGoods/list', {
        pageNo: 1,
        pageSize: 99999,
        goodTypes: ids
      }).then((res) => {
        if (res.success) {
          this.dataSource = [...this.dataSource, ...res.result.records]
        }
      })
      getAction('/pos/posSellClearGoods/thali-list', {
        pageNo: 1,
        pageSize: 99999,
        goodTypes: ids
      }).then((res) => {
        if (res.success) {
          this.dataSource2 = res.result.records
        }
      })
    },
    handleDelete() {
      deleteAction('/pos/posSellClearGoods/delete', {
        goodsId: this.selectGoods.id
      })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
            this.sellClear = 0
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    handleSelectCheckInRoomOrder() {
      this.$refs.modalSelectCheckInRoomOrderModal.add()
      this.$refs.modalSelectCheckInRoomOrderModal.title = '选择转帐人'
      this.$refs.modalSelectCheckInRoomOrderModal.disableSubmit = false
    },
    handlePickingGoodsOrder() {
      this.$refs.modalPickingGoodsOrderForm.add()
      this.$refs.modalPickingGoodsOrderForm.title = '取单'
      this.$refs.modalPickingGoodsOrderForm.disableSubmit = false
    },
    handleAddTempGoods() {
      this.$refs.modalGoodsForm.add()
      this.$refs.modalGoodsForm.title = '新增菜品'
      this.$refs.modalGoodsForm.disableSubmit = false
    },
    /**
     * 确认挂房账
     */
    handleToRoomFeePayment() {
      let param = Object.assign({ toRoomFeeOrderId: this.selectRoomOrder.livingOrderId }, this.getParam())
          postAction('/pos/posOrderGoods/addRoomFee', param).then(resp => {
        if (resp.result === true) {
          this.$message.success('挂账成功')
          this.modalFormOk()
        } else {
          this.$message.warning('挂账失败')
        }
      })
    },
    /** 结账 */
    handlePayment() {
      if (!this.selectGoodsList || this.selectGoodsList.length <= 0) {
        this.$message.warning('请先选择商品')
        return
      }
      if (this.posTableId === '') {
        this.handleAdd()
        this.settleAccounts(this.selectOrderInfo.code, this.getParam())
      } else {
        // 桌台结账时，订单在下单的时候就添加了，不用传参
        this.settleAccounts(this.selectOrderInfo.code, null)
      }
    },
    settleAccounts(orderCode, params) {
      console.log(orderCode)
      var amount = this.selectGoodsList.reduce(function (total, item) {
        return total + item.sellingPrice * item.num
      }, 0)
      console.log('2222222', params)
      this.$refs.modalPaymentForm.edit({
        billAmount: amount,
        deposit: 0,
        roomFee: amount,
        subjectType: 5,
        feeType: 2,
        preferentialType: 1,
        couponFirstAmount: 0,
        discount: 9,
        orderCode: orderCode,
        params: params
      })
      this.$refs.modalPaymentForm.title = 'POS结账'
      this.$refs.modalPaymentForm.disableSubmit = false
    },
    /**
     * 下单
     */
    placeOrder() {
      this.handleAdd()
    },
    pendingOrder() {
      this.selectOrderInfo.isPending = true
      this.handleAdd()
      this.clean()
    },
    handleAdd(callback) {
      if (!this.selectGoodsList || this.selectGoodsList.length <= 0) {
        this.$message.warning('请先选择商品')
        return
      }
      console.log(this.selectGoodsList)
      let param = this.getParam()
      postAction('/pos/posOrderGoods/add', param)
        .then((res) => {
          if (res.success) {
            this.oldSelectGoodsList = JSON.parse(JSON.stringify(this.selectGoodsList))
            this.selectOrderInfo = res.result
            this.loadGoods()
            if (this.posTableId !== '') {
              this.$emit('reTable')
            }
            if (callback) {
              callback(res.result.code)
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },

    getParam() {
      var _info = JSON.parse(localStorage.getItem('storeInfo'))
      var model = {
        goodsId: this.selectGoods.id,
        posTableId: this.posTableId,
        id: this.selectOrderInfo.id,
        posType: this.tabPosTypeId,
        isPending: this.selectOrderInfo.isPending
      }
      if (_info) {
        model.hotelId = _info.id
      }

      if (this.remark) {
        model.remarks = this.remark
      }
      var posOrderGoodsDetailList = []
      this.selectGoodsList.forEach((t) => {
        // 过滤掉订单中已经保存的商品
        if (t.detailId != null) {
          return
        }
        if (t.cesGoodsList == null) {
          posOrderGoodsDetailList.push({
            goodsId: t.goodsId,
            num: t.num,
            money: t.sellingPrice
          })
        } else {
          let childDetails = []
          t.cesGoodsList.forEach(goods => {
            childDetails.push({
              goodsId: goods.id,
              thaliId: t.goodsId,
              num: t.num * goods.thaliNum,
              money: 0
            })
          })
          posOrderGoodsDetailList.push({
            childDetails,
            id: t.id,
            thaliId: t.goodsId,
            num: t.num,
            money: t.sellingPrice
          })
        }
      })
      model.posOrderGoodsDetailList = posOrderGoodsDetailList
      return model
    },

    itemClick(row) {
      console.log(row)
      if (row.id == '0') {
        this.handleAddTempGoods()
        return
      }
      // if (row.isSellClear) {
      //   this.$message.warning('选择的商品已沽清')
      //   return
      // }
      if (row.inventory <= 0) {
        this.$message.warning('选择的商品已沽清')
        return
      }
      if (this.posTableId !== '' && this.posTableState !== 1) {
        this.posTableState = 1
      }
      var good = JSON.parse(JSON.stringify(row))
      this.$set(good, 'num', 1)
      // 如果选的是套餐，这个地方是套餐id
      this.$set(good, 'goodsId', good.id)
      delete good.id
      var find = this.selectGoodsList.find((t) => t.inventory != null && t.goodsId === row.id)
      if (find) {
        if (find.inventory > find.num) {
          find.num++
        }
      } else {
        this.selectGoodsList.push(good)
      }
    },
    itemClick2(row) {
      console.log(row)
      var good = JSON.parse(JSON.stringify(row))
      this.$set(good, 'num', 1)
      this.$set(good, 'goodsId', good.id)
      delete good.id
      var find = this.selectGoodsList.find((t) => t.goodsId === row.id)
      if (find) {
        find.num++
      } else {
        this.selectGoodsList.push(good)
      }
    },
    // 联台按钮
    unionStation(val,index) {
      if (val == '转菜' && (this.transferDishesList.length !== this.selectedRows.length)) {
        this.$message.error('勾选的商品中有未下单的商品，不能进行转菜操作')
        return
      }
      this.unionTitle = val
      this.unionOpen = true
      this.uniteDataSource = []
      this.loadRegion(index)
    },
    // 联台确认
    handleOk() {
      console.log(this.model.reserveTableList);
      if (this.unionTitle == '换台') {
        console.log(111);
        getAction(`/pos/posOrderGoods/change-table?posOrderId=${this.orderId}&tableId=${this.model.reserveTableList[0].id}`).then(res => {
          console.log(res);
          if (res.success) {
            this.$message.success('换台成功')
          }
          this.unionOpen = false
        })
      } else if (this.unionTitle == '转菜') {
        let tempList = []
        this.transferDishesList.forEach(index => {
          tempList.push(index.id)
        })
        postAction(`/pos/posOrderGoods/transfer-dishes?posOrderId=` + this.model.reserveTableList[0].posOrderGoods.id,tempList).then(res => {
          console.log(res);
          if (res.success) {
            this.$message.success('转菜成功')
          }
          // this.itemClick2()
          this.getOrderByTableId(this.tableId)
          this.loadGoods()
          this.unionOpen = false
        })
      } else {
        let tempdata = []
        this.model.reserveTableList.forEach(index => {
          tempdata.push(index.posOrderGoods.id)
        })
        postAction(`/pos/posOrderGoods/merge-order?mainPosOrderId=` + this.selectOrderInfo.id,tempdata).then(res => {
          console.log(res);
          if (res.success) {
            this.$message.success('联台成功')
          }
          this.unionOpen = false
        })
      }
      
      console.log(this.posTableId);
    },
    // 联台大厅tab切换
    tabRegionChange() {
      this.loadTables();
    },
    // 联台大厅tab获取
    loadRegion(index) {
      getAction("/pos/posRegion/list", {
        posTypeId: this.tabPosTypeId,
      }).then((res) => {
        console.log(res);
        if (res.success) {
          this.regionList = res.result.records;
        }
      });
      this.loadTables(index);
    },
    // 联台大厅数据获取
    loadTables(index) {
      var obj = {
        pageNo: 1,
        pageSize: 99999,
        posTypeId: this.tabPosTypeId,
        state: index,
      };
      if (this.tabPosRegionId != "1") {
        obj.posRegionId = this.tabPosRegionId;
      }
      // getAction("/pos/posTable/tableList", obj).then((res) => {
      //   console.log(res);
      //   if (res.success) {
      //     this.uniteDataSource = res.result.records;
      //     console.log(this.uniteDataSource);
      //   }
      // });
      getAction("/pos/posTable/getCanUseTable", obj).then((res) => {
        console.log(res);
        if (res.success) {
          this.uniteDataSource = res.result.records;
          console.log(this.uniteDataSource);
        }
      });
    },
    // 联台点击
    orderMeal(item) {
      console.log(this.unionTitle);
      if (this.unionTitle == '换台' || this.unionTitle == '转菜') {
        this.model.reserveTableList = []
        if (this.model.reserveTableList.some((t) => t.id == item.id)) {
            this.model.reserveTableList = this.model.reserveTableList.filter(
                (t) => t.id != item.id
            );
        } else {
            this.model.reserveTableList = [item];
        }
      } else {
        if (this.model.reserveTableList.some((t) => t.id == item.id)) {
            this.model.reserveTableList = this.model.reserveTableList.filter(
                (t) => t.id != item.id
            );
        } else {
            this.model.reserveTableList.push(item);
        }
      }
      console.log(this.model.reserveTableList);
    },
    // 取消联台
    unlink() {
      getAction(`/pos/posOrderGoods/return-merge-order?posOrderId=${this.orderId}`).then((res) => {
        if (res.success) {
          this.$message.success('取消联台成功')
        }
        this.unionOpen = false
      });
      
    }
  }
}
</script>

<style scoped>
@import "~@assets/less/common.less";

.room-item {
  height: 110px;
  /* line-height: 200px; */
  font-size: 13px;
  padding: 0px 5px;
  border-radius: 5px;
  cursor: pointer;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.check {
  border: #000 solid 3px;
}

.ant-table-wrapper {
  height: calc(100vh - 500px);
}

/deep/ .card-pd .ant-card-body {
  padding: 0 !important;
}

.select-cell {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 10;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.to_be_ordered_style {
  border: 2px solid #000;
  color: #fff;
}
/* .to_be_ordered_style {
  background-color: #00a0e9;
  border: 2px solid #000;
  color: #fff;
}
.wait_for_account_style{
  border: 2px solid #000;
  background-color: #0a7a72;
  color: #fff;
} */
.active {
    border: #ff5500 2px solid !important;
}
</style>
