<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="searchData"/>
      <el-input
        size="mini"
        v-model="search.printBillCode"
        placeholder="施工单号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="searchData"/>
      <el-input
        size="mini"
        v-model="search.productName"
        placeholder="产品类型"
        style="width: 100px;"
        class="filter-item"
        @keyup.enter.native="searchData"/>
      <el-input
        size="mini"
        v-model="search.sendKind"
        placeholder="发货方式"
        style="width: 100px;"
        class="filter-item"
        @keyup.enter.native="searchData"/>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
      <el-button
        size="mini"
        v-show="canForceSearch"
        class="filter-item"
        type="danger"
        icon="el-icon-search"
        @click="forceSearchData">
        强制搜索
      </el-button>
      <el-switch
        size="mini"
        class="filter-item"
        v-model="search.preparedFlag"
        style="margin-right: 1em"
        inactive-color="#13ce66"
        active-text="半成品已反馈"
        inactive-text="半成品未反馈"
        active-value="1"
        inactive-value="0"
        @change="getList()"
      >
      </el-switch>
      <br><br>
      <el-button
        size="mini"
        class="filter-item"
        type="success"
        @click="onShowStockInputDialog">
        自动计算
      </el-button>
      <el-button
        size="mini"
        class="filter-item"
        type="success"
        @click="onConfirmPackage">
        包数录入
      </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"
        v-loading="listLoading"
        ref="stockOrderTable"
        @row-click="handleClickTableRow"
        @cell-click="handleCellInputClick"
        :cell-style="customCellStyle"
        @sort-change="customSort"
        row-key="id"
        border
        :size="sizeType"
        style="margin-top: 10px"
        @selection-change="onTableSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          fixed
          v-if="canForceComplete"
          label="操作"
          align="center"
          width="80px"
          class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button
              title="强制完成"
              v-show="canForceComplete"
              @click.stop="forceComplete(row.idOrder)"
              type="danger"
              class="iconfont"
              icon="el-icon-delete"
              size="mini">
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          key="productName"
          prop="productName"
          label="产品类型"
          sortable="custom"
          width="130"
          show-overflow-tooltip>
          <template slot-scope="{row}">
            <a href="javascript:;" style="color: #20a0ff" @click.stop="openOrderDetail(row)">{{ row.productName }}</a>
          </template>
        </el-table-column>
        <el-table-column
          key="orderCode"
          prop="orderCode"
          label="订单编号"
          sortable="custom"
          width="130"
          show-overflow-tooltip>
          <template slot-scope="{row}">
            <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row)">{{ row.orderCode }}
              <span v-if="row.businessKind==3"
                    style="display: inline-block;color: red">(补{{ row.rePrintIndex }})</span>
              <el-image v-if="row.firstOrderFlag == 1" :src="new_badge"></el-image></a>
          </template>
        </el-table-column>
        <el-table-column
          key="orderMessage"
          prop="orderMessage"
          label="订单消息"
          show-overflow-tooltip
          width="120">
          <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.stop="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>
        <template v-for="column in columnNames">
          <el-table-column
            :key="column.field"
            :prop="column.field"
            :sortable="column.sortable"
            :label="column.name"
            :width="column.width"
            :formatter="columnFormatter"
            show-overflow-tooltip>
          </el-table-column>
        </template>
        <el-table-column
          fixed="right"
          prop="currentBoxCount"
          label="本次打包数据"
          width="200"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.currentBoxCount"></el-input>
          </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>

    <el-dialog title="入库信息" :visible.sync="dialogStockVisible" width="30%">
      <el-form label-position="top" label-width="80px">
        <el-form-item v-show="false" label="包数输入方式">
          <el-radio-group v-model="stockInputType" @change="onStockInputStyleChange">
            <el-radio label="0">等量输入</el-radio>
            <el-radio label="1">表格输入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="stockInputType === 0" label="包数">
          <el-input-number
            v-model="style1StockInfo.boxCount"
            :min="1"
            label="请输入打包数量"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogStockVisible = false">取 消</el-button>
        <el-button type="primary" @click="onCalcStockBoxNum">确 定</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>
  </div>
</template>

