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

    <div class="filter-container">

      <el-input
        v-model="search.keyWord"
        placeholder="关键字"
        style="width: 200px;"
        class="filter-item"
        size="mini"
        @keyup.enter.native="searchData"/>

      <el-button class="filter-item" size="mini" type="primary" :disabled="!canSearch" icon="el-icon-search"
                 @click="searchData">
        搜索
      </el-button>

      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-document" @click="exportData">
        导出
      </el-button>
      <br><br>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        @click="backToStock">
        打包退回
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        @click="printLabel">
        打印包签
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        v-show="!queryStocked"
        @click="stockOrders">
        入库
      </el-button>
      <el-button
        class="filter-item"
        type="success"
        size="mini"
        v-show="!queryStocked"
        @click="stockOrderAndPrint">
        打印标签并入库
      </el-button>

      <el-tag>您一共勾选了{{ stockItems.length }}条</el-tag>

      <div class="top-right-btn">
        <el-switch
          size="mini"
          class="filter-item"
          v-model="queryStocked"
          style="margin-right: 1em"
          inactive-color="#13ce66"
          active-text="查询已入库"
          inactive-text="查询未入库"
          @change="getList()"
        >
        </el-switch>

        <el-tooltip effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList()"/>
        </el-tooltip>
      </div>

      <div class="rowHoverNone elTble">
        <el-table
          :data="tableData"
          v-loading="listLoading"
          ref="stockItemTable"
          @row-click="handleClickTableRow"
          :row-class-name="tableRowClassName"
          :cell-style="customCellStyle"
          @sort-change="customSort"
          :summary-method="getSummaries"
          show-summary
          row-key="id"
          border
          style="margin-top: 10px"
          :size="sizeType"
          max-height="700"
          @selection-change="onTableSelectionChange">
          <el-table-column
            type="selection"
            width="55"
            :reserve-selection="true">
          </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="productTypeName"
            prop="productTypeName"
            label="产品类型"
            width="130"
            show-overflow-tooltip>
            <template slot-scope="{row}">
              <a href="javascript:;" style="color: #20a0ff" @click.stop="openOrderDetail(row)">{{
                  row.productTypeName
                }}</a>
            </template>
          </el-table-column>
          <el-table-column
            key="orderCode"
            prop="orderCode"
            sortable="custom"
            label="订单编号"
            width="130"
            show-overflow-tooltip>
            <template slot-scope="{row}">
              <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row)">{{ row.orderCode }}</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.stop="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.stop="openMessage(row)"></el-button>
              </template>
            </template>
          </el-table-column>
          <template v-for="column in columnNames">
            <el-table-column
              :key="column.field"
              :prop="column.field"
              :label="column.name"
              :width="column.width"
              :sortable="column.sortable"
              show-overflow-tooltip>
            </el-table-column>
          </template>
          <el-table-column
            fixed="right"
            prop="stockLocation"
            label="库位"
            width="200"
            show-overflow-tooltip>
            <template slot-scope="{row}">
              <el-select
                size="mini"
                v-model="row.stockPlace"
                placeholder="请选择"
                filterable
                allow-create
                clearable
                default-first-option
                style="width: 80%">
                <el-option
                  v-for="item in stockLocationList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
              <el-tooltip class="item" effect="dark" content="保存库位" placement="top">
                <el-button
                  type="primary"
                  size="mini"
                  circle
                  icon="el-icon-check"
                  @click.stop="saveStockLocation(row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>

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

      <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" @addMessageHandle="addMessageHandle"></order-message>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import {
  deliveryFormToken,
  enforceFinishDelivery,
  getOrderStockItemList,
  getOrderStockItemCount,
  getPrintLabelInfo,
  orderInStock,
  orderInStockAndPrint,
  orderStockItemBack,
  saveStockPlace
} from '@/api/delivery/delivery'
import OrderDetail from '@/components/orderDetail/orderDetail'
import OrderMessage from '@/components/orderMessage/orderMessage'
import {getDictTypeInfo} from '@/api/complaint/complaintRegister'
import {doLocalPrint} from '@/utils'
import OrderStep from '@/components/orderStep/orderStep'
import {formatMoney} from '@/filters'
import {ifPermissionList} from '@/api/printbill/printbill'
import {exportData} from "@/api/orderCharge/orderCollection";

