<template>
  <div class="grid-container">
    <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 class="row">
        <div class="col-md-12">
          <div class="form-inline">
            <div class="form-group">
              <form id="uploadForm" enctype="multipart/form-data">
                <input id="file" ref="uploadFileInput" type="file" class="fileInput form-control" @change="handleFile" />
              </form>
            </div>
            <div class="form-group">
              <label>{{ uploadFilePath }}</label>
              <select v-model="selectedIndex" class="form-control">
                <option v-for="(sheetItem,index) in sheetItems" :key="index" :value="index">  
                  {{ sheetItem }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';
import { IFrameUtil } from 'pc-component-v3';

export default {

  components: { },
  data: function () {
    return {
      uuid : '',
      'uploadFilePath' : '',
      'selectedIndex' : -1,
      'sheetItems' : [],
      cacheData:{},
      infoWindowId: '',
      obj:{},
      formData:undefined,
    };
  },

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

  methods: {

    /**
			 * 导入数据至采购电子元器件详表
			 */
    generate : function(){
      var _self = this;
      let modelData = parent.getModelData();
      let generateDocumentModelData = {
        windowNo: modelData.windowNo,
        parentTabIndex: modelData.tabIndex,
        sheetIndex: _self.selectedIndex,
        modelData: modelData,
        inputDatas: [],
      };
      let url = null;
      if (_self.type == 'stockInLineImport') {
        // 填写excel后台地址
        // url = 'stockInResource/saveImportModelData';
      }else{
        Notify.error('提示', '不识别的Excel导入地址。' + _self.type, false);
        return;
      }
      // 返回modelData
      _self.responseReceiveData(generateDocumentModelData, url);
    },
    /**
			 * 根据导入的数据返回modelData
			 * @param {Object} obj
			 */
    responseReceiveData : function(obj, url){
      var _self = this;
      $.ajax({
        url: Common.getApiURL(url),
        type: 'post',
        dataType : 'json',
        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;
              });
            }
            parent.modelDataChanged(modelData);

            _self.back();
          }
        },	
        error: function (XMLHttpRequest, textStatus, errorThrown){
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
			 * [handleFile 选择文件]
			 * @return {[type]} [description]
			 */
    handleFile : function(){
      var _self = this;
      _self.uploadFilePath = event.currentTarget.value;
      if(_self.uploadFilePath.length == 0){
        Common.showDialog('提示:','必须选择一个文件', 'danger');
        return ;
      }
      if(!_self.uploadFilePath.toLowerCase().endsWith('.xls') && !_self.uploadFilePath.toLowerCase().endsWith('.xlsx')){
        Common.showDialog('警告:','必须是Excel 2003~2007 文件格式(xls)', 'error');
        return ;
      }
      _self.formData = new FormData();
      _self.formData.append('file', document.getElementById('uploadForm')[0].files[0]);
      $.ajax({
        url : Common.getApiURL('dataImportResource/uploadFile'),
        type : 'post',
        beforeSend : function(request){
          Common.addTokenToRequest(request);
        },
        data: _self.formData,   
        contentType: false,  
        processData: false,
        success : function(data){
          _self.showSheetItems(data);
          _self.$refs.uploadFileInput.value = '';
        },
        error: function (XMLHttpRequest, textStatus, errorThrown){
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    
    /**
			 * [showSheetItems 渲染Excel Sheet]
			 * @param  {[type]} data [description]
			 * @return {[type]}      [description]
			 */
    showSheetItems : function(data){
      var _self = this;
      // 清空数据
      _self.sheetItems.splice(0, _self.sheetItems.length);
      if(data == undefined || data.length == 0){
        return;
      }

      for(var i=0, len = data.length; i < len; i++){
        _self.sheetItems.push(data[i]);
        _self.selectedIndex = i-1;
      }
    },

    /**
         * 返回,关闭模态框
         */
    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%;
    }
</style>