<template>
  <Navbar :title="title" :is-go-back="false" />
  <a-layout class="grid-container">
    <!-- 主体内容 -->
    <a-layout-content class="grid-item-2">
      <a-space :size="16" direction="vertical" style="width: 100%">
        <!-- 操作按钮组 -->
        <a-space>
          <a-button type="primary" @click="generate">
            <template #icon><CheckOutlined /></template>
            确定
          </a-button>
          <a-button type="default" @click="back">
            <template #icon><RollbackOutlined /></template>
            撤销
          </a-button>
        </a-space>

        <!-- 文件上传区域 -->
        <a-row :gutter="16">
          <a-col :span="24">
            <a-space :size="24" align="baseline">
              <!-- 文件上传组件 -->
              <a-upload
                :show-upload-list="false"
                :before-upload="() => false"
                accept=".xls,.xlsx"
                @change="handleFile"
              >
                <a-button type="primary">
                  <UploadOutlined />
                  选择Excel文件
                  <input
                    ref="uploadFileInput"
                    type="file"
                    hidden
                    @change="handleFile"
                  />
                </a-button>
              </a-upload>

              <!-- 文件信息展示 -->
              <a-typography-text strong>{{ uploadFilePath }}</a-typography-text>

              <!-- 工作表选择 -->
              <a-select
                v-model:value="selectedIndex"
                style="width: 200px"
                placeholder="请选择工作表"
              >
                <a-select-option
                  v-for="(sheetItem, index) in sheetItems"
                  :key="index"
                  :value="index"
                >
                  {{ sheetItem }}
                </a-select-option>
              </a-select>
            </a-space>
          </a-col>
        </a-row>
      </a-space>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import {
  UploadOutlined,
  CheckOutlined,
  RollbackOutlined,
} from '@ant-design/icons-vue';
import Common from '../common/Common.js';
import { IFrameUtil } from 'pc-component-v3';

export default defineComponent({
  components: {
    UploadOutlined,
    CheckOutlined,
    RollbackOutlined,
  },
  data() {
    return {
      uuid: '',
      uploadFilePath: '',
      selectedIndex: undefined,
      sheetItems: [],
      cacheData: {},
      infoWindowId: '',
      obj: {},
      formData: undefined,
      type: '',
    };
  },
  mounted() {
    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(info) {
      const file = info.file.originFileObj || info.file;
      this.uploadFilePath = file.name;

      if (!file.name.toLowerCase().match(/\.xls[x]?$/)) {
        this.$message.error('必须选择Excel文件（.xls或.xlsx）');
        return;
      }

      this.formData = new FormData();
      this.formData.append('file', file);

      $.ajax({
        url: Common.getApiURL('dataImportResource/uploadFile'),
        type: 'post',
        beforeSend: request => Common.addTokenToRequest(request),
        data: this.formData,
        contentType: false,
        processData: false,
        success: data => {
          this.showSheetItems(data);
          this.$refs.uploadFileInput.value = '';
        },
        error: (XMLHttpRequest, textStatus, errorThrown) => {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    showSheetItems(data) {
      this.sheetItems = data?.length ? [...data] : [];
      this.selectedIndex = this.sheetItems.length > 0 ? 0 : undefined;
    },
    back() {
      IFrameUtil.close();
    },
  },
});
</script>

<style scoped>
.grid-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.ant-layout-header {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1;
  background-color: #fff;
}

.ant-layout-content {
  flex: 1;
  overflow: auto;
  background-color: #fff;
}
</style>