<template>
  <div class="container-fluid">
    <Navbar :title="$t('lang.DataImportPanel.DataImport')" :is-go-back="true" />

    <div style="margin-top: 1.2rem">
      <a-steps :current="current">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" :description="item.description" />
      </a-steps>

      <a-divider />

      <div>
        <div v-if="current === 0" class="row">
          <div>
            <div>
              <div class="operation-group">
                <label>1.请选择导入模板</label>
                <a-select
                  v-model:value="selectedDataTemplateNo" class="operation-content" style="width: 100%"
                  @change="changeSelected()"
                >
                  <a-select-option value="" />
                  <a-select-option
                    v-for="dataTemplate in dataTemplates" :key="dataTemplate.dataTemplateNo"
                    :value="dataTemplate.dataTemplateNo"
                  >
                    {{ dataTemplate.dataTemplateName }}
                  </a-select-option>
                </a-select>
              </div>
              <div class="operation-group">
                <label>2.请下载导入模板</label><br />
                <a-button style="padding: 0" type="link" @click="downloadTemplateButton">
                  {{ $t("lang.DataImportPanel.downloadTemplate") }}
                </a-button>
              </div>
            </div>
          </div>
        </div>

        <div v-if="current === 1" class="row">
          <div>
            <div>
              <div class="operation-group">
                <label>3.请选择Excel数据</label><br />
                <a-upload 
                  v-model:file-list="fileList" :show-upload-list="false" :before-upload="beforeUpload"
                  @change="handleFile"
                >
                  <a-button>
                    <upload-outlined />
                    请选择Excel数据
                  </a-button>
                </a-upload>
                <span>{{ uploadFilePath }}</span>
              </div>
              <div class="operation-group">
                <label>4.请选择需要导入的sheet</label><br />
                <a-select v-model:value="selectedIndex" class="operation-content" style="width: 100%">
                  <a-select-option v-for="(sheetItem, index) in sheetItems" :key="index" :value="index">
                    {{ sheetItem }}
                  </a-select-option>
                </a-select>
              </div>
            </div>
          </div>
        </div>

        <div v-if="current === 2" class="row">
          <div>
            <div>
              <!-- <label>{{ $t("lang.DataImportPanel.stepThree") }}.</label> -->
              <div v-if="sheetItems.length > 0" style="display: flex; align-items: center">
                <span style="color: red">*</span>
                <label style="margin-bottom: 0">导入行数：</label>
                <a-input-number v-model:value="lineCount" :min="0" style="width: 80px; margin-right: 8px" />
                <span style="color: red">*</span>
                <label style="margin-bottom: 0">导入列数：</label>
                <a-input-number v-model:value="columnCount" :min="0" style="width: 80px; margin-right: 8px" />
                <a-button type="primary" class="btn-primary" @click="testImportButton(true)">
                  {{ $t("lang.DataImportPanel.testImport") }}
                </a-button>
                <a-button
                  v-if="isError"
                  type="primary"
                  class="btn-primary"
                  @click="exportErrorExcel"
                >
                  导出Excel
                </a-button>
                <a-button
                  v-if="testSuccess"
                  type="primary"
                  class="btn-primary"
                  @click="runProcessImport"
                >
                  {{ $t("lang.DataImportPanel.formalImport") }}
                </a-button>
                <!-- <a-button
                  type="button"
                  class="btn btn-primary btn-primary-1 btn-primary-import"
                  @click="runProcessClear(selectedDataTemplateNo, false)"
                >
                  3.{{ $t("lang.DataImportPanel.emptyImport") }}
                </a-button> -->
                <a-button
                  v-if="taskId != null && taskId.length > 0"
                  type="primary"
                  class="btn-primary"
                  @click="finishTask"
                >
                  {{ $t("lang.DataImportPanel.completeTask") }}
                </a-button>
              </div>
            </div>
          </div>

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

          <CommonTable v-if="current === 2" :columns="columns" :data-source="dataSource" :extra-height="66">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'ImportResult'">
                {{ record.ImportResult }}
              </template>
            </template>
          </CommonTable>
          <Loading v-if="loading" />
        </div>
      </div>
      <div class="steps-action">
        <a-button v-if="current === 1" class="prevBtn" @click="prev">
          上一步
        </a-button>
        <a-button v-if="current === 2" class="prevFixed" @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 CommonTable from '../common/CommonTable.vue';
