<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input size="mini" v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item"
                @keyup.enter.native="tableRefresh"/>
      <el-input size="mini" v-model="search.sendKind" placeholder="发货方式" style="width: 200px;" class="filter-item"
                @keyup.enter.native="tableRefresh"/>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="tableRefresh">
        搜索
      </el-button>

      <br><br>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        @click="calcStockItemToDeliver">
        自动分配库存
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        @click="onShowDeliverInputDialog">
        出库
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        @click="exportSendItem">
        导出发货清单
      </el-button>
      <el-button size="mini" @click="toDeliverDrawer = true">待装车列表（{{ prepareToDeliverItems.length }}）</el-button>
      <!--      <el-button-->
      <!--        class="filter-item"-->
      <!--        type="success"-->
      <!--        size="mini"-->
      <!--        @click="enforceDeliverOrder">-->
      <!--        强制发货完成-->
      <!--      </el-button>-->

      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="tableRefresh"/>
        </el-tooltip>
      </div>

      <div class="rowHoverNone">
        <el-table
          :data="tableData"
          :height="heightTable"
          v-loading="listLoading"
          ref="stockItemTable"
          @cell-click="handleCellInputClick"
          border
          row-key="id"
          style="margin-top: 10px"
          default-expand-all
          :row-class-name="tableRowClassName"
          :size="sizeType"
          v-el-table-infinite-scroll="load"
          infinite-scroll-disabled="disabled"
          @selection-change="onTableSelectionChange">
          <el-table-column
            fixed
            reserve-selection
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="订单信息"
            prop="orderInfo"
            width="300"
            show-overflow-tooltip>
            <template slot-scope="{row}">
              {{ row.productInfo }}
              /
              <a href="javascript:;" style="color: #20a0ff" @click.stop="openOrderDetail(row.idOrder)">{{
                  row.clientNameInfo
                }}
              </a>
              /
              <el-tooltip
                placement="top-start"
                :content="row.orderInfo">
                <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row.idOrder)">{{
                    row.orderObj.orderCode
                  }}
                </a>
              </el-tooltip>

            </template>
          </el-table-column>

          <el-table-column
            label="发货备注"
            prop="sendMemo"
            width="150"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              <span style="color: #F56C6C">{{ row.sendMemo }}</span>
            </template>

          </el-table-column>

          <el-table-column
            label="订单消息"
            width="150"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              <template v-if="row.orderMessage">
                <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>
                <a href="javascript:;" style="color: #20a0ff" @click="openMessage(row)">{{ row.orderMessage }}</a>
              </template>
              <template v-else>
                <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="退回原因"
            prop="feedBackReturnMemo"
            width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="sendKind"
            label="发货方式"
            width="100"
            :sortable=true
            :sort-orders=sortOrder
            show-overflow-tooltip>
          </el-table-column>
          <template v-for="column in columnNames">
            <el-table-column
              :prop="column.field"
              :label="column.name"
              :width="column.width"
              :sortable="column.sortable"
              show-overflow-tooltip>
            </el-table-column>
          </template>
          <el-table-column label="本次发货信息" width="150" fixed="right">
            <template slot-scope="{row}">
              <!--              <el-popover-->
              <!--                placement="left"-->
              <!--                title="包数详情"-->
              <!--                trigger="click"-->
              <!--                v-show="row.calcFlag">-->

              <!--                <div>-->
              <!--                  <el-table :data="row.orderObj.stockLabels" size="mini" max-height="500">-->
              <!--                    <el-table-column fixed type="selection" width="50"></el-table-column>-->
              <!--                    <el-table-column width="100" property="stockPlace" label="库位"></el-table-column>-->
              <!--                    &lt;!&ndash;                  <el-table-column width="80" property="labelNum" label="序号"></el-table-column>&ndash;&gt;-->
              <!--                    <el-table-column width="100" property="labelQty" label="每包数量"></el-table-column>-->
              <!--                  </el-table>-->
              <!--                  <div slot="footer" class="dialog-footer">-->
              <!--                    <el-button size="mini" type="success">确认调整</el-button>-->
              <!--                  </div>-->
              <!--                </div>-->

              <!--                <el-button :size="sizeType" slot="reference" @click="showLabelDetail(row)">-->
              <!--                  {{ row.actualSendQty }}-->
              <!--                </el-button>-->
              <!--              </el-popover>-->
              <!--              <el-tooltip class="item" effect="dark" content="多发一包" placement="top-end">-->
              <!--                <i-->
              <!--                  class="el-icon-circle-plus"-->
              <!--                  v-show="scope.row.handleFlag === -1"-->
              <!--                  @click="handlePlusAStock(scope.$index, scope.row)"></i>-->
              <!--              </el-tooltip>-->
              <!--              <el-tooltip class="item" effect="dark" content="少发一包" placement="top-start">-->
              <!--                <i-->
              <!--                  class="el-icon-remove"-->
              <!--                  v-show="scope.row.handleFlag === -1"-->
              <!--                  @click="handleMinusAStock(scope.$index, scope.row)"></i>-->
              <!--              </el-tooltip>-->

              <el-button :size="sizeType" v-show="row.calcFlag" @click="showLabelDetail(row)">
                {{ row.actualSendQty }}
              </el-button>

              <el-button
                class="top-right-btn"
                :size="sizeType"
                v-show="row.calcFlag && row.currentStockLabels.length > 0"
                :disabled="prepareToDeliverItems.find(x => x.id === row.id)!=undefined"
                @click="prepareToDeliver(row)">
                装车
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--      <el-card class="box-card">-->
      <!--        <div slot="header" class="clearfix">-->
      <!--          <span style="size: 20px">待装车</span>-->
      <!--        </div>-->
      <!--        <div style="position: relative">-->
      <!--          <el-table-->
      <!--            row-key="id"-->
      <!--            :data="prepareToDeliverItems"-->
      <!--            max-height="300"-->
      <!--            ref="prepareDeliverTable"-->
      <!--            :size="sizeType">-->
      <!--            <el-table-column label="操作" width="100" fixed>-->
      <!--              <template slot-scope="{row}">-->
      <!--                <el-button-->
      <!--                  :size="sizeType"-->
      <!--                  @click="toDeliverBack(row)">-->
      <!--                  取消装车-->
      <!--                </el-button>-->
      <!--              </template>-->
      <!--            </el-table-column>-->
      <!--            <el-table-column-->
      <!--              label="订单信息"-->
      <!--              prop="orderInfo"-->
      <!--              width="300"-->
      <!--              show-overflow-tooltip>-->
      <!--              <template slot-scope="{row}">-->
      <!--                {{ row.productInfo }}-->
      <!--                /-->
      <!--                <a href="javascript:;" style="color: #20a0ff" @click.stop="openOrderDetail(row.idOrder)">{{-->
      <!--                    row.clientNameInfo-->
      <!--                  }}-->
      <!--                </a>-->
      <!--                /-->
      <!--                <el-tooltip-->
      <!--                  placement="top-start"-->
      <!--                  :content="row.orderInfo">-->
      <!--                  <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row.idOrder)">{{-->
      <!--                      row.orderObj.orderCode-->
      <!--                    }}-->
      <!--                  </a>-->
      <!--                </el-tooltip>-->
      <!--              </template>-->
      <!--            </el-table-column>-->
      <!--            <el-table-column-->
      <!--              label="订单消息"-->
      <!--              width="150"-->
      <!--              show-overflow-tooltip-->
      <!--            >-->
      <!--              <template slot-scope="{row}">-->
      <!--                <template v-if="row.orderMessage">-->
      <!--                  <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>-->
      <!--                  <a href="javascript:;" style="color: #20a0ff" @click="openMessage(row)">{{ row.orderMessage }}</a>-->
      <!--                </template>-->
      <!--                <template v-else>-->
      <!--                  <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>-->
      <!--                </template>-->
      <!--              </template>-->
      <!--            </el-table-column>-->
      <!--            <el-table-column-->
      <!--              prop="sendKind"-->
      <!--              label="发货方式"-->
      <!--              width="100"-->
      <!--              :sortable=true-->
      <!--              :sort-orders="sortOrder"-->
      <!--              show-overflow-tooltip>-->
      <!--            </el-table-column>-->
      <!--            <template v-for="column in columnNames">-->
      <!--              <el-table-column-->
      <!--                :prop="column.field"-->
      <!--                :label="column.name"-->
      <!--                :width="column.width"-->
      <!--                :sortable="column.sortable"-->
      <!--                show-overflow-tooltip>-->
      <!--              </el-table-column>-->
      <!--            </template>-->
      <!--          </el-table>-->
      <!--        </div>-->
      <!--      </el-card>-->

    </div>
    <el-dialog title="发货信息" :visible.sync="dialogDeliverVisible" width="50%">
      <el-form label-position="left" label-width="80px">
        <el-form-item label="发货方式">
          <el-radio-group @change="orderSendKindChange()" v-model="orderSendKind">
            <el-radio label="配送">配送</el-radio>
            <el-radio label="物流企业">物流企业</el-radio>
            <el-radio label="自提">自提</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="orderSendKind" v-show="orderSendKind !== '自提'">
          <el-select filterable @change="logistChange" v-model="idLogistics" placeholder="请选择">
            <el-option
              v-for="item in availDeliverDoc"
              :key="item.id"
              :label="item.logisticName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运费" v-show="orderSendKind !== '自提'">
          <el-input
            type="number"
            @input="onNumInput"
            v-model="logisticsMoney"
            placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" @input="onInput($event)" v-show="orderSendKind !== '自提'">
          <el-input v-model="linkManPhoneNum" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="车牌号" @input="onInput($event)" v-show="orderSendKind !== '自提'">
          <el-input v-model="plateNumber" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="sendMemo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDeliverVisible = false">取 消</el-button>
        <el-button type="primary" @click="deliverOrdersEx">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-if="sendAdjustOrder"
      :title="sendAdjustOrder.orderCode + ' 包数调整'"
      :close-on-click-modal="false"
      :visible.sync="showOrderSendInfo"
      width="800px">
      <el-row>
        <el-col :span="24">
          <div><b>订单消息:</b> {{ sendAdjustOrder.orderMessage }}</div>
          <div><b>生产备注:</b> {{ sendAdjustOrder.orderMemo }}</div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16">
          <el-table
            :data="sendAdjustOrder.deliverInformList"
            highlight-current-row
            @current-change="adjustAddressChange"
            max-height="500"
            ref="adjustAddressTable"
            border
            size="mini">
            <el-table-column property="address" label="发货地址"></el-table-column>
            <el-table-column property="sendKind" width="100" label="发货方式"></el-table-column>
            <el-table-column property="needDeliverQty" width="80" label="需求数量"></el-table-column>
          </el-table>
        </el-col>
        <el-col :span="8">
          <el-table
            :data="sendAdjustOrder.stockLabels"
            border
            ref="adjustLabelTable"
            @row-click="adjustLabelClickRow"
            :row-class-name="adjustLabelTableRowClass"
            @selection-change="onAdjustLabelSelectionChange"
            size="mini">
            <el-table-column type="selection" :selectable="adjustLabelSelect" width="50"></el-table-column>
            <el-table-column property="stockPlace" label="库位"></el-table-column>
            <!--                  <el-table-column width="80" property="labelNum" label="序号"></el-table-column>-->
            <el-table-column property="labelQty" label="每包数量"></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showOrderSendInfo = false">取 消</el-button>
        <el-button type="primary" @click="confirmOrderAdjust">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="订单详情" :close-on-click-modal="false" class="orderDetailDialog" :visible.sync="detailVisible"
               top="10px" width="1200px">
      <order-detail ref="orderDetail"></order-detail>
    </el-dialog>
    <order-step ref="orderStep"></order-step>
    <el-drawer
      title="订单消息"
      :reverse="true"
      :visible.sync="memoDrawer"
      size="600px">
      <order-message ref="orderMessage"></order-message>
    </el-drawer>

    <!--    <el-drawer-->
    <!--      title="待装车列表"-->
    <!--      direction="btt"-->
    <!--      :reverse="true"-->
    <!--      :visible.sync="toDeliverDrawer"-->
    <!--      size="40%">-->
    <div v-show="toDeliverDrawer"
         style="width: 100%;position: fixed;left: 0px;height: 760px;z-index: 1024;background: #fff;bottom:0px;border-top: 1px solid #ddd;overflow-y: auto;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
      <el-row style="width: 98%;margin: auto">
        <div style="float: left;width: 120px;font-size: 16px;line-height: 40px">待装车列表</div>
        <div style="float: left;width: 120px;font-size: 16px;line-height: 40px">总包数: {{
            prepareToDeliverPackage
          }}
        </div>
        <div style="float: left;width: 120px;font-size: 16px;line-height: 40px">总单数: {{
            prepareToDeliverItems.length
          }}
        </div>
        <div @click="clickClose"
             style="float: right;width: 70px;font-size: 20px;text-align:center;line-height: 40px;color: #333;font-weight: bold;cursor: pointer;">
          <span
            style="font-weight: normal;font-size: 16px;line-height: 40px;vertical-align: middle;padding-bottom: 20px">关闭</span><i
          class="el-icon-close"></i></div>
        <div style="clear: both"></div>
        <div class="elTble">
          <el-table
            row-key="id"
            :data="prepareToDeliverItems"
            max-height="700"
            ref="prepareDeliverTable"
            @row-click="handleClickTableRowEx"
            :row-class-name="tableRowClassNameEx"
            :size="sizeType">
            <el-table-column label="操作" width="100" fixed>
              <template slot-scope="{row}">
                <el-button
                  :size="sizeType"
                  @click="toDeliverBack(row)">
                  取消装车
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              label="订单信息"
              prop="orderInfo"
              width="300"
              show-overflow-tooltip>
              <template slot-scope="{row}">
                {{ row.productInfo }}
                /
                <a href="javascript:;" style="color: #20a0ff" @click.stop="openOrderDetail(row.idOrder)">{{
                    row.clientNameInfo
                  }}
                </a>
                /
                <el-tooltip
                  placement="top-start"
                  :content="row.orderInfo">
                  <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row.idOrder)">{{
                      row.orderObj.orderCode
                    }}
                  </a>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              label="订单消息"
              width="150"
              show-overflow-tooltip
            >
              <template slot-scope="{row}">
                <template v-if="row.orderMessage">
                  <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>
                  <a href="javascript:;" style="color: #20a0ff" @click="openMessage(row)">{{ row.orderMessage }}</a>
                </template>
                <template v-else>
                  <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="sendKind"
              label="发货方式"
              width="100"
              :sortable=true
              :sort-orders="sortOrder"
              show-overflow-tooltip>
            </el-table-column>
            <template v-for="column in columnNamesEx">
              <el-table-column
                :prop="column.field"
                :label="column.name"
                :width="column.width"
                :sortable="column.sortable"
                show-overflow-tooltip>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </el-row>
    </div>
    <!--    </el-drawer>-->
  </div>
