<template>
  <div class="page-wrapper batch-import">
    <div class="batch-import-title">
      {{ $t("BATCH_IMPORT") }}
      <span v-if="$route.query.objectName">
        ({{ $t($route.query.objectName) }})
      </span>
    </div>
    <div class="page-container">
      <div class="batch-import-content mt-10">
        <img
          src="~assets/images/batch-import.png"
          :alt="$t('IMPORT_PICTURE')"
        />
        <div class="batch-import-btns flex" style="justify-content: center">
          <a-button
            type="primary"
            icon="cloud-download"
            :disabled="loading"
            @click="handleDownload"
          >
            {{ $t("DOWNLOAD_IMPORT_TEMPLATE") }}
          </a-button>

          <MegaUploader
            ref="upload"
            class="ml-2"
            :attrs="{
              accept: '.xls,.xlsx',
            }"
            :options="options"
            @fileSuccess="uploadChange"
          >
            <a-button
              type="primary"
              ghost
              icon="cloud-upload"
              :disabled="loading"
            >
              {{ $t("UPLOAD") }}
            </a-button>
          </MegaUploader>
          <span class="ml-2">
            <a-button @click="goBack">
              <Icon type="icon-dir-f-rollback" :size="18" />
              {{ $t("BACK") }}
            </a-button>
          </span>
        </div>

        <div v-show="loading" class="uploading">
          <div class="uploading-content">
            <span v-for="item in 5" :key="item"></span>
          </div>
        </div>

        <div
          v-show="cycleData.status === 'EXCEPTION'"
          class="batch-import-result"
        >
          <span class="error-title">{{ $t("UPLOAD_ERROR") }}：</span>
          <a
            v-if="cycleData.resultFileUrl"
            :href="cycleData.resultFileUrl"
            download
            >{{ $t("DOWNLOAD_EXCEPTION_FILE") }}</a
          >
          <span v-show="cycleData.remark" class="error-title"
            >{{ cycleData.remark }}，</span
          >
          <span>{{ $t("UPLOAD_AGAIN") }}</span>
        </div>

        <div
          v-show="cycleData.status === 'SUCCESS'"
          class="batch-import-result"
        >
          <span class="success-title">{{ $t("UPLOAD_SUCCESS") }}</span>
        </div>
      </div>
    </div>

    <!--<div class="page-bottom-op">
      <a-button @click="goBack">
        <Icon type="icon-dir-f-rollback" :size="18" />
        {{ $t("CANCEL") }}
      </a-button>
    </div>-->
  </div>
</template>

<script>
import { Uploader as MegaUploader, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaUploader,
    Icon,
  },
  data() {
    return {
      options: {
        allowDuplicateUploads: true,
        target: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload/chunk`,
        headers: {
          Authorization: this.$auth.getToken("local"),
          tenantId:
            this.$store.state.app.systemConfig.TENANT_OPEN === "true"
              ? this.$store.state.account.tenantId
              : "",
        },
        testChunks: true,
        chunkSize: 10 * 1024 * 1024,
        singleFile: true,
        showUploadList: true,
      },
      form: {
        objectName: "",
        fileName: "",
      },
      fileFormData: null,
      fileList: [],

      timer: null,
      cycleData: {
        status: undefined,
        resultFileUrl: undefined,
      },
      loading: false,
    };
  },
  methods: {
    handleDownload() {
      const { objectName } = this.$route.query;
      if (objectName) {
        const a = document.createElement("a");
        a.href = `/template/${objectName}.xlsx`;
        a.download = "";
        a.click();
      }
    },
    uploadChange(file) {
      this.fileFormData = file;
      this.handleImportSave();
    },
    handleImportCancel() {
      this.$refs.upload?.sFileList.forEach((file) => {
        this.$refs.upload.handleRemove(file);
      });
      this.$refs.upload?.uploader.fileList.forEach((file) => {
        file.cancel();
      });
      this.fileList = [];
    },
    handleImportSave() {
      this.$axios
        .put(
          `${ApiConstant.PREFIX_CORE}/api/sys/file/merge-chunks/${this.fileFormData.name}/${this.fileFormData.size}`
        )
        .then((res) => {
          this.loading = true;
          const { objectName } = this.$route.query;
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/data-import`, {
              objectName,
              fileCode: res.data.data.fileCode,
              fileUrl: res.data.data.fileUrl,
              language: this.locale || "zh_CN",
            })
            .then((dataImportRes) => {
              this.cycleData = {
                status: undefined,
                resultFileUrl: undefined,
              };
              this.handleCycle(dataImportRes.data.data).then((r) => {
                if (r.status === "SUCCESS") {
                  this.$message.success(this.$t("UPLOAD_SUCCESS"));
                }
              });
            });
        });
    },
    handleCycle(id) {
      return new Promise((resolve, reject) => {
        this.timer = setInterval(async () => {
          if (["EXCEPTION", "SUCCESS"].includes(this.cycleData?.status)) {
            clearInterval(this.timer);
            resolve(this.cycleData);
          } else {
            try {
              const res = await this.$axios.get(
                `${ApiConstant.PREFIX_CORE}/api/data-import/get-status/${id}`
              );
              this.loading = !["EXCEPTION", "SUCCESS"].includes(
                res.data.data?.status
              );
              this.cycleData = res.data.data;
            } catch (_err) {}
          }
        }, 2000);
      });
    },
    goBack() {
      const { prevUrl = "/home", objectName, ...rest } = this.$route.query;
      this.$router.push({
        path: prevUrl,
        query: { ...rest },
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import (optional, once) "~assets/less/color";

.batch-import {
  .page-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  &-title {
    line-height: 36px;
    padding: 0 20px;
    border-bottom: 1px solid @layout-body-background;
  }
  &-content {
    text-align: center;
  }
  &-btns {
    text-align: center;
    margin-top: 60px;
  }
  &-result {
    margin-top: 30px;
    .error-title {
      color: @error-color;
    }
    .success-title {
      color: @success-color;
    }
  }

  .uploading {
    position: relative;
    height: 10px;
    margin: 0 auto;
    margin-top: 20px;
    &-content {
      position: absolute;
      width: 100px;
      height: 10px;
      left: 50%;
      transform: translate(-100%, 0);
    }
    span {
      position: absolute;
      width: 10px;
      height: 100%;
      border-radius: 50%;
      background: @primary-color;
      animation: uploading 1.04s ease-in infinite alternate;
    }
    span:nth-child(1) {
      animation-delay: 0.13s;
    }
    span:nth-child(2) {
      animation-delay: 0.26s;
    }
    span:nth-child(3) {
      animation-delay: 0.39s;
    }
    span:nth-child(4) {
      animation-delay: 0.52s;
    }
    span:nth-child(5) {
      animation-delay: 0.65s;
    }
  }
}
/deep/.ant-upload-list-item-info {
  position: absolute;
  width: 800px;
  left: -390px;
  .ant-upload-list-item-name {
    width: auto;
  }
}
@keyframes uploading {
  0% {
    opacity: 1;
    transform: translate(0);
  }
  100% {
    opacity: 0.2;
    transform: translate(100px);
  }
}
</style>