const defaultItems = [
  {
    name: '施工单号', field: 'printBillCode', width: '130'
  },
  {
    name: '订单名称', field: 'orderName', width: '130'
  },
  {
    name: '客户名称', field: 'clientName', width: '120'
  },
  {
    name: '发货方式', field: 'sendKind', width: '120'
  },
  {
    name: '交货日期', field: 'deliverDate', width: '120'
  },
  {
    name: '在库包数', field: 'inStockBoxedCount', width: '80'
  },
  {
    name: '订单数量', field: 'orderQty', width: '80'
  },
  {
    name: '打包数量', field: 'itemPrint', width: '80'
  },
  {
    name: '包数', field: 'boxCount', width: '80'
  },
  {
    name: '本次打包数据', field: 'boxDesc', width: '120'
  },
  {
    name: '操作人', field: 'boxedMan', width: '80', sortable: 'custom'
  },
  {
    name: '入库时间', field: 'inStockDate', width: '120', sortable: 'custom'
  }
]

export default {
  name:"stockItemList",
  components: {
    OrderStep,
    OrderDetail,
    OrderMessage
  },
  data() {
    return {
      queryStocked: false,
      clickCheckId: 0,
      search: {
        keyWord: '',
        isInStock: 0
      },
      columnNames: Object.assign([], defaultItems),
      canForceComplete: false,

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

      listLoading: false,
      tableData: [],
      collection: {},

      stockItems: [],
      deliverToken: '',

      stockLocationList: [], // 库位,字典获取

      detailVisible: false,
      stepList: [],
      drawer: false,
      memoDrawer: false,
      timeString: '',
      canSearch: true
    }
  },
  // watch: {
  //   memoDrawer(val) {
  //     // console.log(val)
  //     if (!val) {
  //       this.getList()
  //     }
  //   }
  // },
  mounted() {
    this.getList()
    this.getStockLocation()
    this.checkPermission()
    this.reqFormToken()
  },
  methods: {
    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(_ => {
        })
    },
    addMessageHandle(data) {
      const _that = this
      _that.tableData.forEach(item => {
        if (item.idOrder == data.idBill) {
          item.orderMessage = data.messageStr
        }
      })
    },
    checkPermission() {
      const _that = this
      var data = {
        'permissions': '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.canForceComplete = false
          } else {
            _that.canForceComplete = true
          }
        }
      }).catch(err => {
        // _that.$message.error(err)
      })
    },
    tableRowClassName({row, rowIndex}) {
      if (row.id === this.clickCheckId) {
        return 'primary-row'
      }
    },
    getList(sortParam) {
      const _that = this
      _that.listLoading = true
      if (_that.listData.pageSize == 10) {
        _that.sizeType = 'medium'
      } else {
        _that.sizeType = 'mini'
      }
      if (_that.queryStocked) {
        _that.search.isInStock = 1
      } else {
        _that.search.isInStock = 0
      }

      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 = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page),
        'orderBy': orderBy
      }
      // console.log(data);
      getOrderStockItemList(data).then(response => {
        console.log(response)
        // //  组合表单数据
        _that.tableData = response.data
        _that.listData.total = response.total
        //_that.collection = response.collection
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
      getOrderStockItemCount(data).then(response => {
        //console.log(response)
        _that.collection = response.collection
        // _that.listLoading = false

        this.canSearch = true
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false

        this.canSearch = true
      })
    },
    getSummaries(param) {
      var _that = this
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.label == '在库包数') {
          sums[index] = formatMoney(_that.collection.inStockBoxedCount)
        } else if (column.label == '订单数量') {
          sums[index] = formatMoney(_that.collection.orderQtyCount)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    customSort({column, prop, order}) {
      console.log(prop)
      if (typeof (prop) === 'undefined') {
        this.getList()
      } else this.getList({prop, order})
    },
    tableRefresh() {
      this.stockItems = []
      this.$refs.stockItemTable.clearSelection()
      this.getList()
    },
    searchData() {
      this.canSearch = false
      this.listData.page = 1
      this.getList()

    },

    handleClickTableRow(row, event, column) {
      this.$refs.stockItemTable.toggleRowSelection(row)
      this.clickCheckId = row.id
    },

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

    // 打包退回
    backToStock() {
      if (this.stockItems.length === 0) {
        this.$message.error('请选择记录')
        return
      }
      this.$confirm('确定要打包退回吗？')
        .then(_ => {
          const params = this.stockItems.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)
          })
        })
        .catch(_ => {
        })
    },

    // 打印包签
    printLabel() {
      if (this.stockItems.length === 0) {
        this.$message.error('请选择记录')
        return
      }

      const params = this.stockItems.map(x => x.id).join(',')
      const data = {
        'itemIds': params
      }
      // console.log(data);
      const _that = this
      getPrintLabelInfo(data).then(response => {
        // console.log(response)
        const printTemplateName = response.data.resultMap.printTemplateName
        const printData = {
          '_rootData': response.data.resultMap.orderStockLableList
        }
        // 调用本地打印服务
        const data = {
          PrintTemplate: printTemplateName,
          NeedPreview: 1,
          PrintData: JSON.stringify(printData)
        }

        doLocalPrint(data)
        _that.tableRefresh()
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 入库
    stockOrders() {
      if (this.stockItems.length === 0) {
        this.$message.error('请选择待入库记录')
        return
      }

      const params = this.stockItems
      const data = JSON.stringify(params)
      // console.log(data);
      const _that = this
      orderInStock(data, this.deliverToken).then(response => {
        console.log(response)
        _that.$message.success('入库成功')
        _that.tableRefresh()
      }).catch(err => {
        _that.$message.error(err)
      })

      this.reqFormToken()
    },

    // 打印标签并入库
    stockOrderAndPrint() {
      if (this.stockItems.length === 0) {
        this.$message.error('请选择待入库记录')
        return
      }

      // const params = this.stockItems
      // tt说这地方传输数据太大了,精简一下

      const params = []
      this.stockItems.forEach(x => {
        const item = {
          id: x.id,
          idOrder: x.idOrder,
          stockPlace: x.stockPlace
        }
        params.push(item)
      })

      const data = JSON.stringify(params)
      // console.log(data);
      const _that = this
      orderInStockAndPrint(data, this.deliverToken).then(response => {
        console.log(response)
        _that.$message.success('入库成功')
        const printTemplateName = response.data.resultMap.printTemplateName
        const printData = {
          '_rootData': response.data.resultMap.orderStockLableList
        }
        // 调用本地打印服务
        const data = {
          PrintTemplate: printTemplateName,
          NeedPreview: 1,
          PrintData: JSON.stringify(printData)
        }

        doLocalPrint(data)
        _that.tableRefresh()
      }).catch(err => {
        _that.$message.error(err)
      })

      this.reqFormToken()
    },

    // 获取订单信息
    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()
      })
    },
    // 获取脚印
    getOrderStep(row) {
      const _that = this
      _that.$refs.orderStep.idOrder = row.idOrder
      _that.$refs.orderStep.getOrderStep()
    },

    // 获取成品库位字典
    getStockLocation() {
      const _that = this
      var data = {
        'dictTypeText': 'ProductLocation'
      }

      getDictTypeInfo(data).then(response => {
        console.log(response)
        _that.stockLocationList = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    customCellStyle({row, column, rowIndex, columnIndex}) {
      if (column.property === 'stockLocation') {
        return {
          background: '#f7b1b180'
        }
      }
      if (column.property === 'boxCount') {
        return 'background-color:#1989fa80;color:#000;font-weight:600;'
      }
    },
    // 保存库位信息
    saveStockLocation(row) {
      if (!row.stockPlace || row.stockPlace === '') {
        this.$message.error('请输入库位信息')
        return
      }
      const _that = this
      const data = {
        id: row.id,
        stockPlace: row.stockPlace
      }

      saveStockPlace(data).then(response => {
        console.log(response)
        _that.$message.success('保存库位成功')
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    reqFormToken() {
      const _that = this
      deliveryFormToken().then(response => {
        console.log(response)

        this.deliverToken = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    exportData() {
      const _that = this
      const data = {
        code: 'OrderoStockItem_Exporter',
        exportName: '导出入库清单',
        params: _that.search
      }
      exportData(data).then(res => {
        console.log(res)
        if (res.httpCode === 200) {
          _that.$message.success('导出成功，请前至系统管理-我的任务中进行查看和下载')
        }
      })
    }
  }
}
</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;
}

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

</style>