</template>

<script>
import {
  deliveryOutStock,
  enforceFinishDelivery,
  exportSendItem,
  getDeliveryOrderList,
  getLogisticsInfoList,
  printSendBill
} from '@/api/delivery/delivery'
import {null2str} from '@/filters'
import {doLocalPrint} from '@/utils'
import elTableInfiniteScroll from 'el-table-infinite-scroll'
import OrderDetail from '@/components/orderDetail/orderDetail'
import OrderMessage from '@/components/orderMessage/orderMessage'
import OrderStep from '@/components/orderStep/orderStep'
import lodash from 'lodash'

const defaultItems = [
  {
    name: '交货时间', field: 'deliverDate', width: '100', sortable: false
  },
  {
    name: '入库时间', field: 'inStockTime', width: '100', sortable: false
  },
  {
    name: '地址', field: 'address', width: '', sortable: false
  },
  {
    name: '库存包数', field: 'stockBoxedQty', width: '60', sortable: false
  },
  {
    name: '需求数量', field: 'needDeliverQty', width: '60', sortable: false
  },
  {
    name: '包数', field: 'packCount', width: '50', sortable: false
  },
  {
    name: '包数详情', field: 'currentDeliverInfo', width: '120', sortable: false
  }
]

const defaultItemsEx = [
  {
    name: '交货时间', field: 'deliverDate', width: '100', sortable: false
  },
  {
    name: '地址', field: 'address', width: '', sortable: false
  },
  {
    name: '需求数量', field: 'needDeliverQty', width: '60', sortable: false
  },
  {
    name: '包数', field: 'packCount', width: '50', sortable: false
  },
  {
    name: '包数详情', field: 'currentDeliverInfo', width: '120', sortable: false
  }
]


