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

    <div class="filter-container">
      <el-input size="mini" v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item"/>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
      <el-input size="mini" v-model="search.keyWord" placeholder="发货方式" style="width: 200px;" class="filter-item"/>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        发货方式搜索
      </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="deliverOrders">
        出库
      </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="getList"/>
        </el-tooltip>
      </div>

      <el-table
        :data="tableData"
        height="800"
        v-loading="listLoading"
        ref="stockItemTable"
        @row-click="handleClickTableRow"
        :row-key="getRowKey"
        border
        style="margin-top: 10px"
        default-expand-all
        :tree-props="{children: 'deliverInformList'}"
        :row-class-name="tableRowClassName"
        @selection-change="onTableSelectionChange">
        <el-table-column
          fixed
          type="selection"
          :selectable="ifRowCanSelect"
          width="55">
        </el-table-column>
        <template v-for="column in columnNames">
          <el-table-column
            :prop="column.field"
            :label="column.name"
            :width="column.width"
            show-overflow-tooltip>
          </el-table-column>
        </template>
        <el-table-column label="本次发货信息" width="125px" fixed="right">
          <template slot-scope="scope">
            <el-popover
              placement="top-start"
              title="包数详情"
              width="200"
              trigger="hover"
              v-show="scope.row.calcFlag"
              :content="scope.row.currentDeliverInfo">
              <el-button slot="reference">{{ scope.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 || scope.row.handleFlag === 2"
                @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 || scope.row.handleFlag === 1"
                @click="handleMinusAStock(scope.$index, scope.row)"></i>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
      <pagination
        v-show="listData.total>0"
        :total="listData.total"
        :page.sync="listData.page"
        :limit.sync="listData.pageSize"
        @pagination="getList"/>
    </div>
  </div>
</template>

<script>
import {deliveryOutStock, enforceFinishDelivery, getDeliveryOrderList} from '@/api/delivery/delivery'

const defaultItems = [
  {
    name: '产品类型', field: 'productName', width: ''
  },
  {
    name: '订单编号', field: 'orderCode', width: ''
  },
  // {
  //   name: '应收单号', field: 'financeCode', width: ''
  // },
  {
    name: '客户名称', field: 'clientName', width: ''
  },
  {
    name: '订单数量', field: 'orderQty', width: ''
  },
  {
    name: '已入库数量/本次发货数量', field: 'boxedOrderQty', width: '125px'
  }
]

export default {
  data() {
    return {
      search: {
        keyWord: ''
      },
      columnNames: Object.assign([], defaultItems),

      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },

      listLoading: false,
      tableData: [],

      dialogStockVisible: false,
      stockOrders: [],

      stockInputType: 0, // 包数输入方式 0:等量输入,计算包数/1:箱数*数量表格

      style1StockInfo: {
        boxCount: 1
      }
    }
  },
  mounted() {
    this.getList()
    // this.getMockDate()
  },
  methods: {
    getList() {
      const _that = this
      _that.listLoading = true
      const params = _that.search
      const page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      const data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      // console.log(data);
      getDeliveryOrderList(data).then(response => {
        console.log(response)
        //  组合表单数据
        response.data.forEach(x => {
          x.canSelect = true // 主表数据
          x.deliverInformList.forEach(y => {
            y.productName = y.linkMan // 联系人
            y.orderCode = y.linkPhone // 联系电话
            y.financeCode = y.sendProvince + y.sendCity + y.sendDistrict + y.sendAddress // 地址
            y.clientName = y.sendKind // 发货方式
            y.boxedOrderQty = y.addressQty // 需求数量

            y.canSelect = false // 子表数据
          })
        })
        _that.tableData = response.data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    getRowKey(row) {
      return row.canSelect + row.id
    },

    tableRefresh() {
      this.getList()
      // this.getMockDate()
    },
    searchData() {
      this.listData.page = 1
      this.getList()
      // this.getMockDate()
    },

    handleClickTableRow(row, event, column) {
      if (!row.canSelect) return
      this.$refs.stockItemTable.toggleRowSelection(row)
    },

    onTableSelectionChange(val) {
      this.stockOrders = val
    },

    onStockInputStyleChange(val) {
      switch (val) {
        case 0: {
          // 等量输入
          break
        }
        case 1: {
          // 表格输入
          break
        }
      }
    },
    // 判断行置否能选取,子表数据行不允许选择
    ifRowCanSelect(row, index) {
      return row.canSelect
    },

    // 入库退回
    // backToStock() {
    //   if (this.stockOrders.size() === 0) {
    //     this.$message.error('请选择记录')
    //     return
    //   }
    //
    //   const params = this.stockOrders.map(x => x.id).join(',')
    //   const data = {
    //     'ids': params
    //   }
    //   // console.log(data);
    //   const _that = this
    //   orderStockItemBack(data).then(response => {
    //     console.log(response)
    //     _that.$message.success('打包已退回')
    //     _that.tableRefresh()
    //   }).catch(err => {
    //     _that.$message.error(err)
    //   })
    // },

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

      this.stockOrders.forEach(x => {
        // 先判断库存数量是否够本次发货
        let totalDeliver = 0
        x.deliverInformList.forEach(y => {
          totalDeliver += y.addressQty
        })

        if (totalDeliver > x.boxedOrderQty) {
          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 - x
        })

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

        // 取出本次待发货的地址信息
        x.deliverInformList.forEach(y => {
          const currentStockLabels = []
          let currentSendQty = y.addressQty
          x.stockLabels.forEach(z => {
            if (z.usedFlag) return // 被别人拿过了
            if (currentSendQty >= z.labelQty) {
              // 这包拿了
              z.usedFlag = true
              currentStockLabels.push(z)
              currentSendQty -= z.labelQty
            }
          })
          y.currentStockLabels = currentStockLabels

          // 判断一下拿到的包数和要发的数量是否一致,不一致的话需要人工处理
          y.actualSendQty = 0
          y.currentDeliverInfo = ''
          y.currentStockLabels.forEach(z => {
            y.actualSendQty += z.labelQty
            y.currentDeliverInfo += '1*' + z.labelQty + '\n'
          })
          if (y.actualSendQty !== y.addressQty) y.handleFlag = -1
          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.handleFlag === -1) {
        return 'warning-row'
      }
      return ''
    },
    // 查找任意节点所对应的订单的库存明细
    findOrderStockLabels(row) {
      if (row.canSelect) {
        // 订单row
        return row.stockLabels
      } else {
        // 地址row
        return this.stockOrders.find(x => x.id === row.idOrder).stockLabels
      }
    },
    // 多发一包
    handlePlusAStock(index, row) {
      if (row.handleFlag === 1) {
        this.$message.info('[多发一包]已处理')
        return
      }
      const orderStockLabels = this.findOrderStockLabels(row)
      // 倒序循环,给最小的包
      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.currentStockLabels.forEach(z => {
        row.actualSendQty += z.labelQty
        row.currentDeliverInfo += '1*' + z.labelQty + '\n'
      })
      // 将handleFlag置为已加包处理
      row.handleFlag = 1
    },
    // 少发一包
    handleMinusAStock(index, row) {
      // 由于默认少发一包,所以点的时候只当是确认过了
      if (row.handleFlag === -1) {
        row.handleFlag = 2
        return
      }

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

      const minLabelIndex = row.currentStockLabels.length - 1
      row.currentStockLabels.splice(minLabelIndex, 1)
      row.currentStockLabels.forEach(z => {
        row.actualSendQty += z.labelQty
        row.currentDeliverInfo += '1*' + z.labelQty + '\n'
      })
      // 将handleFlag置为已减包处理
      row.handleFlag = 2
    },
    // 发货
    deliverOrders() {
      if (this.stockOrders.length === 0) {
        this.$message.error('请选择待出库记录')
        return
      }

      const params = this.stockOrders
      const data = JSON.stringify(params)
      // console.log(data);
      const _that = this
      deliveryOutStock(data).then(response => {
        console.log(response)
        _that.$message.success('出库成功')
        _that.tableRefresh()
      }).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)
      })
    },

    onCalcStockBoxNum() {
      if (this.style1StockInfo.boxCount <= 0) {
        this.$message.error('包数输入不正确')
      }
      const _that = this
      this.stockOrders.forEach(x => {
        const toStockCount = x.orderQty - x.stockCount
        const eachContent = Math.ceil(toStockCount / _that.style1StockInfo.boxCount)
        if (eachContent * _that.style1StockInfo.boxCount === toStockCount) {
          // 整除
          x.boxDesc = _that.style1StockInfo.boxCount + '*' + eachContent
        } else {
          // 计算最后那一箱的数量
          const lastBoxContent = toStockCount - (_that.style1StockInfo.boxCount - 1) * eachContent
          x.boxDesc = _that.style1StockInfo.boxCount - 1 + '*' + eachContent + '+' + lastBoxContent + '*1'
        }
      })

      this.dialogStockVisible = false
    }
  }
}
</script>

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

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

<style lang="scss" scoped>
.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);
    }
  }
}
</style>
