/** * 存货打印 */

<template>
  <div class="container-fluid">
    <Navbar title="标签打印" :is-go-back="false" />
    <div class="flex-container" style="margin-top: 10px">
      <div class="flex-header">
        <div>
          <div class="form-inline" role="form">
            <PrintWidget
              ref="printWidget"
              :printer-localstorage-id="'#InventoryPrinterPrinter'"
              @selected-printer-name="getPrintName"
            />

            <div class="form-group">
              <input
                v-model="message"
                autocomplete="off"
                type="text"
                class="form-control"
                placeholder="请输入要打印存货的名称或编码"
                aria-describedby="basic-addon"
                style="width: 350px"
                @keyup.enter="queryInventory"
              />
            </div>
            <div class="form-group">
              <button class="btn btn-default" @click="queryInventory">查询</button>
              <button class="btn btn-default" @click="$refs.printEpc.show()">
                再次打印
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-content" style="margin-top: 10px">
        <table class="fixed-table table-striped table-bordered">
          <thead>
            <tr>
              <th style="width: 50px">序号</th>
              <th style="width: 50px">图片</th>
              <th style="width: 150px">存货名称</th>
              <th style="width: 150px">存货编号</th>
              <th style="width: 150px">规格型号</th>
              <th style="width: 60px">计量单位</th>
              <th style="width: 60px">采购订单编号</th>
              <th style="width: 100px">批号</th>
              <th style="width: 80px">标签个数</th>
              <th style="width: 80px">标签代表数量</th>
              <th style="width: 150px">供应商</th>
              <th style="width: 150px">放置货位</th>
              <th style="width: 60px">
                <button
                  type="button"
                  class="btn btn-default"
                  style="width: 100%"
                  @click="generateAllPack()"
                >
                  打印
                </button>
              </th>
              <th style="width: 100px">
                <button
                  type="button"
                  class="btn btn-default"
                  style="width: 100%"
                  @click="generateAllRepeatPack()"
                >
                  重复打印全部
                </button>
              </th>
            </tr>
          </thead>
          <tbody class="table1">
            <tr v-for="(inventoryInstance, index) in inventoryInstanceDatas" :key="inventoryInstance.id">
              <td>
                {{
                  index +
                    1 +
                    (pagination.current_page - 1) * pagination.per_page
                }}
              </td>
              <td>
                <img
                  :src="
                    Common.getThumbnailImageSrc(className, inventoryInstance.imageNames)
                  "
                  class="image"
                  @click="
                    $refs.imagePreview.preview(className, inventoryInstance.imageNames)
                  "
                />
              </td>
              <td>
                {{ inventoryInstance.inventoryName }}
              </td>
              <td>
                {{ inventoryInstance.inventoryCode }}
              </td>
              <td>
                {{ inventoryInstance.type }}
              </td>
              <td>
                {{ inventoryInstance.computationUnit }}
              </td>
              <td>
                <input
                  v-model="inventoryInstance.purchaseOrderNo"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  style="width: 100%"
                />
              </td>
              <td>
                <input
                  v-model="inventoryInstance.batchNo"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  style="width: 100%"
                />
              </td>
              <td>
                <input
                  v-model="inventoryInstance.packageCount"
                  autocomplete="off"
                  type="number"
                  class="form-control"
                  style="width: 100%"
                />
              </td>
              <td>
                <input
                  v-model="inventoryInstance.quantity"
                  autocomplete="off"
                  type="text"
                  style="width: 100%"
                  class="form-control"
                />
              </td>
              <td>
                <SearchWidget
                  :info-window-no="infoWindowNo1"
                  :field-value="getFieldValue1(inventoryInstance)"
                  :display-name="'v.name'"
                  :where-clause-source="whereClauseSource"
                  @value-changed="valueChanged1($event, inventoryInstance)"
                />
              </td>
              <td>
                <SearchWidget
                  :info-window-no="infoWindowNo2"
                  :field-value="getFieldValue2(inventoryInstance)"
                  :display-name="'p.barCode'"
                  :where-clause-source="whereClauseSource"
                  @value-changed="valueChanged2($event, inventoryInstance)"
                />
              </td>
              <td>
                <button
                  type="button"
                  class="btn btn-default"
                  style="width: 100%"
                  @click="generatePack(inventoryInstance)"
                >
                  打印
                </button>
              </td>
              <td>
                <button
                  type="button"
                  class="btn btn-default"
                  style="width: 100%"
                  @click="generateRepeatPack(inventoryInstance)"
                >
                  重复打印
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="flex-footer">
        <div>
          <div class="form-group">
            <div class="pull-left">
              共查询到<b>{{ pagination.total }}</b>条数据
            </div>
            <div class="pull-right">
              <VueBootstrapPagination
                v-if="pagination.last_page > 0"
                :pagination="pagination"
                :callback="queryInventory"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <PrintEpc ref="printEpc" :printer-name="printerName" />
    <Loading v-if="loading" />
    <ImagePreview ref="imagePreview" />
  </div>
