<template>
  <div class="data-migration">
    <div class="top-box">
      <div class="title-box">岗位批处理</div>
    </div>
    <div class="bottom-box">
      <div class="empty-box" v-if="info.fileList.length === 0">
        <el-empty></el-empty>
        <div class="upload-box">
          <el-upload
              class="upload-demo"
              :action="info.uploadAction"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-success="handleSuccess"
              :limit="1"
              :on-exceed="handleExceed"
              :show-file-list="false"
          >
            <awsui-button type="primary" @click="handleUploadBtn">导入Excel文件</awsui-button>
            <template #tip>
              <div class="el-upload__tip">
                仅支持xls格式文本
              </div>
            </template>
          </el-upload>
        </div>
      </div>
      <div class="file-list-box" v-else>
        <el-scrollbar height="400px">
          <div v-for="item in info.fileList" :key="item" class="scrollbar-demo-item">
            <div>{{ item.name }} <i class="awsui-iconfont" style="cursor: pointer; position: relative; top: 2px;" @click="removeFile">&#xe626;</i></div>
          </div>
        </el-scrollbar>
      </div>
      <div class="action-box" v-if="info.fileList.length > 0">
        <awsui-button style="cursor: pointer" type="primary" @click="next">执行导入</awsui-button>
      </div>
    </div>
  </div>
  <el-dialog
      title="日志"
      v-model="dlg.visible"
      width="800px"
      height="520px"
      destroy-on-close
      @close="dlgClose">
    <div style="width: 100%;height: 500px;">
      <log-codemirror ref="dataCodemirrorRef" :width="logCodemirror.width" :height="logCodemirror.height" :log-str="logCodemirror.logStr" ></log-codemirror>
      <div style="width: 100%;height: 10px;">
        <el-progress :percentage="result.totalCount == 0 ? 0 : (Math.floor(result.importingCount / result.totalCount * 100))" color="#287ff4" />
      </div>
      <div style="width: 100%;height: 10px;text-align: left;">
        <span>正在导入第[{{result.importingCount}}]条，总共[{{result.totalCount}}]条</span>
      </div>

    </div>
    <template #footer>
      <span class="dialog-footer">
      <awsui-button type="primary" @click="downloadLog">下载日志</awsui-button>
      <awsui-button @click="dlg.visible = false">关闭</awsui-button>
    </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import {defineComponent, getCurrentInstance, reactive, ref, nextTick} from 'vue';