export default {
  name: 'toTransferItemList',
  components: {
    OrderStep,
    OrderDetail,
    OrderMessage
  },
  computed: {
    availDeliverDoc() {
      if (this.orderSendKind === '配送') {
        // 物流档案的idLogisticType=3
        return this.deliverDocOptions.filter(x => x.idLogisticType === 3)
      } else if (this.orderSendKind === '物流企业') {
        // 物流档案的idLogisticType=1或者2
        return this.deliverDocOptions.filter(x => x.idLogisticType === 1 || x.idLogisticType === 2)
      }
    },
    noMore() {
      return this.currentOrderCount >= this.listData.total
    },
    disabled() {
      return this.listLoading || this.noMore
    },
    prepareToDeliverPackage() {
      let total = 0
      this.prepareToDeliverItems.forEach(x => {
        total = total + x.currentStockLabels.length
      })
      return total
    }
  },
  directives: {
    'el-table-infinite-scroll': elTableInfiniteScroll
  },
  data() {
    return {
      heightTable: 'auto',
      search: {
        keyWord: '',
        searchOrderToDeliver: 1,
        sendKind: ''
      },
      columnNames: Object.assign([], defaultItems),
      columnNamesEx: Object.assign([], defaultItemsEx),
      sizeType: 'mini',
      listData: {
        total: 0,
        page: 1,
        pageSize: 50
      },
      currentOrderCount: 0,
      clickCheckId: 0,

      listLoading: false,
      tableData: [],
      memoDrawer: false,
      showOrderSendInfo: false,
      sendAdjustOrder: null,
      sendAdjustSelectAddress: {id: 0},
      sendAdjustSelectLabels: [],

      toDeliverDrawer: false,
      prepareToDeliverItems: [],


      sortOrder: ['ascending', null],

      stockOrders: [],
      dialogDeliverVisible: false,
      orderSendKind: '配送',
      logisticsMoney: '',
      idLogistics: '',
      logisticsName: '',
      plateNumber: '',
      idSendMan: '',
      sendMan: '',
      sendMemo: '',
      idLinkMan: '',
      linkMan: '',
      linkManPhoneNum: '',
      sendBillItemList: [],
      detailVisible: false,
      deliverDocOptions: []
    }
  },
  mounted() {
    this.getList()
    // this.getMockDate()
  },
  methods: {
    handleClickTableRowEx(row, event, column) {
      this.clickCheckId = row.id
    },
    tableRowClassNameEx({row, rowIndex}) {
      if (row.id === this.clickCheckId) {
        return 'primary-row'
      }
    },
    clickClose() {
      this.toDeliverDrawer = false;
    },
    // 获取脚印
    getOrderStep(id) {
      const _that = this
      _that.$refs.orderStep.idOrder = id;
      _that.$refs.orderStep.getOrderStep()
    },
    logistChange() {
      const _that = this
      _that.plateNumber = ''
      _that.sendMemo = ''
      _that.linkManPhoneNum = ''

      const deliveryInfo = this.deliverDocOptions.find(x => x.id === this.idLogistics)
      // console.log('deliveryInfo', deliveryInfo)
      if (deliveryInfo !== undefined) {
        _that.logisticsName = deliveryInfo.logisticName
        _that.sendMan = deliveryInfo.logisticName
        _that.linkMan = deliveryInfo.logisticName
        _that.plateNumber = deliveryInfo.carNumber
        _that.idSendMan = deliveryInfo.id
        _that.idLogistics = deliveryInfo.id
        _that.linkManPhoneNum = deliveryInfo.contactPhone
        // _that.deliveryForm.logisticsName = deliveryInfo.logisticName;
        // _that.deliveryForm.sendMan = deliveryInfo.logisticName;
        // _that.deliveryForm.linkMan = deliveryInfo.logisticName;
        // _that.deliveryForm.plateNumber = deliveryInfo.carNumber;
        // _that.deliveryForm.idSendMan = deliveryInfo.id;
        // _that.deliveryForm.idLogistics = deliveryInfo.id;
        // _that.deliveryForm.linkManPhoneNum = deliveryInfo.contactPhone;
      }
      // _that.deliveryForm.plateNumber = deliveryInfo.logisticCode;
      // _that.deliveryForm.plateNumber = deliveryInfo.logisticCode;
    },
    onInput() {
      this.$forceUpdate()
      // alert('1')
    },
    orderSendKindChange(val) {
      const _that = this
      // if(_that.deliveryForm.orderSendKind=="配送" || _that.deliveryForm.orderSendKind=="物流企业"){
      //   _that.deliveryForm.idLogistics = "";
      // }
      if (_that.orderSendKind == '自提') {
        _that.logisticsMoney = ''
      }
    },
    // 展示本次发货包数详情
    showLabelDetail(row) {
      // 先判断装车,已装车不允许修改
      if (this.prepareToDeliverItems.find(x => x.idOrder === row.idOrder)) {
        this.$message.error('该订单已装车,请取消装车再调整')
        return
      }

      // 深拷贝一个出来,避免取消掉原有的数据
      this.sendAdjustOrder = lodash.cloneDeep(row.orderObj)
      // 传进来的时候把自动计算的结果暂时清掉
      this.sendAdjustOrder.deliverInformList.forEach(x => {
        x.currentStockLabels = []
        x.actualSendQty = 0
        x.handleFlag = 0
        x.currentDeliverInfo = ''
        x.packInfo = ''
        x.packCount = 0
      })
      this.sendAdjustOrder.stockLabels.forEach(x => {
        x.usedFlag = false
        x.idDeliverInfo = 0
      })

      this.$nextTick(() => {
        this.$refs.adjustAddressTable.setCurrentRow(this.sendAdjustOrder.deliverInformList[0])
      })

      this.showOrderSendInfo = true
    },
    load() {
      // 滑到底部时进行加载
      setTimeout(() => {
        this.listData.page++ // 页数+1
        this.getList() // 调用接口，此时页数+1，查询下一页数据
      }, 1000)
    },
    // 刷新表格
    tableRefresh() {
      // this.heightTable = 'auto'
      this.listData.page = 1
      this.currentOrderCount = 0
      this.tableData = []
      this.$refs.stockItemTable.clearSelection()
      this.stockOrders = []
      this.getList()
    },
    getList() {
      const _that = this
      _that.listLoading = true
      // if (_that.listData.pageSize == 10) {
      //   _that.sizeType = 'medium'
      // } else {
      //   _that.sizeType = 'mini'
      // }
      const page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      // console.log(data);

      if (_that.search.keyWord) {
        var params = {
          keyWord: _that.search.keyWord,
          searchOrderToDeliver: 1
        }
        var data = {
          'params': JSON.stringify(params),
          'page': JSON.stringify(page)
        }
      } else if (_that.search.sendKind) {
        var params = {
          sendKind: _that.search.sendKind,
          searchOrderToDeliver: 1
        }
        var data = {
          'params': params,
          'page': JSON.stringify(page)
        }
      } else {
        var params = {
          searchOrderToDeliver: 1
        }
        var data = {
          'params': params,
          'page': JSON.stringify(page)
        }
      }
      getDeliveryOrderList(data).then(response => {
        // console.log(response)

        if (response.data.length > 0) {
          _that.heightTable = '700'
          _that.currentOrderCount += response.data.length

          //  组合表单数据
          const deliverInformList = []
          response.data.forEach(x => {
            x.deliverInformList.forEach(y => {
              y.address = null2str(y.sendProvince) + null2str(y.sendCity) + null2str(y.sendDistrict) + null2str(y.sendAddress) // 地址
              y.orderObj = x
              y.orderInfo = '印品名称：' + null2str(x.orderName) + '\n' +
                // '产品类型：' + null2str(x.productName) + '\n' +
                // '订单编号：' + null2str(x.orderCode) + '\n' +

                // '客户名称：' + null2str(x.clientName) + '\n' +
                '订单数量：' + null2str(x.orderQty) + '\n' +
                '库存数量：' + (x.stockCount === null ? 0 : x.stockCount) + '\n'
              // '交货日期：' + parseTime(x.deliverDate, '{y}-{m}-{d}')

              y.productInfo = null2str(x.productName)
              y.orderCodeInfo = null2str(x.orderCode)
              y.clientNameInfo = null2str(x.clientName)
              y.deliverDate = x.deliverDate
              y.orderMessage = x.orderMessage
              y.feedBackReturnMemo = x.feedBackReturnMemo
              y.stockBoxedQty = x.stockBoxedQty
              y.inStockTime = x.inStockTime
              y.sendMemo = x.sendMemo

              deliverInformList.push(y)
            })

            // 将库位信息冗余到包签上
            x.orderStockItemList.forEach(y => {
              y.orderStockLabelList.forEach(z => {
                z.stockPlace = y.stockPlace
              })
            })
          })
          _that.tableData = _that.tableData.concat(deliverInformList) // 主表合并为第一单元格,列表主体为子表显示
          // console.log("2222",_that.tableData);
          _that.listData.total = response.total
        } else {
          _that.heightTable = 'auto'
        }
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })

      // 获取物流档案
      getLogisticsInfoList(params).then(response => {
        // console.log(response)
        _that.deliverDocOptions = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    spanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex in [0, 1, 2, 3]) {
        if (rowIndex === 0) return {rowspan: row.orderObj.deliverInformList.length, colspan: 1}
        if (row.idOrder === this.tableData[rowIndex - 1].idOrder) {
          return {
            rowspan: 0,
            colspan: 0
          }
        } else {
          return {
            rowspan: row.orderObj.deliverInformList.length,
            colspan: 1
          }
        }
      }
    },

    // 订单消息
    openMessage(row) {
      var _that = this
      _that.memoDrawer = true
      _that.$nextTick(function () {
        // console.log(_that.$refs.orderMemo);
        _that.$refs.orderMessage.idOrder = row.idOrder
        _that.$refs.orderMessage.getList()
      })
    },

    onNumInput(e) {
      e = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
      this.logisticsMoney = e
    },

    onShowDeliverInputDialog() {
      var _that = this
      _that.orderSendKind = '配送'
      _that.logisticsMoney = ''
      _that.idLogistics = ''
      _that.logisticsName = ''
      _that.plateNumber = ''
      _that.idSendMan = ''
      _that.sendMan = ''
      _that.sendMemo = ''
      _that.linkMan = ''
      _that.linkManPhoneNum = ''
      _that.sendBillItemList = []
      if (this.prepareToDeliverItems.length === 0) {
        this.$message.error('请先装车')
        return
      }

      // for (const x of this.stockOrders) {
      //   // 判断这订单处理过没
      //   if (!x.stockLabels) {
      //     this.$message.error('请先分配本次发货的库存')
      //     return
      //   }
      //   // 取出本次待发货的地址信息
      //   for (const y of x.deliverInformList) {
      //     if (y.handleFlag < 0) {
      //       this.$message.error('请先针对需要处理的记录进行人工处理')
      //       return
      //     }
      //   }
      // }
      this.dialogDeliverVisible = true
      this.sendBillItemList = []
    },

    // 获取订单信息
    openOrderDetail(idOrder) {
      var _that = this
      _that.detailVisible = true
      _that.$nextTick(() => {
        _that.$refs.orderDetail.idOrder = idOrder
        _that.$refs.orderDetail.getInfo()
      })
    },

    adjustLabelClickRow(row, column, event) {
      if (row.usedFlag && (row.idDeliverInfo !== this.sendAdjustSelectAddress.id)) return false
      this.$refs.adjustLabelTable.toggleRowSelection(row)
    },
    adjustLabelSelect(row, index) {
      return !(row.usedFlag && (row.idDeliverInfo !== this.sendAdjustSelectAddress.id))
    },
    adjustLabelTableRowClass({row, rowIndex}) {
      if (row.usedFlag && (row.idDeliverInfo !== this.sendAdjustSelectAddress.id)) {
        return 'disable-row'
      }
      return ''
    },
    // 确认调整订单包数
    confirmOrderAdjust() {
      // 最后点击确定的时候手工调一次adjustAddressChange写入数据
      this.adjustAddressChange(this.sendAdjustSelectAddress, this.sendAdjustSelectAddress)

      // for (let x in this.stockOrders) {
      //   if (this.stockOrders[x].id === this.sendAdjustOrder.id) {
      //     this.stockOrders[x] = this.sendAdjustOrder
      //     break
      //   }
      // }

      // const tableArr = []
      this.sendAdjustOrder.deliverInformList.forEach(x => {
        for (const i in this.tableData) {
          if (this.tableData[i].id === x.id) {
            this.tableData[i].orderObj = this.sendAdjustOrder
            this.tableData[i].currentStockLabels = x.currentStockLabels
            this.tableData[i].actualSendQty = x.actualSendQty
            this.tableData[i].handleFlag = x.handleFlag
            this.tableData[i].currentDeliverInfo = x.currentDeliverInfo
            this.tableData[i].packInfo = x.packInfo
            this.tableData[i].packCount = x.packCount
            // tableArr.push(this.tableData[i])
            break
          }
        }
      })

      this.showOrderSendInfo = false
      // 我是lowb
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
    },
    // 调整订单发货包数,点击某个地址
    adjustAddressChange(currentRow, oldCurrentRow) {
      this.sendAdjustSelectAddress = currentRow

      if (!oldCurrentRow) return

      oldCurrentRow.currentStockLabels.forEach(x => {
        x.usedFlag = false
        x.idDeliverInfo = 0
      })

      oldCurrentRow.currentStockLabels = []
      this.sendAdjustSelectLabels.forEach(x => {
        if (x.usedFlag && (x.idDeliverInfo !== oldCurrentRow.id)) return // 被别人拿过了
        // 这包拿了
        x.usedFlag = true
        x.idDeliverInfo = oldCurrentRow.id
        oldCurrentRow.currentStockLabels.push(x)
      })

      // 判断一下拿到的包数和要发的数量是否一致,不一致的话需要人工处理
      oldCurrentRow.actualSendQty = 0
      oldCurrentRow.handleFlag = 0
      oldCurrentRow.currentDeliverInfo = ''

      const stockPlaceInfo = []

      oldCurrentRow.currentStockLabels.forEach(z => {
        oldCurrentRow.actualSendQty += z.labelQty
        // y.currentDeliverInfo += '1*' + z.labelQty + '\n'
      })

      const groupedStockPlace = groupBy(oldCurrentRow.currentStockLabels, label => {
        return label.stockPlace
      })

      const grouped = groupBy(oldCurrentRow.currentStockLabels, label => {
        return label.labelQty
      })

      oldCurrentRow.packInfo = ''
      oldCurrentRow.packCount = 0
      grouped.forEach(x => {
        oldCurrentRow.currentDeliverInfo += x.length + '*' + x[0].labelQty + '+'
        oldCurrentRow.packInfo += x.length + '*' + x[0].labelQty + '+'
        oldCurrentRow.packCount += x.length
      })
      oldCurrentRow.currentDeliverInfo = oldCurrentRow.currentDeliverInfo.substr(0, oldCurrentRow.currentDeliverInfo.length - 1)
      oldCurrentRow.packInfo = oldCurrentRow.packInfo.substr(0, oldCurrentRow.packInfo.length - 1)

      groupedStockPlace.forEach(x => {
        stockPlaceInfo.push(x[0].stockPlace)
      })

      oldCurrentRow.currentDeliverInfo += stockPlaceInfo.join(',')
      if (oldCurrentRow.actualSendQty !== oldCurrentRow.needDeliverQty) oldCurrentRow.handleFlag = -1
    },

    handleCellInputClick(row, column, cell, event) {
      if (column.property === 'orderInfo' || column.type === 'selection' || column.property === 'address') {
        this.$refs.stockItemTable.toggleRowSelection(row)
      }
    },

    onTableSelectionChange(selections) {
      this.stockOrders = []
      selections.forEach(deliver => {
        if (!this.stockOrders.find(order => order.id === deliver.idOrder)) {
          this.stockOrders.push(deliver.orderObj)
        }
      })
    },

    onAdjustLabelSelectionChange(selections) {
      this.sendAdjustSelectLabels = selections
    },

    // 分配库存给每个地址
    calcStockItemToDeliver() {
      if (this.stockOrders.length === 0) {
        this.$message.error('请选择待发货订单')
        return
      }

      this.stockOrders.forEach(x => {
        // 判断这订单处理过没
        if (x.stockLabels) return

        // 判断库存数量是否够本次发货
        // let totalDeliver = 0
        // x.deliverInformList.forEach(y => {
        //   totalDeliver += y.needDeliverQty
        // })
        //
        // if (totalDeliver > x.stockCount) {
        //   this.$message.error('订单[' + x.orderCode + ']库存数量不足以本次发货,请联系业务员重新分配发货数量')
        //   return
        // }

        // 取出订单在库的包数信息
        const stockLabels = []
        x.orderStockItemList.forEach(y => {
          y.orderStockLabelList.forEach(z => {
            stockLabels.push(z)
          })
        })

        stockLabels.sort((x, y) => {
          return y.labelQty - x.labelQty
        })

        // console.log(stockLabels)
        x.stockLabels = stockLabels

        // 取出本次待发货的地址信息
        let orderActualSendQty = 0;
        x.deliverInformList.forEach(y => {
          const currentStockLabels = []
          let currentSendQty = y.needDeliverQty
          x.stockLabels.forEach(z => {
            if (z.usedFlag) return // 被别人拿过了
            // 如果量对不上,默认少发一包
            // if (currentSendQty >= z.labelQty) {
            //   // 这包拿了
            //   z.usedFlag = true
            //   z.idDeliverInfo = y.id
            //   currentStockLabels.push(z)
            //   currentSendQty -= z.labelQty
            // }
            // 如果量对不上,默认多发一包
            if (currentSendQty > 0) {
              // 这包拿了
              z.usedFlag = true
              z.idDeliverInfo = y.id
              currentStockLabels.push(z)
              currentSendQty -= z.labelQty
            }
          })
          y.currentStockLabels = currentStockLabels

          // 判断一下拿到的包数和要发的数量是否一致,不一致的话需要人工处理
          y.actualSendQty = 0
          y.handleFlag = 0
          y.currentDeliverInfo = ''

          const stockPlaceInfo = []

          y.currentStockLabels.forEach(z => {
            y.actualSendQty += z.labelQty
            // y.currentDeliverInfo += '1*' + z.labelQty + '\n'
          })

          const groupedStockPlace = groupBy(y.currentStockLabels, label => {
            return label.stockPlace
          })

          const grouped = groupBy(y.currentStockLabels, label => {
            return label.labelQty
          })

          y.packInfo = ''
          y.packCount = 0
          grouped.forEach(x => {
            y.currentDeliverInfo += x.length + '*' + x[0].labelQty + '+'
            y.packInfo += x.length + '*' + x[0].labelQty + '+'
            y.packCount += x.length
          })
          y.currentDeliverInfo = y.currentDeliverInfo.substr(0, y.currentDeliverInfo.length - 1)
          y.packInfo = y.packInfo.substr(0, y.packInfo.length - 1)

          groupedStockPlace.forEach(x => {
            stockPlaceInfo.push(x[0].stockPlace)
          })

          y.currentDeliverInfo += stockPlaceInfo.join(',')

          orderActualSendQty += y.actualSendQty

          if (y.actualSendQty !== y.needDeliverQty) y.handleFlag = -1
          y.calcFlag = true
        })
        //todo 如果全部的地址都分配过了还是没把库存用完,那么这部分地址也标出来
        if (x.stockQty > orderActualSendQty) {
          x.deliverInformList.forEach(y => {
            y.calcFlag = true
          })
        }
      })
      // this.$set(this.$refs.stockItemTable, this.stockOrders[0].$index, this.stockOrders[0])
      // this.$forceUpdate()
      // 这段代码的目的是为了让table重新渲染
      // 因为上面增加了mount阶段没有的新字段,相当于需要重新加载一下整个列表对象
      // 暂时没找到其他方法能够快速的解决
      // 我是lowb
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
    },

    tableRowClassName({row, rowIndex}) {
      if (row.actualSendQty) {
        if(row.actualSendQty!=row.needDeliverQty){
          return 'danger-row'
        }
      }
      for (let i = 0; i < this.stockOrders.length; i++) {
        if (this.stockOrders[i].id == row.idOrder) {
          return "success-row";
        }
      }


      return ''
    },
    // 多发一包
    handlePlusAStock(index, row) {
      if (row.handleFlag === 1) {
        this.$message.info('[多发一包]已处理')
        return
      }
      const stockPlaceInfo = []

      const orderStockLabels = row.orderObj.stockLabels
      // 倒序循环,给最小的包
      for (let i = orderStockLabels.length - 1; i >= 0; i--) {
        const x = orderStockLabels[i]
        if (!x.usedFlag) {
          // 这包拿了
          x.usedFlag = true
          row.currentStockLabels.push(x)
          break
        }
      }
      row.actualSendQty = 0
      row.currentStockLabels.forEach(z => {
        row.actualSendQty += z.labelQty
        // row.currentDeliverInfo += '1*' + z.labelQty + '\n'
      })

      const groupedStockPlace = groupBy(row.currentStockLabels, label => {
        return label.stockPlace
      })

      const grouped = groupBy(row.currentStockLabels, label => {
        return label.labelQty
      })
      row.currentDeliverInfo = ''
      row.packInfo = ''
      row.packCount = 0
      grouped.forEach(x => {
        row.currentDeliverInfo += x.length + '*' + x[0].labelQty + '\n'
        row.packInfo += x.length + '*' + x[0].labelQty + '+'
        row.packCount += x.length
      })
      row.packInfo = row.packInfo.substr(0, row.packInfo.length - 1)

      groupedStockPlace.forEach(x => {
        stockPlaceInfo.push(x[0].stockPlace)
      })

      row.currentDeliverInfo += stockPlaceInfo.join(',')
      // 将handleFlag置为已加包处理
      row.handleFlag = 1
      // 这段代码的目的是为了让table重新渲染
      // 因为上面增加了mount阶段没有的新字段,相当于需要重新加载一下整个列表对象
      // 暂时没找到其他方法能够快速的解决
      // 我是lowb
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
    },
    // 少发一包
    handleMinusAStock(index, row) {
      // 由于默认少发一包,所以点的时候只当是确认过了
      if (row.handleFlag === -1) {
        row.handleFlag = 2
        // 我是lowb
        this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
        this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
        return
      }

      if (row.handleFlag === 2) {
        this.$message.info('[少发一包]已处理')
        return
      }

      const stockPlaceInfo = []

      const minLabelIndex = row.currentStockLabels.length - 1
      row.currentStockLabels.splice(minLabelIndex, 1)
      row.actualSendQty = 0
      row.currentStockLabels.forEach(z => {
        row.actualSendQty += z.labelQty
        // row.currentDeliverInfo += '1*' + z.labelQty + '\n'
      })

      const groupedStockPlace = groupBy(row.currentStockLabels, label => {
        return label.stockPlace
      })

      const grouped = groupBy(row.currentStockLabels, label => {
        return label.labelQty
      })
      row.currentDeliverInfo = ''
      row.packInfo = ''
      row.packCount = 0
      grouped.forEach(x => {
        row.currentDeliverInfo += x.length + '*' + x[0].labelQty + '\n'
        row.packInfo += x.length + '*' + x[0].labelQty + '+'
        row.packCount += x.length
      })
      row.packInfo = row.packInfo.substr(0, row.packInfo.length - 1)

      groupedStockPlace.forEach(x => {
        stockPlaceInfo.push(x[0].stockPlace)
      })

      row.currentDeliverInfo += stockPlaceInfo.join(',')
      // 将handleFlag置为已减包处理
      row.handleFlag = 2
      // 这段代码的目的是为了让table重新渲染
      // 因为上面增加了mount阶段没有的新字段,相当于需要重新加载一下整个列表对象
      // 暂时没找到其他方法能够快速的解决
      // 我是lowb
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
      this.$refs.stockItemTable.toggleRowSelection(this.tableData[0])
    },
    // 装车
    prepareToDeliver(row) {
      if (row.currentStockLabels.length <= 0) {
        this.$message.error('发货数量为0,不能装车')
        return
      }
      // console.log(this.prepareToDeliverItems.find(x => x.id === row.id));
      if (this.prepareToDeliverItems.find(x => x.id === row.id)) return

      this.prepareToDeliverItems.push(row)
    },
    // 取消装车
    toDeliverBack(row) {
      const removeIndex = this.prepareToDeliverItems.findIndex(x => x.id === row.id)
      if (removeIndex >= 0) {
        this.prepareToDeliverItems.splice(removeIndex, 1)
      }
    },
    // 老版发货,代码留存
    deliverOrders() {
      const _that = this
      _that.sendBillItemList = []

      // idSendMan
      // sendMan
      if (!this.orderSendKind) {
        this.$message('请选择发货方式')
        return
      }
      if (!this.orderSendKind) {
        this.$message('请选择发货方式')
        return
      }
      if (this.stockOrders.length === 0) {
        this.$message.error('请选择待出库记录')
        return
      }

      if (!this.idLogistics) {
        this.$message('请选择物流')
        return
      }
      if (_that.orderSendKind == '配送' || _that.orderSendKind == '物流企业') {
        if (!_that.logisticsMoney) {
          this.$message('请填写运费')
          return
        }
      }
      if (!_that.linkManPhoneNum) {
        this.$message('联系电话')
        return
      }

      // for (const i in this.stockOrders) {
      //   for (const j in this.stockOrders[i].deliverInformList) {
      //     if (this.stockOrders[i].deliverInformList[j].currentStockLabels.length <= 0) {
      //       this.$message.error('发货数量不可为0')
      //       return
      //     }
      //   }
      // }

      // console.log(this.stockOrders);
      this.stockOrders.forEach(x => {
        x.deliverInformList.forEach(y => {
          if (y.currentStockLabels.length <= 0) return
          const billItem = {
            idOrder: x.id,
            orderCode: x.orderCode,
            sendPrintQty: y.actualSendQty,
            sendBoxCount: y.currentStockLabels.length,
            idDeliverInfo: y.id,
            orderDeliverSendKind: y.sendKind,
            deliveryInfoVersionCode: y.versionCode,
            sendBillItemLabelList: []
          }
          y.currentStockLabels.forEach(z => {
            const itemLabel = {
              idStockLabel: z.id
            }
            billItem.sendBillItemLabelList.push(itemLabel)
          })
          _that.sendBillItemList.push(billItem)
        })
      })
      if (_that.orderSendKind == '配送') {
        var params = {
          idSendMan: _that.idLogistics,
          linkMan: _that.linkMan,
          linkManPhoneNum: _that.linkManPhoneNum,
          logisticsMoney: _that.logisticsMoney,
          sendMan: _that.sendMan,
          orderSendKind: _that.orderSendKind,
          plateNumber: _that.plateNumber,
          sendBillItemList: _that.sendBillItemList,
          sendMemo: _that.sendMemo
        }
      } else if (_that.orderSendKind == '物流企业') {
        var params = {
          idLogistics: _that.idLogistics,
          linkMan: _that.linkMan,
          linkManPhoneNum: _that.linkManPhoneNum,
          logisticsMoney: _that.logisticsMoney,
          logisticsName: _that.logisticsName,
          orderSendKind: _that.orderSendKind,
          plateNumber: _that.plateNumber,
          sendBillItemList: _that.sendBillItemList,
          sendMemo: _that.sendMemo
        }
      } else if (_that.orderSendKind == '自提') {
        var params = {
          orderSendKind: _that.orderSendKind,
          sendBillItemList: _that.sendBillItemList,
          sendMemo: _that.sendMemo
        }
      }
      // console.log("params",params);
      // return

      const data = JSON.stringify(params)

      deliveryOutStock(data).then(response => {
        // console.log(response)
        if (response.httpCode === 200) {
          _that.$message.success('出库成功')

          // 打印出库单
          const sendBillResult = response.data
          const printParam = {
            'ids': sendBillResult.id
          }
          printSendBill(printParam).then(printResp => {
            const printData = {
              '_rootData': printResp.data.resultMap.PrintData
            }
            // console.log(PrintData);
            const pData = {
              PrintTemplate: 'SendBill.fr3',
              NeedPreview: 1,
              PrintData: JSON.stringify(printData)
            }

            doLocalPrint(pData)
          })

          _that.dialogDeliverVisible = false
          _that.tableRefresh()
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 现版发货
    deliverOrdersEx() {
      const _that = this
      _that.sendBillItemList = []

      // idSendMan
      // sendMan
      if (!this.orderSendKind) {
        this.$message('请选择发货方式')
        return
      }
      if (this.prepareToDeliverItems.length === 0) {
        this.$message.error('装车记录为空')
        return
      }

      // if (!this.idLogistics && (this.orderSendKind !== '自提')) {
      //   this.$message('请选择物流')
      //   return
      // }
      if (_that.orderSendKind == '配送' || _that.orderSendKind == '物流企业') {
        if (!_that.logisticsMoney) {
          this.$message('请填写运费')
          return
        }
      }

      // if (_that.orderSendKind == '配送' || _that.orderSendKind == '物流企业') {
      //   if (!_that.linkManPhoneNum) {
      //     this.$message('联系电话')
      //     return
      //   }
      // }

      // for (const i in this.stockOrders) {
      //   for (const j in this.stockOrders[i].deliverInformList) {
      //     if (this.stockOrders[i].deliverInformList[j].currentStockLabels.length <= 0) {
      //       this.$message.error('发货数量不可为0')
      //       return
      //     }
      //   }
      // }

      // console.log(this.stockOrders);
      this.prepareToDeliverItems.forEach(y => {
        if (y.currentStockLabels.length <= 0) return
        const billItem = {
          idOrder: y.idOrder,
          orderCode: y.orderCodeInfo,
          sendPrintQty: y.actualSendQty,
          sendBoxCount: y.currentStockLabels.length,
          idDeliverInfo: y.id,
          orderDeliverSendKind: y.sendKind,
          deliveryInfoVersionCode: y.versionCode,
          sendBillItemLabelList: []
        }
        y.currentStockLabels.forEach(z => {
          const itemLabel = {
            idStockLabel: z.id
          }
          billItem.sendBillItemLabelList.push(itemLabel)
        })
        _that.sendBillItemList.push(billItem)
      })
      if (_that.orderSendKind == '配送') {
        var params = {
          idLogistics: _that.idLogistics,
          linkMan: _that.linkMan,
          linkManPhoneNum: _that.linkManPhoneNum,
          logisticsMoney: _that.logisticsMoney,
          sendMan: _that.sendMan,
          orderSendKind: _that.orderSendKind,
          plateNumber: _that.plateNumber,
          sendBillItemList: _that.sendBillItemList,
          sendMemo: _that.sendMemo
        }
      } else if (_that.orderSendKind == '物流企业') {
        var params = {
          idLogistics: _that.idLogistics,
          linkMan: _that.linkMan,
          linkManPhoneNum: _that.linkManPhoneNum,
          logisticsMoney: _that.logisticsMoney,
          logisticsName: _that.logisticsName,
          orderSendKind: _that.orderSendKind,
          plateNumber: _that.plateNumber,
          sendBillItemList: _that.sendBillItemList,
          sendMemo: _that.sendMemo
        }
      } else if (_that.orderSendKind == '自提') {
        var params = {
          orderSendKind: _that.orderSendKind,
          sendBillItemList: _that.sendBillItemList,
          sendMemo: _that.sendMemo
        }
      }
      // console.log("params",params);
      // return

      const data = JSON.stringify(params)

      deliveryOutStock(data).then(response => {
        // console.log(response)
        if (response.httpCode === 200) {
          _that.$message.success('出库成功')

          // 打印出库单
          const sendBillResult = response.data
          const printParam = {
            'ids': sendBillResult.id
          }
          printSendBill(printParam).then(printResp => {
            const printData = {
              '_rootData': printResp.data.resultMap.PrintData
            }
            // console.log(PrintData);
            const pData = {
              PrintTemplate: 'SendBill.fr3',
              NeedPreview: 1,
              PrintData: JSON.stringify(printData)
            }

            doLocalPrint(pData)
          })

          _that.dialogDeliverVisible = false
          _that.tableRefresh()
          _that.$refs.stockItemTable.clearSelection()
          _that.prepareToDeliverItems = []
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    exportSendItem() {
      if (this.prepareToDeliverItems.length === 0) {
        this.$message.error('装车记录为空')
        return
      }

      let index = 1
      const sendItemExport = []
      this.prepareToDeliverItems.forEach(y => {
        const stockPlaceInfo = []
        const groupedStockPlace = groupBy(y.currentStockLabels, label => {
          return label.stockPlace
        })
        groupedStockPlace.forEach(x => {
          stockPlaceInfo.push(x[0].stockPlace)
        })

        const grouped = groupBy(y.currentStockLabels, label => {
          return label.labelQty
        })
        const currentDeliverInfo = []
        grouped.forEach(z => {
          currentDeliverInfo.push(z.length + '*' + z[0].labelQty)
        })
        const currentDeliverInfoStr = currentDeliverInfo.join('+')

        let entrustReceive = 0 // 取订单的现金收款
        let shipReceive = 0 // 取订单的物流代收

        let payKind = []
        if (y.orderObj.payKind) {
          payKind = y.orderObj.payKind.split('+')
          payKind.forEach(item => {
            const tmp = item.split(':')
            if (tmp[0] === '0') {
              entrustReceive = tmp[2]
            } else if (tmp[0] === '1') {
              shipReceive = tmp[2]
            }
          })
        }


        const sendItem = {
          index: index,
          stockPlace: stockPlaceInfo.join(','),
          sendArea: y.sendProvince + y.sendCity + y.sendDistrict,
          orderCode: y.orderObj.orderCode,
          clientName: y.orderObj.clientName,
          orderName: y.orderObj.orderName,
          packageCount: y.currentStockLabels.length,
          packDescribe: currentDeliverInfoStr,
          packUnit: '包',
          deliverTime: y.orderObj.deliverDate,
          receiveAddress: y.sendProvince + y.sendCity + y.sendDistrict + y.sendAddress,
          receiveMan: y.linkMan,
          receivePhone: y.linkPhone,
          shipFee: 0,
          entrustReceive: entrustReceive,
          shipReceive: shipReceive,
          sendMemo: y.orderObj.sendMemo,
          sendKind: y.sendKind,
          remark: y.orderObj.orderMessage
        }
        index++
        sendItemExport.push(sendItem)
      })

      const _that = this
      const data = JSON.stringify(sendItemExport)
      exportSendItem(data).then(response => {
        // console.log(response)
        if (response.httpCode === 200) {
          _that.$message.success('导出成功，请前至系统管理-我的任务中进行查看和下载')
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 强制发货完成
    enforceDeliverOrder() {
      if (this.stockOrders.length === 0) {
        this.$message.error('请选择强制发货记录')
        return
      }

      const params = this.stockOrders.map(x => (x.id))
      const data = {
        'idOrders': params.join(',')
      }
      // console.log(data);
      const _that = this
      enforceFinishDelivery(data).then(response => {
        // console.log(response)
        _that.$message.success('强制发货完成')
        _that.tableRefresh()
      }).catch(err => {
        _that.$message.error(err)
      })
    }
  }
}

function groupBy(array, f) {
  // debugger
  const groups = {}
  array.forEach(function (o) { // 注意这里必须是forEach 大写
    const group = JSON.stringify(f(o))
    groups[group] = groups[group] || []
    groups[group].push(o)
  })
  return Object.keys(groups).map(function (group) {
    return groups[group]
  })
}
</script>

<style scoped>
.el-table .warning-row {
  background: #ffd1d1;
}


.el-table .disable-row {
  background: #c2c2c2;
}

.el-table .cell {
  white-space: pre-line;
}

.el-popover {
  white-space: pre-line;
}
</style>

<style lang="scss" scoped>
/* 选中的行背景色 */
::v-deep .el-table .success-row {
  background-color: rgb(255, 244, 232);
}
/* 选中的行背景色 */
::v-deep .el-table .danger-row {
  background-color: rgb(253, 226, 226);;
}

.app-container {
  ::v-deep .el-card__header {
    padding: 5px 15px !important;
    font-size: 14px !important;
  }
}

::v-deep .elTble .el-table .primary-row {
  background: #8cc5ff !important;
  color: #fff !important;
}

.filter-container {
  margin-bottom: 15px;
}

.board-column {
  min-width: 100px;
  min-height: 100px;
  height: auto;
  overflow: hidden;
  background: #f0f0f0;
  border-radius: 3px;

  .board-column-header {
    height: 50px;
    line-height: 50px;
    overflow: hidden;
    padding: 0 20px;
    text-align: center;
    background: #333;
    color: #fff;
    border-radius: 3px 3px 0 0;
  }

  .board-column-content {
    height: auto;
    overflow: hidden;
    border: 10px solid transparent;
    min-height: 60px;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    align-items: center;

    .board-item {
      cursor: pointer;
      width: 100%;
      height: 64px;
      margin: 5px 0;
      background-color: #fff;
      text-align: left;
      line-height: 54px;
      padding: 5px 10px;
      box-sizing: border-box;
      box-shadow: 0px 1px 3px 0 rgba(0, 0, 0, 0.2);
    }
  }
}

.box-card {
  margin-top: 10px;

  ::v-deep .el-card__body {
    padding-bottom: 0;
  }
}
</style>
