<template>
  <div class="container-fluid">
    <!-- <NavBar :title="$t('lang.DataImportPanel.DataImport')" :is-go-back="true" /> -->
    <div>
      <a-steps :current="current">
        <a-step
          v-for="item in steps"
          :key="item.title"
          :title="item.title"
          :description="item.description"
        />
      </a-steps>
      <div class="steps-content">
        <div v-if="current === 0" class="row">
          <div class="col-md-12">
            <div class="form-inline">
              <div class="form-group">
                <label>1.请选择导入模板</label><br /> 
                <select
                  v-model="selectedDataTemplateNo"
                  class="form-control"
                  @change="changeSelected()"
                >
                  <option />
                  <option
                    v-for="dataTemplate in dataTemplates"
                    :key="dataTemplate.dataTemplateNo"
                    :value="dataTemplate.dataTemplateNo"
                  >
                    {{ dataTemplate.dataTemplateName }}
                  </option>
                </select>
              </div>
              <div>
                <div>
                  <label class="downloadTemplateLabel">2.请下载导入模板</label><br />
                  <button
                    type="button"
                    class="btn btn-primary"
                    @click="downloadTemplateButton"
                  >
                    <a style="color: #fff" href="javascript:">{{
                      $t("lang.DataImportPanel.downloadTemplate")
                    }}</a>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="current === 1" class="row">
          <div class="col-md-12">
            <div class="form-inline">
              <div class="form-group">
                <label>1.请选择Excel数据</label><br />
                <input
                  id="file"
                  ref="uploadFileInput"
                  autocomplete="off"
                  type="file"
                  class="fileInput form-control"
                  @change="handleFile"
                />
                <span>{{ uploadFilePath }}</span>
              </div>
              <div>
                <label>2.请选择需要导入的sheet</label><br />
                <select v-model="selectedIndex" class="form-control sheet-select">
                  <option
                    v-for="(sheetItem, index) in sheetItems"
                    :key="index"
                    :value="index"
                  >
                    {{ sheetItem }}
                  </option>
                </select>
              </div>
            </div>
          </div>
        </div>
        <div v-if="current === 2" class="row">
          <div class="col-md-12">
            <div class="form-inline">
              <!-- <label>{{ $t("lang.DataImportPanel.stepThree") }}.</label> -->
              <div v-if="sheetItems.length > 0" class="form-group">
                <button
                  type="button"
                  class="btn btn-primary"
                  @click="runProcessClear(selectedDataTemplateNo)"
                >
                  3.1{{ $t("lang.DataImportPanel.emptyImport") }}
                </button>
                <button
                  type="button"
                  class="btn btn-primary"
                  @click="testImportButton(true)"
                >
                  3.2{{ $t("lang.DataImportPanel.testImport") }}
                </button>
                <button
                  type="button"
                  class="btn btn-primary"
                  @click="runProcessImport(selectedDataTemplateNo)"
                >
                  3.3{{ $t("lang.DataImportPanel.formalImport") }}
                </button>
                <button
                  v-if="taskId != null && taskId.length > 0"
                  type="button"
                  class="btn btn-primary"
                  @click="finishTask"
                >
                  <a style="color: #fff" href="javascript:">{{
                    $t("lang.DataImportPanel.completeTask")
                  }}</a>
                </button>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-12">
              <div
                v-if="selectedDataTemplate != null"
                style="white-space: pre-wrap"
              >
                {{ selectedDataTemplate.description }}
              </div>
            </div>
          </div>

          <a-table
            bordered
            :columns="columns"
            :data-source="dataSource"
            :scroll="{ y:900 }"
            size="small"
          >
            <a-table-column type="index" />
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'ImportResult'">
                {{ record.ImportResult }}
              </template>
            </template>
          </a-table>
 
          <Loading v-if="loading" />
        </div>
      </div>
      <div class="steps-action">
        <a-button v-if="current>0" class="prevBtn" @click="prev"> 上一步 </a-button>
        <a-button
          v-if="current < steps.length - 1"
          class="nextBtn"
          type="primary"
          @click="next"
        >
          下一步
        </a-button>
      </div>
    </div>
  </div>
</template>

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

import DownloadService from '../resource/file/DownloadService.js';
import WorkflowResource from '../api/workflow/WorkflowResource.js';
import { Notify, Uuid } from 'pc-component-v3';
import { notificationError } from '../common/notification.js';