</template>

<script>
import Common from '../common/Common.js';



import InventoryResource from '../api/common/InventoryResource.js';
import InventoryInstancePrintResource from '../api/wms/InventoryInstancePrintResource.js';
import { PrintUtil, PrintWidget } from 'pc-component-v3';

export default {
  components: {
    PrintWidget,
    
  },
  data: function () {
    this.Common = Common;
    return {
      message: '',
      inventoryInstanceDatas: [],
      recordIds: [],
      infoWindowNo1: 283036,
      infoWindowNo2: 283920,
      whereClauseSource: {
        customerDataDimensions:[{
          fieldName: 'organization.id',
          dataDimensionTypeNo: '202201191700',
          defaultDataDimensionTypeValueNo: '1',
        }],
      },
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },
      isUpdatePage: true,
      className: 'com.leanwo.prodog.model.common.Inventory',
      allRepeatPack: [], //重复打印全部的id
      printType: 0, //类型 0:采购入库打印/1:扫描入库打印
      printerName: '',
      loading: false,
      selectedPrinterTitle:'',
    };
  },

  mounted: function () {
    var _self = this;
    _self.queryInventory();

    $('.fixed-table').tableFixer({
      left: 3,
      head: true,
    });

    $('.fixed-table').colResizable({
      resizeMode: 'overflow',
      partialRefresh: true,
    });
  },

  methods: {

    getPrintName:function(value){
      this.selectedPrinterTitle = value;
    },

    getFieldValue1: function (item) {
      var fieldValue1 = {
        id: item.vendorId,
        displayValue: [item.vendorName],
        fieldType: 'Key',
      };
      return fieldValue1;
    },

    getFieldValue2: function (item) {
      var fieldValue2 = {
        id: item.positionId,
        displayValue: [item.savePositionName],
        fieldType: 'Key',
      };
      return fieldValue2;
    },

    // 用户选择框change事件
    valueChanged1: function (newFieldValue, item) {
      item.vendorId = newFieldValue.id;
      item.vendorName = newFieldValue.displayValue[0];
    },

    // 用户选择框change事件
    valueChanged2: function (newFieldValue, item) {
      item.positionId = newFieldValue.id;
      item.savePositionName = newFieldValue.displayValue[0];
    },

    /**
     * 打印选择的全部存货
     */
    generateAllPack: function () {
      var _self = this;
      var quantityFilled = true;
      this.inventoryInstanceDatas.forEach(function (item) {
        if (!item.quantity) {
          quantityFilled = false;
        }
      });

      if (!quantityFilled) {
        Notify.error('提示', '请填写数量', false);
        return;
      }

      var correctQuantity = true;
      this.inventoryInstanceDatas.forEach(function (item) {
        if (parseInt(item.quantity) != item.quantity || item.quantity <= 0) {
          correctQuantity = false;
        }
      });

      if (!correctQuantity) {
        Notify.error('提示', '请输入正整数', false);
        return;
      }

      let selectedPrinter = this.selectedPrinterTitle;
      if (selectedPrinter == null || selectedPrinter.length == 0) {
        Notify.error('提示', '请先选择打印机。', false);
        return;
      }
      $.ajax({
        url: Common.getApiURL(
          'InventoryInstanceResource/generateInventoryInstances?type=' + _self.printType,
        ),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(_self.inventoryInstanceDatas),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (successData) {
          var ids = [];
          if(successData.errorCode == 0) {
            if(successData.datas.length > 0) {
              successData.datas.forEach(function (item) {
                ids.push(item.id);
              });
              _self.print(ids);

              //更新全部重复打印数据
              _self.allRepeatPack = successData.datas;
            }
          } else {
            Notify.error('提示', successData.errorMessage, false);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 重复打印全部
     */
    generateAllRepeatPack: function () {
      var _self = this;
      if (_self.allRepeatPack == null || _self.allRepeatPack.length == 0) {
        Notify.error(
          '提示',
          '请先点击【打印】按钮，然后再点击【重复打印全部】按钮。',
          false,
        );
        return;
      } else {
        var ids = [];
        _self.allRepeatPack.forEach(function (item) {
          ids.push(item.id);
        });
        _self.print(ids);
      }
    },

    /**
     * 打印单个存货
     */
    generatePack: function (inventoryInstance) {
      var _self = this;
      if (!inventoryInstance.quantity) {
        Notify.error('提示', '请填写数量。', false);
        return;
      }
      if (
        parseInt(inventoryInstance.quantity) != inventoryInstance.quantity ||
        inventoryInstance.quantity <= 0
      ) {
        Notify.error('提示', '请输入正整数。', false);
        return;
      }

      let selectedPrinter = this.selectedPrinterTitle;
      if (selectedPrinter == null || selectedPrinter.length == 0) {
        Notify.error('提示', '请先选择打印机。', false);
        return;
      }

      var datas = [];
      datas.push(inventoryInstance);
      $.ajax({
        url: Common.getApiURL(
          'InventoryInstanceResource/generateInventoryInstances?type=' + _self.printType,
        ),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(datas),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
          _self.loading=true;
        },
        success: function (successData) {
          _self.loading=false;
          var ids = [];
          if(successData.errorCode == 0) {
            if(successData.datas.length > 0) {
              successData.datas.forEach(function (item) {
                ids.push(item.id);
              });
              _self.print(ids);

              //更新全部重复打印数据
              _self.allRepeatPack = successData.datas;
            }
          } else {
            Notify.error('提示', successData.errorMessage, false);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 重复打印其中一种
     * @param {Object} inventoryInstance
     */
    generateRepeatPack: function (inventoryInstance) {
      var _self = this;
      var printIds = [];
      _self.allRepeatPack.forEach(function (item) {
        if (item.inventoryId == inventoryInstance.inventoryId) {
          printIds.push(item.id);
        }
      });

      if (printIds == null || printIds.length == 0) {
        Notify.error('提示', '请先点击【打印】按钮，然后再点击【重复打印】按钮。', false);
        return;
      } else {
        _self.print(printIds);
      }
    },

    /**
     * 根据物料名称或者编号查询数据
     */
    queryInventory: function () {
      var _self = this;
      var message = $.trim(this.message);
      if (_self.message.length > 0 && !_self.isUpdatePage) {
        _self.pagination.current_page = 1;
        _self.isUpdatePage = true;
      } else if (_self.message.length <= 0) {
        _self.isUpdatePage = false;
      }
      _self.inventoryInstanceDatas.splice(0, _self.inventoryInstanceDatas.length);

      let inventoryQueryConditionRequest = {
        name: message,
        no: message,
        type: message,
        range: {
          start: (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
      };
      _self.loading=true;
      InventoryResource.findByQueryCodition(inventoryQueryConditionRequest).then(
        baseRangeResponse => {
          _self.loading=false;
          if (baseRangeResponse.errorCode == 0) {
            if(baseRangeResponse.datas != null){
              baseRangeResponse.datas.forEach(function (item) {
                var newInventoryInstance = {
                  inventoryName: item.name,
                  inventoryCode: item.no,
                  quantity: '',
                  batchNo: '',
                  savePositionName: item.savePositionName,
                  computationUnit: item.computationUnit,
                  type: item.type,
                  inventoryId: item.id,
                  vendorId: item.vendorId,
                  positionId: item.positionId,
                  vendorName: item.vendorName,
                  imageNames: item.imageNames,
                  purchaseOrderNo: item.purchaseOrderNo,
                };
                _self.inventoryInstanceDatas.push(newInventoryInstance);
              });
              _self.pagination.total = baseRangeResponse.total;
              _self.pagination.last_page = Math.ceil(
                _self.pagination.total / _self.pagination.per_page,
              );
            }
          }
          //查询清空上一次的打印数据
          _self.allRepeatPack = [];
          _self.fixedTableHeader();
        },
        errorData => {
          _self.loading=false;
          Common.processException(errorData);
        },
      );
    },

    /**
     * 打印文件
     */
    print: function (recordIds) {
      var _self = this;
      var printData = [];

      _self.loading=true;
      InventoryInstancePrintResource.print(recordIds).then(
        baseListResponse => {
          _self.loading=false;
          if (baseListResponse.errorCode == 0) {
            let selectedPrinter = this.selectedPrinterTitle;
            let selectedPrinterType = _self.$refs.printWidget.getSelectedPrinterTypeTitle();
            _self.printerName = selectedPrinter;
            if (selectedPrinterType == '发卡机' || selectedPrinterType == 'Jw发卡机') {
              _self.$nextTick(function () {
                _self.$refs.printEpc.printPrintPages(baseListResponse.datas);
              });
            } else {
              var contents = [];
              baseListResponse.datas.forEach(function (item) {
                var printItem = {
                  id: null,
                  name: null,
                  content: item,
                };
                console.log(printItem);
                if (
                  printItem.content == null ||
                  printItem.content.printItems == null ||
                  printItem.content.printItems.length == 0
                ) {
                  Notify.error('错误', '打印模板无数据，不能打印。');
                  return;
                }
                var content = JSON.stringify(printItem.content);
                if (content == null || content == '' || content == '{}') {
                  Notify.error('错误', '请先选择模板，再点击下载。');
                  return;
                }
                contents.push(printItem.content);
              });
              PrintUtil.printPrintPages(contents, selectedPrinter);
            }
          }
        },
        errorData => {
          _self.loading=false;
          Common.processException(errorData);
        },
      );
    },

    /**
     * 冻结表头
     */
    fixedTableHeader: function () {
      let _self = this;

      _self.$nextTick(function () {
        $('.fixed-table').tableFixer({
          left: 3,
          head: true,
        });
      });
    },
  },
};
</script>

<style scoped>
.flex-container {
  display: flex;
  /* 垂直*/
  flex-direction: column;
  width: 100%;
  /*视口被均分为100单位的vh 占据整个窗口，扣掉顶部topNav的距离后，计算得到container的高度*/
  height: calc(100vh - 140px);
}

.flex-header {
  /*放大缩小比例为0 */
  flex: 0 0 35px;
}

.flex-footer {
  height: 45px;
  /*放大缩小比例为0 */
  flex: 0 0 45px;
}

.flex-content {
  flex: 1;
  overflow: scroll;
  width: 100%;
}

.fixed-table {
  table-layout: fixed;
  word-wrap: break-word;
  word-break: break-all;
}
</style>

<style scoped>
.fixed-table {
  table-layout: fixed;
  width: 800px !important;
  min-width: 800px !important;
}

table.fixed-table tr {
  height: 40px;
}

table.fixed-table th,
table.fixed-table td {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.image {
  width: 40px;
  height: 40px;
}

.modal-img-box {
  width: 100%;
  text-align: center;
  overflow: auto;
}

.m-img {
  width: 100%;
}
</style>