import DownloadService from '../resource/file/DownloadService.js';
import WorkflowResource from '../api/workflow/WorkflowResource.js';
import { Notify, Uuid, Navbar } from 'pc-component-v3';
import { notificationError } from '../common/notification.js';
import { UploadOutlined } from '@ant-design/icons-vue';

import {
  UserOutlined,
  SolutionOutlined,
  LoadingOutlined,
  SmileOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
export default {
  components: {
    UserOutlined,
    SolutionOutlined,
    LoadingOutlined,
    SmileOutlined,
    Navbar,
    CommonTable,
    UploadOutlined,
  },

  data: function () {
    return {
      current: 0,
      steps: [
        {
          title: '步骤一',
          description: '选择模板',
        },
        {
          title: '步骤二',
          description: '上传文件',
        },
        {
          title: '步骤三',
          description: '导入成功',
        },
      ],
      dataTemplates: [],
      selectedDataTemplateNo: '',
      selectedDataTemplate: '', // 选择的导入模板
      uploadFilePath: '',
      sheetItems: [],
      importFields: [],
      importTable: {},
      selectedIndex: undefined,
      dataTemplateNos: [],
      loading: false,
      selectedFile: null,
      dataTemplateNo: null,
      taskId: null,

      columns: [], // 列定义
      dataSource: [], // 表格数据源
      lineCount: null, // 导入行数
      columnCount: null, // 导入列数
      testSuccess: false, // 测试导入是否成功
      isError: false,
      batchNo: null, //批次号
      fileList: [],
    };
  },

  computed: {},

  mounted: function () {
    var _self = this;
    _self.initView();

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

  methods: {
    beforeUpload(file) {
      return false;
    },
    /**
     * 步骤条切换
     */
    next() {
      console.log('selectedDataTemplateNo:::', this.selectedDataTemplateNo);
      if (!this.selectedDataTemplateNo) {
        message.error('请选择导入模板');
      } else {
        this.current++;
      }
      if (this.current == 2) {
        this.testSuccess = false;
        this.runProcessClear(this.selectedDataTemplateNo, true);
      }
    },
    prev() {
      this.current--;
      this.isError = false;
    },

    /**
     * [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 = [];
      _self.batchNo = null;
      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;

            var downloadUrl =
              '/api/dataImportResource/downloadTemplateFile?dataTemplateNo=' +
              _self.selectedDataTemplateNo;

            var fileName = realtivePath != null ? realtivePath : '导入模板.xls';

            DownloadService.downloadFile(downloadUrl, fileName);
          }
        }
      } else {
        message.error('请先选择导入模板');
      }
    },

    /**
     * [handleFile 选择文件]
     * @return {[type]} [description]
     */
    handleFile: function (info) {
      var _self = this;
      const file = info.file.originFileObj || info.file;
      _self.uploadFilePath = file.name;
      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 = info.fileList;
      if (fileList.length > 0) {
        _self.selectedFile = file;
        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);
        },
        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;
      }
      _self.selectedIndex = 0;
    },

    /**
     * [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);
          _self.columnCount = data.importFields.length;
        },
        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 = 120;
      });
      columns.push({
        title: _self.$t('lang.DataImportPanel.processingResults'),
        dataIndex: 'ImportResult',
        key: 'ImportResult',
        width: 150,
        fixed: 'right',
        filters: [
          {
            text: '成功',
            value: '成功',
          },
          {
            text: '失败',
            value: '失败',
          },
        ],
        filterMultiple: false,
        onFilter: (value, record) => record.ImportResult.indexOf(value) === 0,
        // scopedSlots: { customRender: 'ImportResult' },
      });
      _self.columns = columns.map(item => ({
        ...item,
        resizable: true,
        mainWidth: 75,
        maxWidth: 400,
        ellipsis: true,
      }));
    },

    /**
     * [测试导入点击事件]
     * @return {[type]} [description]
     */
    testImportButton: function (isformalImport) {
      var _self = this;
      var sheetIndex = _self.selectedIndex;

      if (_self.lineCount <= 0) {
        message.warning('请输入正确的导入行数！');
        return;
      }
      if (_self.columnCount <= 0) {
        message.warning('请输入正确的导入列数！');
        return;
      }

      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 = {
        no: _self.selectedDataTemplateNo,
        isForamlImport: isformalImport,
        sheetIndex: sheetIndex,
        importTable: _self.importTable,
        dataTemplateVersion: _self.selectedDataTemplate.version,
      };
      const lineCount = _self.lineCount;
      const columnCount = _self.columnCount;
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL(
          `dataImportResource/saveImportModelData?lineCount=${lineCount}&columnCount=${columnCount}`,
        ),
        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) {
            _self.batchNo = data.batchNo;
            Notify.info(
              _self.$t('lang.Notify.success'),
              _self.$t('lang.DataImportPanel.describe5'),
              false,
            );
          } else {
            Notify.error(
              _self.$t('lang.Notify.fail'),
              _self.$t('lang.DataImportPanel.describe7') +
              `导入成功${data.successCount}条，导入失败${data.errorCount}条。`,
              false,
            );
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 导出表格数据
    exportErrorExcel: function () {
      const _self = this;
      const url = Common.getApiURL('dataImportResource/downloadTemplateExcel');
      const xhr = new XMLHttpRequest();
      xhr.open('get', url, true);
      xhr.setRequestHeader('token', localStorage.getItem('#token'));
      xhr.setRequestHeader('Content-type', 'application/json');
      xhr.responseType = 'blob';
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let res = xhr.response;
          let blob = new Blob([res]);
          const blobUrl = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.download = `${_self.selectedDataTemplate.dataTemplateName}.xlsx`;
          link.style.display = 'none';
          link.href = blobUrl;
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(blobUrl);
          document.body.removeChild(link);
        }
      };
      xhr.send();
    },
    /**
     * 测试导入之后将文件上传到服务端并保存
     */
    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);
      });
      // message
      const flag = _self.dataSource.every(item => {
        return item.ImportResult === '成功';
      });
      if (flag) {
        this.testSuccess = true;
        this.isError = false;
      } else {
        this.testSuccess = false;
        this.isError = true;
      }
    },

    /**
     * 点击正式导入、清空临时表按钮
     */
    runProcessImport: function () {
      var _self = this;
      if (_self.lineCount <= 0) {
        message.warning('请输入正确的导入行数！');
        return;
      }
      if (_self.columnCount <= 0) {
        message.warning('请输入正确的导入列数！');
        return;
      }
      const no = _self.selectedDataTemplateNo;
      const params = {
        batchNo: _self.batchNo,
      };
      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('dataImportResource/formalDataImportByIds/') + no,
        type: 'post',
        dataType: 'json',
        data: params,
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;

          if (data != null && data.processResult != null && data.processResult.success == true) {
            Notify.success(_self.$t('lang.DataImportPanel.describe9'), data.processResult.result, false);
          } else {
            Notify.error(_self.$t('lang.DataImportPanel.describe12'), 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, flag) {
      var _self = this;
      var no = selectedDataTemplateNo;
      _self.loading = true;
      _self.dataSource = [];
      $.ajax({
        url: Common.getApiURL('dataImportResource/clearDataImportByIds/') + no,
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading = false;
          console.log(
            _self.$t('lang.DataImportPanel.describe9') +
            '!' +
            data.processResult.result,
          );
        },
        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;
}

.operation-group {
  margin-bottom: 10px;
}

.operation-content {
  margin-top: 10px;
}

.btn-primary {
  margin-right: 10px;
}

.button-item {
  margin-right: 5px;
}

.checkResultFlag {
  background-color: red;
}

.steps-action {
  margin-top: 8px;
  position: relative;
}

.prevBtn {
  position: absolute;
  left: 0px;
}

.nextBtn {
  position: absolute;
  right: 0px;
}

.prevFixed {
  position: fixed;
  top: 92%;
}

.btn-primary-1 {
  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);
  border: 1px solid transparent;
  border-radius: 2px;
}

.btn-primary-block {
  display: block;
}

.btn-primary-import {
  margin-left: 5px;
}

:deep(.ant-table-sticky-scroll) {
  display: none !important;
}

.ant-divider-horizontal {
  margin: 12px 0 !important;
}
:deep(.ant-btn-default){
  margin-top: 10px !important;
}
</style>