<script>
import {addOrderStockItem, deliveryFormToken, enforceFinishDelivery, getStockOrderList} from '@/api/delivery/delivery'
import OrderDetail from '@/components/orderDetail/orderDetail'
import OrderMessage from '@/components/orderMessage/orderMessage'
import OrderStep from '@/components/orderStep/orderStep'
import {ifPermissionList} from '@/api/printbill/printbill'
import new_badge from '@/assets/new_badge.gif'

const defaultItems = [
  {
    name: '施工单号', field: 'printBillCode', width: '130', sortable: 'custom'
  },
  {
    name: '订单名称', field: 'orderName', width: '130', sortable: false
  },
  {
    name: '客户名称', field: 'clientName', width: '120', sortable: 'custom'
  },
  // {
  //   name: '发货方式', field: 'sendKind', width: '150', sortable: false
  // },
  {
    name: '发货备注', field: 'sendMemo', width: '150', sortable: false
  },
  {
    name: '订单数量', field: 'orderQty', width: '', sortable: false
  },
  {
    name: '已打包数量', field: 'finishQty', width: '120', sortable: false
  },
  {
    name: '下单日期', field: 'checkDate', width: '120', sortable: 'custom'
  },
  {
    name: '交货日期', field: 'deliverDate', width: '180', sortable: 'custom'
  }
]

