<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.id == 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="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>
          <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.price.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>
    </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: ''
    }
  },
  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: {}
    }
  },
  provide() {
    return {
      treeData: computed(() => this.treeData)
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(
            `selectedRowKeys: ${selectedRowKeys}`,
            'selectedRows: ',
            selectedRows
          )
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        },
        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() {
      var res = this.selectGoodsList && this.selectGoodsList.length > 0
      return !res
    }
  },
  created() {
    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: {
    /** 通过桌号查询订单 */
    getOrderByTableId(tableId) {
      getAction('/pos/posOrderGoods/getOrderByTableId', { tableId }).then(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/list', {
        pageNo: 1,
        pageSize: 99,
        orderId: this.selectOrderInfo.code
      }).then((res) => {
        if (res.success) {
          this.selectGoodsList = res.result.records;
          res.result.records.forEach((t) => {
            t.sellingPrice = t.payMoney
            t.name = t.goodsName
            t.id = t.goodsId
          })
          this.selectGoodsList = res.result.records
        }
      });
    },
    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.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()
    },
    handleAdd(callback) {
      if (!this.selectGoodsList || this.selectGoodsList.length <= 0) {
        this.$message.warning('请先选择商品')
        return
      }
      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.id != null) {
          return
        }
        posOrderGoodsDetailList.push({
          id: t.id,
          goodsId: 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)
      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)
      }
    }
  }
}
</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;
}
</style>
