<template>
  <div class="contain-fluid">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="title">{{ title }}</h4>
      </div>
      <div class="panel-body">
        <div style="margin-bottom: 10px;">
          <div class="btn-group">
            <button
              class="btn btn-primary"
              @click="generate()"
            >
              确定
            </button>
            <button
              class="btn btn-warning"
              @click="back()"
            >
              撤销
            </button>
            <button
              class="btn btn-default"
              @click="refresh()"
            >
              刷新
            </button>
          </div>
        </div>
        <DocGenerate
          ref="docGenerate"
          :info-window-no="infoWindowNo"
          :generate-ids="generateIds"
          @show-title="showTitle($event)"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';
import { UserStorageResource } from 'pc-component-v3';
import { Notify, Uuid } from 'pc-component-v3';

export default {

  components: {  },
  data: function () {
    return {
      uuid: '',
      infoWindowNo: '',
      cacheData: {},
      type: '',
      url: '',
      obj: {},
      title: '',
      generateIds: [],
    };
  },

  created: function () {
    this.uuid = this.$route.params.uuid;
    this.infoWindowNo = this.$route.params.infoWindowNo;
    this.type = this.$route.params.type;
  },

  mounted: function () {
    this.getModalDataFromUserStorage();
  },

  methods: {

    showTitle: function (e) {
      this.title = e;
    },

    refresh: function () {
      this.$refs.docGenerate.loadInfoWindowDto();
    },

    generate: function () {
      var _self = this;

      var data = _self.$refs.docGenerate.getSelectedData();

      let key = _self.uuid + '_modelData';
      UserStorageResource.uniqueByKey(key).then(successData => {
        // if(successData.errorCode != 0) {
        //   Notify.error('提示', successData.errorMessage, false);
        //   return;
        // }
        if (successData.data != null && successData.data != '') {
          let cacheModelData = JSON.parse(successData.data);
          if (cacheModelData.id > 0) {
            Notify.error('错误', '已经保存过的单据不允许生单，请新建单据然后生单。', true);
            setTimeout(function () {
              history.back();
            }, 1000);
          } else {
            _self.cacheData = cacheModelData;
            // 父页签的数据
            data.infoWindowNo = cacheModelData.windowNo;

            var inputDatas = this.$refs.docGenerate.getSelectedItems();
            _self.obj = {
              windowNo: cacheModelData.windowNo,
              documentDto: data,
              modelData: cacheModelData,
              tabIndex: cacheModelData.tabIndex,
              inputDatas: inputDatas,
              saveDatas: cacheModelData.saveDatas,
            };

            // 生单数据模型
            _self.generateURL(data);
          }
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },
    generateURL: function (data) {
      if (data.recordIds == null || data.recordIds.length == 0) {
        Notify.error('提示', '未选择任何数据。', false);
        return;
      }
      var _self = this;
      if (_self.type == 'purchaseRequest') {
        _self.url = 'PurchaseOrderResource/generatePurchaseOrderModelData';
      } else if (_self.type == 'purchaseOrder') {
        _self.url = 'purchaseOrderArrivalResource/generatePurchaseOrderArrivalModelData';
      } else if (_self.type == 'purchaseOrderArrival') {
        _self.url = 'incomingInspectionRequestResource/generateInspectRequestModelData';
      } else if (_self.type == 'inspectionRequest') {
        if (data.recordIds != undefined && data.recordIds.length > 1) {
          Notify.error('数据选择错误', '只能选择一条报检单明细数据', false);
          return;
        } else {
          _self.url = 'incomingInspectionResource/generateInspectionModelData';
        }
      } else if (_self.type == 'inspectionReject') {
        if (data.recordIds != undefined && data.recordIds.length > 1) {
          Notify.error('数据选择错误', '只能选择一条检验单数据', false);
          return;
        } else {
          _self.url = 'incomingInspectionRejectResource/generateInspectionRejectModelData';
        }
      } else if (_self.type == 'inspectionStockIn') {
        _self.url = 'stockInResource/generateStockInModelDataByInspection';
      } else if (_self.type == 'purchaseOrderArrivalStockIn') {
        _self.url = 'stockInResource/generateStockInModelDataByArrival';
      } else if (_self.type == 'purchaseStockIn') {
        _self.url = 'StockOutResource/generateMaterialStockOutModelData';
      } else if (_self.type == 'AssetOrder') {
        _self.url = 'AssetOrderResource/generateAssetOrderModelData';
      } else if (_self.type == 'newAssetOrder') {
        //资产申购单生成资产采购单
        _self.url = 'AssetOrderResource/generateModelData';
      } else if (_self.type == 'purchaseOrderReturn') {
        _self.url = 'purchaseOrderReturnResource/generatePurchaseOrderReturnModelData';
      } else if (_self.type == 'materialStockOut') {
        _self.url = 'StockOutResource/generateRedStockOutModelData';
      } else if (_self.type == 'redPurchaseStockIn') {
        _self.url = 'stockInResource/generateRedStockInModelData';
      } else if (_self.type == 'stockInPrepareLine') {
        _self.url = 'stockInResource/generateRedStockInPrepareModelData';
      } else if (_self.type == 'generateStockInByOrder') {
        _self.url = 'stockInResource/generateStockInByOrder';
      } else if (_self.type == 'newPurchaseRequest') {
        //仓库模块-采购订单
        _self.url = 'PurchaseOrderResource/generateModelData';
      } else if (_self.type == 'newPurchaseOrder') {
        //仓库模块-采购到货单
        _self.url = 'purchaseOrderArrivalResource/generateModelData';
      } else if (_self.type == 'newArrivalStockIn') {
        //仓库模块-（到货单生成）入库单
        _self.url = 'stockInResource/generateArrivalStockInModelData';
      } else if (_self.type == 'newArrivalInspectionRequest') {
        //仓库模块-来料报检单
        _self.url = 'incomingInspectionRequestResource/generateModelData';
      } else if (_self.type == 'newInspectionRequest') {
        //仓库模块-来料检验单
        if (data.recordIds != undefined && data.recordIds.length > 1) {
          Notify.error('数据选择错误', '只能选择一条报检单数据', false);
          return;
        } else {
          _self.url = 'incomingInspectionResource/generateModelData';
        }
      } else if (_self.type == 'newInspectionReject') {
        //仓库模块-不良品处理单
        if (data.recordIds != undefined && data.recordIds.length > 1) {
          Notify.error('数据选择错误', '只能选择一条检验单数据', false);
          return;
        } else {
          _self.url = 'incomingInspectionRejectResource/generateModelData';
        }
      } else if (_self.type == 'newCurrentStock') {
        //仓库模块-（仓库库存生成）出库单
        _self.url = 'StockOutResource/generateModelData';
      } else if (_self.type == 'newRedStockOut') {
        //仓库模块-红字出库单
        _self.url = 'StockOutResource/generateRedModelData';
      } else if (_self.type == 'newPurchaseOrderReturn') {
        //仓库模块-采购退货单
        _self.url = 'purchaseOrderReturnResource/generateModelData';
      } else if (_self.type == 'newStockOut') {
        //仓库模块-红字出库单
        _self.url = 'StockOutResource/generateRedModelData';
      } else if (_self.type == 'newRedStockIn') {
        //仓库模块-红字入库单
        _self.url = 'stockInResource/generateRedModelData';
      } else if (_self.type == 'invStockIn') {
        //仓库模块-（物料批量）入库单
        _self.url = 'stockInResource/generateModelDataByInventory';
      } else if (_self.type == 'orderToIn') {
        //仓库模块-（订单生成）入库单
        _self.url = 'stockInResource/generateOrderToInModelData';
      } else if (_self.type == 'saleOrderToIn') {
        //仓库模块-销售订单生成入库单
        _self.url = 'stockInResource/generateSaleOrderToInModelData';
      } else if (_self.type == 'saleOrderToOut') {
        //仓库模块-销售订单生成出库单
        _self.url = 'StockOutResource/generateSaleOrderToOutModelData';
      } else if (_self.type == 'saleOrderToPrepare') {
        //仓库模块-销售订单生成领料单
        _self.url = 'stockOutPrepareResource/generateSaleOrderToPrepareModelData';
      } else if (_self.type == 'prepareToOut') {
        //仓库模块-领料单生成出库单
        _self.url = 'StockOutResource/generatePrepareToOutModelData';
      } else if (_self.type == 'saleOrderToStockUp') {
        //销售订单生成备货单
        _self.url = 'StockUpResource/generateSaleOrderToStockUpModelData';
      } else if (_self.type == 'applyToStockUp') {
        //布草管理-出库申请单生成仓库备货单
        _self.url = 'StockUpResource/generateApplyToUpModelData';
      } else if (_self.type == 'purchaseOrderToStockOut') {
        //布草管理-采购订单详单生成工厂出库单
        _self.url = 'StockOutResource/generateStockOutByPurchaseOrder';
      } else if (_self.type == 'newAssetCheck') {
        //资产采购单生成验收单
        _self.url = 'assetCheckResource/generateModelData';
      } else if (_self.type == 'newPurchaseBill') {
        //采购单生成采购丁单发票
        _self.url = 'purchaseOrderBillResource/generateModelData';
      } else if (_self.type == 'newPurchaseOrderPayment') {
        //采购订单生成付款单
        _self.url = 'purchaseOrderPaymentResource/generateModelData';
      } else if (_self.type == 'newSaleOrderReceivables') {
        //销售订单生成收款单
        _self.url = 'SaleOrderReceiptResource/generateModelData';
      } else if (_self.type == 'newSaleOrderBill') {
        //销售订单生成销售订单发票
        _self.url = 'saleOrderBillResource/generateModelData';
      } else if (_self.type == 'newSaleOrderReceipt') {
        //销售订单生成收款单
        _self.url = 'SaleOrderReceiptResource/generateModelData';
      } else if (_self.type == 'generatePurchaseRequest') {
        //申购单生成采购订单
        _self.url = 'PurchaseOrderResource/generateModelData';
      } else if (_self.type == 'generatePurchaseOrder') {
        //采购订单生成采购到货
        _self.url = 'PurchaseOrderArrivalResource/generateModelData';
      } else if (_self.type == 'generatePurchaseOrderReturn') {
        //退货单生成换货单
        _self.url = 'PurchaseOrderArrivalResource/generateModelDataReturn';
      } else if (_self.type == 'fiveOneOneInspectionOrder') {
        //511送检单生单
        _self.url = 'FiveOneOneInspectionOrderResource/generateModelData';
      } else if (_self.type == 'sevenOneOneInspectionOrder') {
        //711送检单生单
        _self.url = 'SevenOneOneInspectionOrderResource/generateModelData';
      } else if (_self.type == 'twoZeroOneInspectionOrder') {
        //201送检单生单
        _self.url = 'TwoZeroOneInspectionOrderResource/generateModelData';
      } else if (_self.type == 'eightZeroEightInspectionOrder') {
        //808送检单生单
        _self.url = 'EightZeroEightInspectionOrderResource/generateModelData';
      } else if (_self.type == 'spaceCenterInspectionOrder') {
        //空间中心送检单
        _self.url = 'SpaceCenterInspectionOrderResource/generateModelData';
      } else if (_self.type == 'sethInspectionOrder') {
        //赛思送检单
        _self.url = 'SethInspectionOrderResource/generateModelData';
      } else if (_self.type == 'purchaseOrderRetest') {
        //到货生成采购复验单
        _self.url = 'PurchaseOrderRetestResource/generateModelData';
      } else if (_self.type == 'generatePurchaseOrderRetest') {
        //采购复验单生成退货单
        _self.url = 'PurchaseOrderReturnResource/generateModelData';
      } else if (_self.type == 'generateEntryInspectionLine') {
        //入所检验生成退货单
        _self.url = 'PurchaseOrderReturnResource/generateModelData1';
      } else if (_self.type == 'generateStockInLine') {
        //入库单生成质量处补充信息
        _self.url = 'QualityDepartmentSupplementResource/generateModelData';
      } else if (_self.type == 'newReceiveOrder') {
        //到货生成民品领用单
        _self.url = 'ReceiveOrderResource/generateModelData';
      } else if (_self.type == 'generatePurchaseRequestLine') {
        //申购单生成申购变更单
        _self.url = 'PurchaseRequestChangeResource/generateModelData';
      } else if (_self.type == 'generatePurchaseOrderLine') {
        //采购订单生成采购变更单
        _self.url = 'PurchaseOrderChangeResource/generateModelData';
      } else if (_self.type == 'generateStockOutPrepareLine') {
        //库存生成借用明细单
        _self.url = 'stockOutPrepareResource/generateModelData';
      } else if (_self.type == 'generateStockInLineByReportNumberRecord') {
        //入库单生成添加报告号
        _self.url = 'ReportNumberRecordResource/generateModelData';
      } else if (_self.type == 'generateStockIn') {
        //入所检验生成入库单
        _self.url = 'stockInResource/generateModelData';
      } else if (_self.type == 'generateStockIn1') {
        //采购复验生成入库单
        _self.url = 'stockInResource/generateModelData1';
      } else if (_self.type == 'generatePurchaseOrderArrival1') {
        //借用详单生成归还单
        _self.url = 'PurchaseOrderArrivalResource/generateModelData1';
      } else if (_self.type == 'generateCompanyChangeOrder') {
        //申购单生成筛选单位更改单
        _self.url = 'CompanyChangeOrderResource/generateModelData';
      } else if (_self.type == 'generateInspectionOrder') {
        //到货单生成送检单
        _self.url = 'InspectionOrderResource/generateModelData';
      } else if (_self.type == 'generateEntryInspection') {
        //送检单生成入所检验单
        _self.url = 'EntryInspectionResource/generateModelData';
      } else if (_self.type == 'generateQualityDepartmentInspection') {
        //到货单生成所质量处送检
        _self.url = 'QualityDepartmentInspectionResource/generateModelData';
      } else if (_self.type == 'generatePurchaseInquiry') {
        //申购生成国产订货单
        _self.url = 'PurchaseInquiryResource/generateModelData';
      } else if (_self.type == 'generateStockIn2') {
        //申购生成国产订货单
        _self.url = 'EntryInspectionResource/generateModelData1';
      }

      _self.responseReceiveData(_self.obj);
    },

    responseReceiveData: function (obj) {
      var _self = this;
      if (_self.url != undefined && _self.url != '') {
        $.ajax({
          url: Common.getApiURL(_self.url),
          type: 'post',
          contentType: 'application/json',
          data: JSON.stringify(obj),
          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;
                });
              }

              console.log(modelData);

              _self.cacheData = modelData;
              // 存放modalData到后台数据库
              _self.setModalDataToUserStorage(obj);



            }
          },
          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();
              _self.url = 'PurchaseOrderResource/generatePurchaseOrderModelData';
              _self.responseReceiveData(_self.obj);
            },
          }, {
            label: '取消',
            action: function (dialogItself) {
              dialogItself.close();
            },
          },
        ],
      });
    },
    /**
         * 返回
         */
    back: function () {
      // history.back();
      // 当你在iframe页面关闭自身时
      var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
      parent.layer.close(index); //再执行关闭
    },

    /**
         * 从UserStorage中获取modalData
         * @author LeiGuoXian
         * @date 2020-09-16
         */
    getModalDataFromUserStorage: function () {
      var _self = this;
      let key = _self.uuid + '_modelData';
      UserStorageResource.uniqueByKey(key).then(successData => {
        // if(successData.errorCode != 0) {
        //   Notify.error('提示', successData.errorMessage, false);
        //   return;
        // }
        if (successData.data != null && successData.data != '') {
          let cacheModelData = JSON.parse(successData.data);
          if (cacheModelData.id > 0) {
            Notify.error('错误', '已经保存过的单据不允许生单，请新建单据然后生单。', true);
            setTimeout(function () {
              history.back();
            }, 1000);
          } else {
            let cacheModelData = JSON.parse(successData.data);
            var savaDatas = cacheModelData.saveDatas;
            _self.generateIds = [];
            if (savaDatas != null) {
              savaDatas.forEach(function (item, index) {
                _self.generateIds.push(item.data['generateId'].id);
              });
            }
          }
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },


    /**
         * 存放modalData在UserStorage中
         * @author LeiGuoXian
         * @date 2020-09-16
         */
    setModalDataToUserStorage: function (obj) {
      var _self = this;
      let key = _self.uuid + '_modelData';
      let userStorageDtos = [
        {
          key: key,
          value: JSON.stringify(_self.cacheData),
        },
      ];
      // 组装查询条件，然后放到后台数据库当中
      UserStorageResource.uploadUserStorage(userStorageDtos).then(successData => {
        _self.$router.push('/desktop/window1/window-edit/restore/' + obj.windowNo + '/0' + '?currPage=' + 1 + '&currIndex=' + 1 + '&totalCount=' + 1 + '&uuid=' + _self.uuid);
      }, errorData => {
        Common.processException(errorData);
      });
    },
  },
};


</script>

<style scoped>
.title {
    margin-top: 5px;
    margin-bottom: 0px;
}
</style>