export default {
  components: {
    OrderStep,
    OrderDetail,
    OrderMessage
  },
  data() {
    return {
      new_badge: new_badge,
      search: {
        keyWord: '',
        searchOrderToBox: 1,
        printBillCode: '',
        productName: '',
        sendKind: '',
        preparedFlag: '1'
      },
      canForceSearch: false,
      canForceComplete: false,
      columnNames: Object.assign([], defaultItems),

      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },
      sizeType: 'mini',

      listLoading: false,
      tableData: [],
      detailVisible: false,

      dialogStockVisible: false,
      stockOrderItems: [],

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

      style1StockInfo: {
        boxCount: 1
      },

      deliverToken: '',

      stepList: [],
      drawer: false,
      memoDrawer: false,
      timeString: ''
    }
  },
  watch: {
    memoDrawer(val) {
      // console.log(val)
      if (!val) {
        this.getList()
      }
    }
  },
  mounted() {
    this.getList()
    this.reqFormToken()
    this.checkPermission()
  },
  methods: {
    testEval() {
      let a = '1+2*100+3-4'
      try {
        console.log('aaaaaaaaaaaaaaaaa' + eval(a))
      } catch {
        console.log('bbbbbbbbbbb')
      }
    },
    forceComplete(idOrder) {
      this.$confirm('确定强制完成？')
        .then(_ => {
          const data = {
            idOrder: idOrder
          }
          // console.log(data);
          const _that = this
          enforceFinishDelivery(data).then(response => {
            console.log(response)
            _that.$message.success('操作成功')
            this.getList()
          }).catch(err => {
            _that.$message.error(err)
          })
        })
        .catch(_ => {
        })
    },
    checkPermission() {
      const _that = this
      var data = {
        'permissions': 'search:admin|delivery:enforce:admin'
      }
      ifPermissionList(data).then(response => {
        // console.log('response', response)
        if (response.httpCode === 200) {
          const permsArr = response.data.split('|')
          if (permsArr[0] === '0') {
            _that.canForceSearch = false
          } else {
            _that.canForceSearch = true
          }

          if (permsArr[1] === '0') {
            _that.canForceComplete = false
          } else {
            _that.canForceComplete = true
          }
        }
      }).catch(err => {
        // _that.$message.error(err)
      })
    },
    getList(sortParam) {
      const _that = this
      _that.listLoading = true
      if (_that.listData.pageSize == 10) {
        _that.sizeType = 'medium'
      } else {
        _that.sizeType = 'mini'
      }
      const params = _that.search
      const page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      let orderBy = ''

      if (sortParam) {
        orderBy = sortParam.prop + ','
        if (sortParam.order === 'descending') {
          orderBy = orderBy + 'desc'
        } else {
          orderBy = orderBy + 'asc'
        }
      }
      const data = {
        'searchData': JSON.stringify(params),
        'page': JSON.stringify(page),
        'orderBy': orderBy
      }
      // console.log(data);
      getStockOrderList(data).then(response => {
        console.log(response)
        //  组合表单数据
        response.data.forEach(x => {
          if (x.packKind === 1) {
            // 按要求打包
            x.currentBoxCount = x.packRequire
          }
        })
        _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
      })

      // 每次查询后把条件重置为正常
      this.search.searchOrderToBox = 1
    },

    stockOrder() {
      const _that = this;
      // const execMathExpress = require('@/utils/execMathExpress');

      for (const x of _that.stockOrderItems) {
        if (x.currentBoxCount === null || x.currentBoxCount === undefined || x.currentBoxCount === '') {
          _that.$message.error('打包数量不正确')
          return
        }
        var regTest = /^(?:(\d+\*\d+)\+)+$/
        var valInput = x.currentBoxCount+'+';
        if(!regTest.test(valInput)){
          _that.$message.error('打包数量存在非法字符,请检查')
          return
        }

        const reg = new RegExp('^[0-9*+]*$')
        const vali = x.currentBoxCount.search(reg)
        if (vali < 0) {
          _that.$message.error('打包数量存在非法字符,请检查')
          return
        }
        try {
          // eslint-disable-next-line no-eval
          eval(x.currentBoxCount)
        } catch (e) {
          _that.$message.error('打包数量存在非法字符,请检查')
          return
        }

        // const packCount = execMathExpress(x.currentBoxCount)
        // console.log(packCount);
      }

      const params = JSON.stringify(_that.stockOrderItems)
      addOrderStockItem(params, _that.deliverToken).then(response => {
        // console.log(response)
        _that.$message({
          type: 'success',
          message: '操作成功!'
        })

        _that.getList()
      }).catch(err => {
        _that.$message.error(err)
      })

      _that.reqFormToken()
    },

    // 获取脚印
    getOrderStep(row) {
      const _that = this
      _that.$refs.orderStep.idOrder = row.idOrder
      _that.$refs.orderStep.getOrderStep()
    },

    customCellStyle({row, column, rowIndex, columnIndex}) {
      if (column.property === 'currentBoxCount') {
        return {
          background: '#f7b1b180'
        }
      }
    },
    customSort({column, prop, order}) {
      if (typeof (prop) === 'undefined') {
        this.getList()
      } else this.getList({prop, order})
    },

    tableRefresh() {
      this.getList()
    },
    searchData() {
      this.listData.page = 1
      this.getList()
    },
    forceSearchData() {
      if ((this.search.keyWord.trim() === '') && (this.search.printBillCode.trim() === '')) {
        this.$message.error('请输入查询条件')
        return
      }
      this.search.searchOrderToBox = 0
      this.listData.page = 1
      this.getList()
    },
    handleClickTableRow(row, column, event) {
      this.$refs.stockOrderTable.toggleRowSelection(row)
    },

    handleCellInputClick(row, column, cell, event) {
      // 避免反选
      if (column.property === 'currentBoxCount') {
        this.$refs.stockOrderTable.toggleRowSelection(row)
      }
    },

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

    onStockInputStyleChange(val) {
      switch (val) {
        case 0: {
          // 等量输入
          break
        }
        case 1: {
          // 表格输入
          break
        }
      }
    },

    onShowStockInputDialog() {
      if (this.stockOrderItems.length <= 0) {
        this.$message.error('未选择订单')
        return
      }

      this.dialogStockVisible = true
    },

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

      this.dialogStockVisible = false
    },

    onConfirmPackage() {
      if (this.stockOrderItems.length <= 0) {
        this.$message.error('未选择订单')
        return
      }
      this.$confirm('确定录入打包信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 进行包签录入操作
        this.stockOrder()
      }).catch(() => {
      })
    },
    // 获取订单信息
    openOrderDetail(row) {
      var _that = this
      _that.detailVisible = true
      _that.$nextTick(() => {
        _that.$refs.orderDetail.idOrder = row.idOrder
        _that.$refs.orderDetail.getInfo()
      })
    },
    // 订单消息
    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()
      })
    },
    columnFormatter(row, column) {
      if (column.property === 'checkDate' || column.property === 'deliverDate') {
        return row[column.property] ? row[column.property].substring(0, 19) : row[column.property]
      } else return row[column.property]
    },
    reqFormToken() {
      const _that = this
      deliveryFormToken().then(response => {
        console.log(response)

        this.deliverToken = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    }
  }
}
</script>
<style>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
  overflow: auto;
}

.stepList .el-card__body {
  padding: 10px;
}

:focus {
  outline: 0;
}
</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>