import LogCodemirror from "./log-codemirror";
export default defineComponent({
  name: "position-import",
  components: {
    LogCodemirror,
  },
  setup() {
    const {proxy: $this} = getCurrentInstance();
    const dataCodemirrorRef = ref();
    let info = reactive({
      activeStep: 0,
      steps: [{title: "上传"}, {title: "校验"}, {title: "结果"}],
      fileList: [],
      uploadAction: '',
      repositoryName: 'positionExcel',
      groupValue: 'upfile',
      fileValue: '',
      appId: 'com.actionsoft.apps.coe.pal.datamigration',
      fileName: ''
    });
    let dlg = reactive({
      visible: false
    })
    let logCodemirror = reactive({
      height: '100%',
      width: '100%',
      logStr: ''
    })
    const result = reactive({
      path: '',
      logId : '',
      totalCount : 0,
      importingCount: 0,
      resultStatus: 0,
      interval: null, // 查询日志定时器
      timer:0, // 时间戳记录
    })
    const handleClose = (done: () => void) => {
      done();
    }
    const handlePreview = () => {
    }
    const handleRemove = () => {
    }
    const beforeRemove = () => {
    }
    const handleExceed = () => {
    }
    const handleSuccess = (res: any, uploadFile: any, uploadFiles: any) => {
      console.log(res, '---', uploadFile, '----', uploadFiles)
      info.fileName = res.files.name
      let tempFileObj = {id: uploadFile.uid, name: res.files.name, downloadUrl: res.data.data.attrs.downloadUrl}
      info.fileList.push(tempFileObj)
      console.info('fileList', info.fileList)
    }
    const dlgClose = () => {
      if (result.resultStatus == 0) {
        $this.$message({message: '导入正在进行中，关闭窗口不影响导入的执行', type: 'warning',})
      }
      clearResult();
      logCodemirror.logStr = '';
    }
    const clearResult = () => {
      if (result.interval != null) {
        removeInterval();
      }
      result.path = '';
      result.logId = '';
      result.totalCount = 0;
      result.importingCount = 0;
      result.resultStatus = 0;
      result.interval = null; // 查询日志定时器
      result.timer = 0; // 时间戳记录
    }
    const next = () => {
      if (info.fileList.length === 0) {
        $this.$message({type: 'warning', message: '请上传文件'});
        return;
      }
      dlg.visible = true;
      const param = {
        url: './jd',
        data: {
          cmd: 'com.actionsoft.apps.coe.pal.datamigration_position_import',
          sid: settingParam.sessionId,
          wsId: settingParam.wsId ? settingParam.wsId : '1b19ab87-5727-4621-bc3f-117183b06e59',
          groupValue: info.groupValue,
          fileValue: info.fileValue,
          fileName: info.fileName
        }
      }
      $this.awsuiaxios.post(param)
          .then((ro: any) => {
            result.path = ro.data.path;
            result.logId = ro.data.logId;
            result.resultStatus = ro.data.resultStatus;
            if (ro.result == 'ok') {
              result.totalCount = ro.data.totalCount;
              result.importingCount = ro.data.importingCount;
            } else {
              // $this.$message.error(ro.msg);
            }
            getImportInfoEvent();
          })
          .catch((err: any) => {
          })
    }
    // 获取导入进度
    const getImportInfoEvent = () => {
      result.interval = setInterval(queryLog, 1000);
    }
    const queryLog = () => {
      const that = $this;
      result.timer = new Date().getTime();
      const param = {
        url: './jd',
        data: {
          cmd: 'com.actionsoft.apps.coe.pal.datamigration_position_import_log_query',
          sid: settingParam.sessionId,
          logId: result.logId,
          path: result.path,
          timer: result.timer
        }
      }
      that.awsuiaxios.post(param)
          .then((ro: any) => {
            if (ro.result === 'ok') {
              if (parseInt(ro.data.timer) <= result.timer) {
                logCodemirror.logStr = ro.data.content;
                // 添加内容后定位到行尾
                nextTick(()=> {
                  moveLogEnd();
                });
                result.resultStatus = ro.data.resultStatus;
                if (result.resultStatus != 0) {
                  removeInterval();
                  result.importingCount = result.totalCount;// 出错或成功，直接100%
                } else {
                  result.importingCount = ro.data.importingCount;
                }
              }
            } else {
              that.$message.error(ro.msg);
              removeInterval();
            }
          })
          .catch((err: any) => {
          })
    }
    // log-codemirror日志内容移动到行尾部
    const moveLogEnd = () => {
      dataCodemirrorRef.value.moveTextToEnd();
    }
    const removeInterval= () => {
      clearInterval(result.interval);
    }
    const downloadLog = () => {
      // 下载日志
      const that = $this;
      if (result.path == '') {
        that.$message({message: '获取日志失败', type: 'warning'});
        return;
      }
      if (result.resultStatus == 0) {
        that.$message({message: '正在导入，请稍等', type: 'warning'});
        return;
      }
      const param = {
        url:'./jd',
        data:{
          cmd : "com.actionsoft.apps.coe.pal.datamigration_position_import_log_download",
          path: result.path,
          logId: result.logId
        }
      };
      that.awsuiaxios.post(param)
          .then((ro: any) => {
            if (ro.result === 'ok') {
              window.open(ro.data.url);
            } else {
              that.$message.error(ro.msg);
            }
          })
          .catch((err: any) => {
          })
    }
    const removeFile = () => {
      info.fileList = [];
    }
    const handleUploadBtn = () => {
      info.fileValue = 'positionExcel-' + transDate(new Date());
      info.uploadAction = axiosBaseUrl + 'uf?sid=' + settingParam.sessionId + '&repositoryName=' + info.repositoryName + '&groupValue='
          + info.groupValue + '&fileValue=' + info.fileValue + '&appId=' + info.appId;
    }
    const transDate = (date: Date) => {
      var ndate = new Date(date);
      let type = 'yyyy-MM-dd-hhmmss';
      const o = {
        'M+': ndate.getMonth() + 1, // 月份
        'd+': ndate.getDate(), // 日
        'h+': ndate.getHours(), // 小时
        'm+': ndate.getMinutes(), // 分
        's+': ndate.getSeconds(), // 秒
        'q+': Math.floor((ndate.getMonth() + 3) / 3), // 季度
        'S': ndate.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(type)) type = type.replace(RegExp.$1, (ndate.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(type)) type = type.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return type;
    }
    return {
      dataCodemirrorRef,
      info,
      dlg,
      logCodemirror,
      result,
      handlePreview,
      handleRemove,
      beforeRemove,
      handleExceed,
      handleUploadBtn,
      handleSuccess,
      next,
      removeFile,
      handleClose,
      dlgClose,
      downloadLog
    }
  }
})
</script>

<style lang="less" scoped>
.data-migration {
  width: 100%;
  height: 100%;
  background-color: #F7F7FB;

  .top-box {
    height: 75px;
    margin: 0 35px 0 35px;
    display: flex;
    justify-content: space-between;

    .title-box {
      line-height: 75px;
      font-size: 18px;
    }

    .step-box {
      width: 45%;
      padding: 15px 0;
    }
  }

  .bottom-box {
    height: 650px;
    margin: 0 35px 0 35px;
    background-color: rgb(255, 255, 255);
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;

    .empty-box {
      width: 500px;
      height: 500px;

      .upload-box {
        text-align: center;
      }
    }

    .file-list-box {
      width: 100%;

      :deep(.el-scrollbar) {
        padding: 0 25px;
      }

      .scrollbar-demo-item {
        font-size: 16px;
        height: 35px;
        margin: 10px;
        border-radius: 4px;
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        line-height: 35px;
      }
    }
  }
}
</style>