import {
  UserOutlined,
  SolutionOutlined,
  LoadingOutlined,
  SmileOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
export default {
  components: {
    UserOutlined,
    SolutionOutlined,
    LoadingOutlined,
    SmileOutlined,
  },
    
  data: function () {
    return {
      current: 0,
      steps: [
        {
          title: '步骤一',
          description: '选择模板',
        },
        {
          title: '步骤二',
          description: '上传文件',
        },
        {
          title: '步骤三',
          description: '导入成功',
        },
      ],
      dataTemplates: [],
      selectedDataTemplateNo: '',
      selectedDataTemplate: '', // 选择的导入模板
      uploadFilePath: '',
      sheetItems: [],
      importFields: [],
      importTable: {},
      selectedIndex: -1,
      dataTemplateNos: [],
      loading: false,
      selectedFile: null,
      dataTemplateNo: null,
      taskId: null,

      columns: [],    // 列定义
      dataSource: [], // 表格数据源
    };
  },

  computed: {},

  mounted: function () {
    var _self = this;
    console.log('uploadFileInput::::',_self);
    _self.initView();

    _self.$nextTick(function () {
      _self.canVisit();
      
    });
    if (_self.$route.query.dataTemplateNos) {
      _self.dataTemplateNos = JSON.parse(_self.$route.query.dataTemplateNos);
    };

  },

  methods: {
    /**
     * 步骤条切换
     */
    next() {
      console.log('selectedDataTemplateNo:::',this.selectedDataTemplateNo);
      if (!this.selectedDataTemplateNo) {
        message.error('请选择导入模板');
      } else{
        this.current++;
      }
    },
    prev() {
      this.current--;
    },

    /**
     * [canVisit 获取当前权限下可访问的导入数据模板]
     * @return {[type]} [description]
     */
    canVisit: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('roleDataTemplateResource/canVisitNew2'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.showDataTemplates(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * [showDataTemplates 渲染选择模板下拉框]
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    showDataTemplates: function (data) {
      var _self = this;
      // 清空数据
      _self.dataTemplates.splice(0, _self.dataTemplates.length);
      if (data == undefined || data.length == 0) {
        return;
      }

      for (var i = 0, len = data.length; i < len; i++) {
        if (_self.dataTemplateNos != null && _self.dataTemplateNos.length > 0) {
          if (
            _self.arrayContain(_self.dataTemplateNos, data[i].dataTemplateNo)
          ) {
            _self.dataTemplates.push(data[i]);
          }
        } else {
          if (_self.dataTemplateNo != null) {
            if (_self.dataTemplateNo == data[i].dataTemplateNo) {
              _self.dataTemplates.push(data[i]); //0 0 12 1 1 ?
            }
          } else {
            _self.dataTemplates.push(data[i]);
          }
        }
      }

      _self.$nextTick(function () {
        if (_self.dataTemplates != null && _self.dataTemplates.length > 0) {
          _self.selectedDataTemplateNo = _self.dataTemplates[0].dataTemplateNo;
          _self.selectedDataTemplate = _self.dataTemplates[0];
          _self.changeSelected();
        }
      });
    },

    arrayContain: function (array, obj) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] == obj)
          //如果要求数据类型也一致，这里可使用恒等号===
          return true;
      }
      return false;
    },

    /**
     * [changeSelected 下拉框改变事件]
     * @return {[type]} [description]
     */
    changeSelected: function () {
      var _self = this;
      _self.columns = [];
      _self.dataSource = [];
      if (_self.dataTemplates != null && _self.dataTemplates.length > 0) {
        _self.dataTemplates.forEach(item => {
          if (item.dataTemplateNo == _self.selectedDataTemplateNo) {
            _self.selectedDataTemplate = item;
          }
        });
      }
      _self.getImportTable(_self.selectedDataTemplateNo);
    },

    /**
     * [downloadTemplate 下载模板按钮点击事件]
     * @return {[type]} [description]
     */
    downloadTemplateButton: function () {
      var _self = this;
      //var url = window.location.origin;
      if(this.selectedDataTemplateNo){

 
        for (var i = 0, len = _self.dataTemplates.length; i < len; i++) {
          if (
            _self.selectedDataTemplateNo == _self.dataTemplates[i].dataTemplateNo
          ) {
            var realtivePath = _self.dataTemplates[
              i
            ].dataTemplateFileRelativePath.replace('\\', '/');
            var downloadUrl = Common.getFileServerUrl() + realtivePath;
            var fileName =
            realtivePath != null && realtivePath.lastIndexOf('/') >= 0
              ? realtivePath.substring(realtivePath.lastIndexOf('/') + 1)
              : '导入模板.xls';
            DownloadService.downloadFile(downloadUrl, fileName);
            this.current++;
          }
        }
      }else{
        message.error('请先选择导入模板');
      }
    },

    /**
     * [handleFile 选择文件]
     * @return {[type]} [description]
     */
    handleFile: function (event) {
      var _self = this;
      _self.uploadFilePath = event.currentTarget.value;
      if (_self.uploadFilePath.length == 0) {
        Notify.error(
          _self.$t('lang.Notify.prompt'),
          _self.$t('lang.DataImportPanel.describe1'),
          false,
        );
        return;
      }
      if (
        !_self.uploadFilePath.toLowerCase().endsWith('.xls') &&
        !_self.uploadFilePath.toLowerCase().endsWith('.xlsx')
      ) {
        Notify.error(
          _self.$t('lang.Notify.warning'),
          _self.$t('lang.DataImportPanel.describe2'),
          false,
        );
        return;
      }
      var formData = new FormData();
      let fileList = event.target.files;
      if (fileList.length > 0) {
        let file = fileList[0];
        _self.selectedFile = fileList[0];
        formData.append('file', file);
      }
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('dataImportResource/uploadFile'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: formData,
        contentType: false,
        processData: false,
        success: function (data) {
          _self.loading = false;
          _self.showSheetItems(data);
          _self.$refs.uploadFileInput.value = '';
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          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;
      }
    },

    /**
     * [getImportTable 获取表头]
     * @param  {[type]} dataTemplateNo [description]
     * @return {[type]}                [description]
     */
    getImportTable: function (dataTemplateNo) {
      if (dataTemplateNo == '' || dataTemplateNo == undefined) {
        return;
      }
      var _self = this;
      $.ajax({
        url: Common.getApiURL('dataImportResource/getImportTable'),
        type: 'get',
        dataType: 'json',
        data: {
          dataTemplateNo: dataTemplateNo,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.importTable = data;
          _self.showImportTable(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * [showImportTable 渲染表头]
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    showImportTable: function (data) {
      var _self = this;
      _self.importFields.splice(0, _self.importFields.length);
      if (data == undefined || data.length == 0) {
        return;
      }
      _self.importFields = data.importFields;

      let columns = JSON.parse(JSON.stringify(_self.importFields));
      columns.forEach(function (item) {
        item.title = item.displayName;
        item.dataIndex = item.fieldName;
        item.key = item.fieldName;
        item.width = 100;
      });
      _self.columns = columns;
      _self.columns.push({
        title: _self.$t('lang.DataImportPanel.processingResults'),
        dataIndex: 'ImportResult',
        key: 'ImportResult',
        width: 100,
        fixed: 'right',
        // scopedSlots: { customRender: 'ImportResult' },
      });
    },

    /**
     * [测试导入点击事件]
     * @return {[type]} [description]
     */
    testImportButton: function (isformalImport) {
      var _self = this;
      var sheetIndex = _self.selectedIndex;
      if (
        _self.selectedDataTemplateNo == '' ||
        _self.selectedDataTemplateNo == undefined
      ) {
        Notify.error(
          _self.$t('lang.Notify.prompt'),
          _self.$t('lang.DataImportPanel.describe3'),
          false,
        );
        return;
      }

      if (
        _self.selectedDataTemplate == '' ||
        _self.selectedDataTemplate == undefined
      ) {
        Notify.error(
          _self.$t('lang.Notify.prompt'),
          _self.$t('lang.DataImportPanel.describe3'),
          false,
        );
        return;
      }

      if (sheetIndex < 0 || sheetIndex == undefined) {
        Notify.error(
          _self.$t('lang.Notify.prompt'),
          _self.$t('lang.DataImportPanel.describe4'),
          false,
        );
        return;
      }

      var importTableData = {
        isForamlImport: isformalImport,
        sheetIndex: sheetIndex,
        importTable: _self.importTable,
        dataTemplateVersion: _self.selectedDataTemplate.version,
      };

      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('dataImportResource/saveImportModelData'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(importTableData),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          _self.showTestImportTable(data.dataList);
          _self.uploadClassFile();
          if (data.isSuccess) {
            if (isformalImport) {
              Notify.info(
                _self.$t('lang.Notify.success'),
                _self.$t('lang.DataImportPanel.describe5'),
                false,
              );
            } else {
              Notify.info(
                _self.$t('lang.Notify.success'),
                _self.$t('lang.DataImportPanel.describe6'),
                false,
              );
            }
          } else {
            if (isformalImport) {
              Notify.error(
                _self.$t('lang.Notify.fail'),
                _self.$t('lang.DataImportPanel.describe7'),
                false,
              );
            } else {
              Notify.error(
                _self.$t('lang.Notify.fail'),
                _self.$t('lang.DataImportPanel.describe8'),
                false,
              );
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 测试导入之后将文件上传到服务端并保存
     */
    uploadClassFile: function () {
      var _self = this;
      var formData = new FormData();
      formData.append('files', _self.selectedFile);
      $.ajax({
        url: Common.getApiURL('dataImportResource/classFileUpload'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: formData,
        contentType: false,
        processData: false,
        success: function (data) {
          if (data.errorCode != 0) {
            notificationError(data.errorMessage, '导入文件上传失败');
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * [showTestImportTable 渲染测试导入表格数据]
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    showTestImportTable: function (data) {
      var _self = this;
      // 清空数据
      if (data == undefined || data.length == 0) {
        return;
      }

      _self.dataSource = [];

      data.forEach(function (item) {
        _self.dataSource.push(item.data);
        console.log('dataSource:::',_self.dataSource);
      });
    },

    /**
     * 点击正式导入、清空临时表按钮
     */
    runProcessImport: function (selectedDataTemplateNo) {
      var _self = this;
      var no = selectedDataTemplateNo;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('dataImportResource/formalDataImportByIds/') + no,
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          Notify.success(
            _self.$t('lang.DataImportPanel.describe9'),
            data.processResult.result,
            false,
          );
          if (_self.dataTemplateNo != null && _self.taskId != null) {
            _self.finishTask();
          }
          return;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 运行清空流程
     */
    runProcessClear: function (selectedDataTemplateNo) {
      var _self = this;
      var no = selectedDataTemplateNo;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('dataImportResource/clearDataImportByIds/') + no,
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          Notify.success(
            _self.$t('lang.DataImportPanel.describe9'),
            data.processResult.result,
            false,
          );
          return;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    initView: function () {
      let _self = this;
      const dataTemplateNo = this.$route.query.dataTemplateNo;
      if (dataTemplateNo != null) {
        _self.dataTemplateNo = dataTemplateNo;
      }
      _self.taskId = _self.$route.query.taskId;
      console.log('taskId:' + _self.taskId);
    },

    /**
     * 完成任务
     */
    finishTask: function () {
      let _self = this;
      if (_self.taskId == null) {
        Notify.error(
          _self.$t('lang.Notify.error'),
          _self.$t('lang.DataImportPanel.describe10'),
          true,
        );
        return;
      }

      WorkflowResource.finishTask(_self.taskId).then(
        successData => {
          if (successData.errorCode == 0) {
            Notify.success(
              _self.$t('lang.Notify.success'),
              _self.$t('lang.DataImportPanel.describe11'),
            );
          } else {
            Notify.error(
              _self.$t('lang.Notify.error'),
              successData.errorMessage,
            );
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
  },
};
</script>

<style scoped>
.row {
  margin: 10px 0px;
}

.fileInput {
  width: 200px !important;
  font-size: 12px !important;
}
.form-control{
  margin-left: 20px;
}
label {
  /* margin-bottom: 0px !important; */
  margin-top: 24px;
}
/* .downloadTemplateLabel{
  margin-left: -160px;
} */
/* .form-inline{
  margin-top: 24px;
} */
.button-item {
  margin-right: 5px;
}
.checkResultFlag {
  background-color: red;
}
.steps-content {
  /* margin-top: 16px; */
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 240px;
  /* text-align: center; */
  padding-top: 8px;
}

.steps-action {
  margin-top: 8px;
 position: relative;
}
.prevBtn{
  position: absolute;
  left: 8px;
}
.nextBtn{
  position: absolute;
  right: 8px;
}
.btn-primary {
    color: #fff;
    background: #1890ff;
    border-color: #1890ff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.12);
    box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
    margin-left: 5px;
}
</style>
