<template>
  <div class="container-box">
    <div class="grid-item-1">
      <Navbar :title="title" :is-go-back="false" />
    </div>
    <div class="grid-item-2" style="margin-bottom: 5px">
      <div class="btn-group">
        <button class="btn btn-primary" @click="generate()">确定</button>
        <button class="btn btn-warning" @click="back()">撤销</button>
      </div>
    </div>
    <div class="grid-item-3">
      <DocGenerator
        ref="docGenerator"
        :info-window-no="infoWindowNo"
        :generate-ids="generateIds"
        :add-sql="addSql"
        @show-title="title = $event"
      />
    </div>
  </div>
</template>
  
<script>
import Common from '../../packages/common/Common.js';
import DocGenerator from '../../packages/info/src/DocGenerator.vue';
import Notify from '../../packages/common/Notify';
import IFrameUtil from '../../packages/common/IFrameUtil.js';
import Navbar from '../../packages/navbar/src/Navbar.vue';
export default {
  components: { DocGenerator, Navbar },
  data: function () {
    return {
      uuid: '',
      infoWindowNo: '',
      type: '',
      title: '',
      generateIds: [],
      addSql: undefined,
      modelData: undefined,
      userId: null,
    };
  },

  mounted: function () {
    // 测试请手动设置路由
    this.uuid = this.$route.params.uuid;
    this.infoWindowNo = this.$route.params.infoWindowNo;
    this.type = this.$route.params.type;
    // 测试请手动设置localStorage
    const item = `${this.uuid}#GenerateDocumentTool`;
    this.modelData = JSON.parse(localStorage.getItem(item));
    // 正式使用
    // this.modelData = window.opener.getModelData();
    const loginInfo = localStorage.getItem('#LoginInfo');
    if (loginInfo) {
      this.userId = JSON.parse(loginInfo).userId;
    } else {
      this.userId = -1;
    }
    if (this.type == 'currentStock') {
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = 'c.id = ' + this.modelData.data.warehouse.id;
      } else {
        this.addSql = 'c.id = -1 ';
      }
    } else if (this.type == 'currentStockWork') {
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = 'c.id = ' + this.modelData.data.warehouse.id;
      } else {
        this.addSql = 'c.id = -1 ';
      }
    } else if (this.type == 'currentStockProject') {
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = 'c.id = ' + this.modelData.data.warehouse.id;
      } else {
        this.addSql = 'c.id = -1 ';
      }
    } else if (this.type == 'inventoryOut') {
      //必选先选择仓库
      if (this.modelData.data.warehouse.id != null) {
        //分配状态为责任人变更
        if (
          this.modelData.data.inventoryOutType != null &&
          this.modelData.data.inventoryOutType.displayValue[0] != null &&
          this.modelData.data.inventoryOutType.displayValue[0] ==
            'Change_Of_Responsible_Person'
        ) {
          this.addSql =
            `c.id = ${this.modelData.data.warehouse.id} AND (csk.inventoryItemStatus = 'Assigned') ` +
            ` AND (csk.responsibilityUserId = ${this.userId}) `;
        }
        //分配状态为退回/归还
        else if (
          this.modelData.data.inventoryOutType != null &&
          this.modelData.data.inventoryOutType.displayValue[0] == 'Send_Back'
        ) {
          this.addSql =
            `c.id = ${this.modelData.data.warehouse.id} AND (csk.inventoryItemStatus = 'Assigned') ` +
            ` AND (u.id = ${this.userId}) `;
        }
        //分配状态为领用/借用
        else if (
          this.modelData.data.inventoryOutType != null &&
          this.modelData.data.inventoryOutType.displayValue[0] ==
            'Requisition_Borrowing'
        ) {
          this.addSql = `c.id = ${this.modelData.data.warehouse.id} AND (csk.inventoryItemStatus = 'Assignable' OR csk.inventoryItemStatus = 'Returning_Distributable_Funds') `;
        }
        //管理员分配
        else if (this.modelData.data.inventoryOutType == null) {
          this.addSql = `c.id = ${this.modelData.data.warehouse.id} AND (csk.inventoryItemStatus = 'Assignable' OR csk.inventoryItemStatus = 'Returning_Distributable_Funds') `;
        } else {
          this.addSql = 'c.id = -1 ';
        }
      } else {
        this.addSql = 'c.id = -1 ';
      }
    } else if (this.type == 'stockOutProject') {
      //当选择出库类型是正常报废出库的时候，从报废申请明细中生成出库明细
      //下面的查询窗口代码是根据报废申请明细查询库存数据
      if (
        this.modelData.data.stockOutProjectType.displayValue[0] ==
        'Normal_Scrapping'
      ) {
        this.infoWindowNo = '20240201_161916';
      } else if (
        this.modelData.data.stockOutProjectType.displayValue[0] ==
        'Systematic_Differences'
      ) {
        this.infoWindowNo = '20240415_201354';
      }
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = 'c.id = ' + this.modelData.data.warehouse.id;
      } else {
        this.addSql = 'c.id = -1 ';
      }
    } else if (this.type == 'scrapApply') {
      if (this.modelData.data.warehouse.id != null) {
        //报废申请查询的物料库存数据只能查询责任人是当前登录人的
        this.addSql = `c.id = ${this.modelData.data.warehouse.id} AND u.id = ${this.userId}`;
      } else {
        this.addSql = 'c.id = -1 ';
      }
    } else if (this.type == 'syncStockOutPrepareProject') {
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = `cwh.id = ${this.modelData.data.warehouse.id}`;
      } else {
        this.addSql = 'cwh.id = -1 ';
      }
    } else if (this.type == 'IdleManagement') {
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = 'w.id = ' + this.modelData.data.warehouse.id;
      } else {
        this.addSql = 'w.id = -1 ';
      }
    } else if (this.type == 'IdleManagementWork') {
      if (this.modelData.data.warehouse.id != null) {
        this.addSql = 'w.id = ' + this.modelData.data.warehouse.id;
      } else {
        this.addSql = 'w.id = -1 ';
      }
    }
  },

  methods: {
    generate: function () {
      var _self = this;

      var selectedDatas = _self.$refs.docGenerator.getSelectedData();
      if (
        selectedDatas === undefined ||
        selectedDatas === null ||
        selectedDatas.length === 0
      ) {
        Notify.error('提示', '未选择任何数据。', false);
        return;
      }
      let modelData = IFrameUtil.getCurdModelData();
      let url = null;

      if (_self.type == 'purchaseRequest') {
        url = 'PurchaseOrderResource/generatePurchaseOrderModelData';
      } else if (_self.type == 'purchaseOrder') {
        url =
          'purchaseOrderArrivalResource/generatePurchaseOrderArrivalModelData';
      } else if (_self.type == 'purchaseOrderArrival') {
        url =
          'incomingInspectionRequestResource/generateInspectRequestModelData';
      } else if (_self.type == 'inspectionRequest') {
        if (selectedDatas.length > 1) {
          Notify.error('数据选择错误', '只能选择一条报检单明细数据', false);
          return;
        } else {
          url = 'incomingInspectionResource/generateInspectionModelData';
        }
      } else if (_self.type == 'inspectionReject') {
        if (selectedDatas.length > 1) {
          Notify.error('数据选择错误', '只能选择一条检验单数据', false);
          return;
        } else {
          url =
            'incomingInspectionRejectResource/generateInspectionRejectModelData';
        }
      } else if (_self.type == 'inspectionStockIn') {
        url = 'stockInResource/generateStockInModelDataByInspection';
      } else if (_self.type == 'purchaseOrderArrivalStockIn') {
        url = 'stockInResource/generateStockInModelDataByArrival';
      } else if (_self.type == 'purchaseStockIn') {
        url = 'StockOutResource/generateMaterialStockOutModelData';
      } else if (_self.type == 'purchaseOrderReturn') {
        url =
          'purchaseOrderReturnResource/generatePurchaseOrderReturnModelData';
      } else if (_self.type == 'materialStockOut') {
        url = 'StockOutResource/generateRedStockOutModelData';
      } else if (_self.type == 'redPurchaseStockIn') {
        url = 'stockInResource/generateRedStockInModelData';
      } else if (_self.type == 'stockInPrepareLine') {
        url = 'stockInResource/generateRedStockInPrepareModelData';
      } else if (_self.type == 'generateStockInByOrder') {
        url = 'stockInResource/generateStockInByOrder';
      } else if (_self.type == 'newPurchaseRequest') {
        //仓库模块-采购订单
        url = 'PurchaseOrderResource/generateModelData';
      } else if (_self.type == 'newPurchaseOrder') {
        //仓库模块-采购到货单
        url = 'purchaseOrderArrivalResource/generateModelData';
      } else if (_self.type == 'newArrivalStockIn') {
        //仓库模块-（到货单生成）入库单
        url = 'stockInResource/generateArrivalStockInModelData';
      } else if (_self.type == 'newArrivalInspectionRequest') {
        //仓库模块-来料报检单
        url = 'incomingInspectionRequestResource/generateModelData';
      } else if (_self.type == 'newInspectionRequest') {
        //仓库模块-来料检验单
        if (selectedDatas.length > 1) {
          Notify.error('数据选择错误', '只能选择一条报检单数据', false);
          return;
        } else {
          url = 'incomingInspectionResource/generateModelData';
        }
      } else if (_self.type == 'newInspectionReject') {
        //仓库模块-不良品处理单
        if (selectedDatas.length > 1) {
          Notify.error('数据选择错误', '只能选择一条检验单数据', false);
          return;
        } else {
          url = 'incomingInspectionRejectResource/generateModelData';
        }
      } else if (_self.type == 'newCurrentStock') {
        //仓库模块-（仓库库存生成）出库单
        url = 'StockOutResource/generateModelData';
      } else if (_self.type == 'newRedStockOut') {
        //仓库模块-红字出库单
        url = 'StockOutResource/generateRedModelData';
      } else if (_self.type == 'newPurchaseOrderReturn') {
        //仓库模块-采购退货单
        url = 'purchaseOrderReturnResource/generateModelData';
      } else if (_self.type == 'newStockOut') {
        //仓库模块-红字出库单
        url = 'StockOutResource/generateRedModelData';
      } else if (_self.type == 'newRedStockIn') {
        //仓库模块-红字入库单
        url = 'stockInResource/generateRedModelData';
      } else if (_self.type == 'invStockIn') {
        //仓库模块-（物料批量）入库单
        url = 'stockInResource/generateModelDataByInventory';
      } else if (_self.type == 'orderToIn') {
        //仓库模块-（订单生成）入库单
        url = 'stockInResource/generateOrderToInModelData';
      } else if (_self.type == 'saleOrderToIn') {
        //仓库模块-销售订单生成入库单
        url = 'stockInResource/generateSaleOrderToInModelData';
      } else if (_self.type == 'saleOrderToOut') {
        //仓库模块-销售订单生成出库单
        url = 'StockOutResource/generateSaleOrderToOutModelData';
      } else if (_self.type == 'saleOrderToPrepare') {
        //仓库模块-销售订单生成领料单
        url = 'stockOutPrepareResource/generateSaleOrderToPrepareModelData';
      } else if (_self.type == 'prepareToOut') {
        //仓库模块-领料单生成出库单
        url = 'StockOutResource/generatePrepareToOutModelData';
      } else if (_self.type == 'saleOrderToStockUp') {
        //销售订单生成备货单
        url = 'StockUpResource/generateSaleOrderToStockUpModelData';
      } else if (_self.type == 'applyToStockUp') {
        //布草管理-出库申请单生成仓库备货单
        url = 'StockUpResource/generateApplyToUpModelData';
      } else if (_self.type == 'purchaseOrderToStockOut') {
        //布草管理-采购订单详单生成工厂出库单
        url = 'StockOutResource/generateStockOutByPurchaseOrder';
      } else if (_self.type == 'newAssetCheck') {
        //资产采购单生成验收单
        url = 'assetCheckResource/generateModelData';
      } else if (_self.type == 'newPurchaseBill') {
        //采购单生成采购丁单发票
        url = 'purchaseOrderBillResource/generateModelData';
      } else if (_self.type == 'newPurchaseOrderPayment') {
        //采购订单生成付款单
        url = 'purchaseOrderPaymentResource/generateModelData';
      } else if (_self.type == 'newSaleOrderReceivables') {
        //销售订单生成收款单
        url = 'SaleOrderReceiptResource/generateModelData';
      } else if (_self.type == 'newSaleOrderBill') {
        //销售订单生成销售订单发票
        url = 'saleOrderBillResource/generateModelData';
      } else if (_self.type == 'newSaleOrderReceipt') {
        //销售订单生成收款单
        url = 'SaleOrderReceiptResource/generateModelData';
      } else if (_self.type == 'generatePurchaseRequest') {
        //申购单生成采购订单
        url = 'PurchaseOrderResource/generateModelData';
      } else if (_self.type == 'generatePurchaseOrder') {
        //采购订单生成采购到货
        url = 'PurchaseOrderArrivalResource/generateModelData';
      } else if (_self.type == 'syncStockOutPrepare') {
        //领料申请生成入库单
        url = 'stockInResource/generateModelDataBySyncStockOutPrepare';
      } else if (_self.type == 'syncStockOutPrepareWork') {
        //领料申请生成入库单-办公劳保
        url = 'StockInWorkResource/generateModelDataBySyncStockOutPrepareWork';
      } else if (_self.type == 'syncStockOutPrepareProject') {
        //调拨申请生成入库单-工程设备仓
        url =
          'StockInProjectResource/generateModelDataBySyncStockOutPrepareProject';
      } else if (_self.type == 'currentStock') {
        //库存查询生成领料叫料
        url = 'StockOutResource/generateModelDataByCurrentStock';
      } else if (_self.type == 'currentStockWork') {
        //库存查询生成领料叫料-办公劳保
        url = 'StockOutWorkResource/generateModelDataByCurrentStockWork';
      } else if (_self.type == 'inventoryOut') {
        //库存查询生成物料分配明细-工程设备仓
        url = 'InventoryOutResource/generateModelDataByCurrentStockProject';
      } else if (_self.type == 'scrapApply') {
        //库存查询生成物料报废明细-工程设备仓
        url = 'ScrapApplyResource/generateModelDataByCurrentStockProject';
      } else if (_self.type == 'stockOutProject') {
        //库存查询生成物料出库明细-工程设备仓
        url = 'StockOutProjectResource/generateModelDataByCurrentStockProject';
      } else if (_self.type == 'stockReturn') {
        //领料生成退库
        url = 'StockOutResource/generateModelDataByStockReturn';
      } else if (_self.type == 'stockWorkReturn') {
        //领料生成退库-办公劳保
        url = 'StockOutWorkResource/generateModelDataByStockReturn';
      } else if (_self.type == 'IdleManagement') {
        //库存查询生成闲置
        url = 'IdleManagementResource/generateModelDataByCurrentStock';
      } else if (_self.type == 'IdleManagementWork') {
        //库存查询生成闲置-办公劳保
        url = 'IdleManagementWorkResource/generateModelDataByCurrentStock';
      } else {
        Notify.error('提示', '不识别的生单地址。' + _self.type, false);
        return;
      }
      let generateDocumentModelData = {
        windowNo: modelData.windowNo,
        tabIndex: modelData.tabIndex,
        modelData: modelData,
        inputDatas: selectedDatas,
      };

      $.ajax({
        url: Common.getApiURL(url),
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(generateDocumentModelData),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (modelData) {
          if (modelData != undefined) {
            if (modelData.saveDatas != undefined) {
              modelData.saveDatas.forEach(function (item) {
                if (item.editMode == null) {
                  item.editMode = true;
                }
                item.tabIndex = 1;
              });
            }
            // IFrameUtil.setCurdModelData(modelData);
            window.opener.modelDataChanged(modelData);
            _self.back();
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    isShowVendorDialogA: function (data) {
      var _self = this;
      var messageStr = '';
      data.forEach(function (item, index) {
        if (index == data.length - 1) {
          messageStr += item.name;
        } else {
          messageStr += item.name + '，';
        }
      });
      Notify.show({
        title: '项目确认',
        message: '您选择的请购订单明细中存在不同项目【' + messageStr + '】',
        buttons: [
          {
            label: '取消',
            action: function (dialogItself) {
              dialogItself.close();
            },
          },
        ],
      });
    },

    isShowVendorDialog: function (data) {
      var _self = this;
      var messageStr = '';
      data.forEach(function (item, index) {
        if (index == data.length - 1) {
          messageStr += item.vendorName;
        } else {
          messageStr += item.vendorName + '，';
        }
      });
      Notify.show({
        title: '供应商确认',
        message:
          '您选择的请购订单明细中存在不同供应商【' +
          messageStr +
          '】，如果点击\\"确定\\"按钮，将从供应商【' +
          data[data.length - 1].vendorName +
          '】下订单，否则点击\\"取消\\"按钮',
        buttons: [
          {
            label: '确定',
            cssClass: 'btn-primary',
            action: function (dialogItself) {
              dialogItself.close();
              var url = 'PurchaseOrderResource/generatePurchaseOrderModelData';
              _self.responseReceiveData(_self.obj);
            },
          },
          {
            label: '取消',
            action: function (dialogItself) {
              dialogItself.close();
            },
          },
        ],
      });
    },
    /**
     * 返回,关闭模态框
     */
    back: function () {
      IFrameUtil.close();
    },
  },
};
</script>
  
  <style scoped>
.grid-container {
  display: grid;
  grid-template-columns: 100%;
  grid-template-rows: min-content min-content auto;
  height: calc(100vh - 35px);
  width: 100%;
  padding: 10px;
}

.grid-item-1 {
  grid-row: 1 / 2;
  grid-column: 1 / 2;
}

.grid-item-2 {
  grid-row: 2 / 3;
  grid-column: 1 / 2;
}

.grid-item-3 {
  overflow: auto;
  grid-row: 3/4;
  grid-column: 1 / 2;
  height: 100%;
}
.container-box {
  padding: 20px;
  height: calc(100vh - 20px);
}
</style>
  