<template>
  <BasicModal
    :title="getTitle"
    :canFullscreen="false"
    :maskClosable="false"
    :showOkBtn="showOkBtn"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleSubmit"
    width="580px"
  >
    <div
      class="wrap"
      :style="{
        borderColor: importInfo[importStatus].borderColor,
        borderStyle: importInfo[importStatus].borderStyle,
      }"
    >
      <div class="wrap-cnt" :style="{ backgroundColor: importInfo[importStatus].backgroundColor }">
        <div>
          <div class="cnt-tit">
            <i
              :class="[
                'iconfont cnt-icon',
                'cnt-icon_' + importStatus,
                importInfo[importStatus].icon,
              ]"
            />
            {{ importInfo[importStatus].title }}
          </div>
          <div v-if="importStatus == 'default'">
            <div class="cnt-desc">
              若是您第一次上传文件，可先下载
              <span :class="['pointer', 'cnt-desc_link']" @click="downloadFile"> 文件模板</span
              >,文件大小不超过5M
            </div>
            <div class="cnt-detail">
              <Upload
                class="button-style"
                name="file"
                :before-upload="handleBeforeUpload"
                :show-upload-list="false"
              >
                <a-button type="primary"> 导入文件 </a-button>
              </Upload>
            </div>
          </div>
        </div>
        <div v-if="importStatus == 'progress'">
          <div class="cnt-desc">
            {{ importInfo[importStatus].desc }}
          </div>
          <div class="cnt-detail">
            <Progress
              :stroke-color="strokeColor"
              :percent="importProgress"
              :showInfo="false"
              status="active"
            />
          </div>
        </div>
        <div v-if="importStatus == 'success'">
          <div :class="['cnt-desc pointer', 'cnt-desc_link']" @click="importStatus = 'default'">
            继续导入数据
          </div>
        </div>
        <div v-if="importStatus == 'fail'">
          <div class="cnt-desc">
            <span class="mr-3">
              成功:
              <span
                :style="{
                  color: '#19BE6B',
                }"
              >
                {{ importFail.success }}
              </span></span
            >
            <span class="mr-3">
              失败:
              <span
                :style="{
                  color: importInfo[importStatus].borderColor,
                }"
              >
                {{ importFail.fail }}
              </span>
            </span>
            <span> 总数: {{ importFail.total }}</span>
          </div>
          <div class="cnt-detail">
            下载失败结果 <a class="cnt-desc_link pointer" @click="exportExcel"> 失败文件</a>
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { excelSheetDetail, getDownloadUrl } from '/@/api/common/index';
  import { downloadByBase64, downloadByUrl } from '/@/utils/file/download';
  import { reactive, ref } from 'vue';
  import { Progress, Upload } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const uploadApi = ref<any>();
  const exportApi = ref<any>();
  const getTitle = ref('导入数据');
  const isComplete = ref(0);
  const exportFileId = ref('');
  const timer = ref(null);
  const showOkBtn = ref(false);
  const strokeColor = {
    '0%': '#00A8FF',
    '100%': '#0072FF',
  };
  const importStatus = ref<'default' | 'progress' | 'success' | 'fail'>('default');
  const importInfo = {
    default: {
      icon: '',
      title: '选择需要导入的文件',
      desc: '',
      borderColor: '#DCDEE2',
      borderStyle: 'dashed',
      backgroundColor: '#F4F6F9',
    },
    progress: {
      icon: '',
      title: '数据导入中…',
      desc: '请稍等, 不要离开此页面',
      borderColor: '#DCDEE2',
      borderStyle: 'dashed',
      backgroundColor: '#F4F6F9',
    },
    success: {
      icon: 'icon-xt-success',
      title: '数据导入成功',
      desc: '',
      borderColor: '#DCDEE2',
      borderStyle: 'solid',
      backgroundColor: '#F4F6F9',
    },
    fail: {
      icon: 'icon-xt-fail',
      title: '数据导入失败',
      desc: '',
      borderColor: '#FF5D39',
      borderStyle: 'solid',
      backgroundColor: '#FFF0ED',
    },
  };
  const importFail = reactive({
    success: 0,
    fail: 0,
    total: 0,
  });
  const importProgress = ref(30);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    console.log('🚀 ~ file: code.vue:21 ~ data:', data);
    setModalProps({ confirmLoading: false });
    getTitle.value = data?.title;
    uploadApi.value = data.importUrl;
    exportApi.value = data.exportUrl;
  });

  async function handleSubmit() {
    showOkBtn.value = false;
    clearInterval(timer.value);
    timer.value = null;
    importProgress.value = 30;
    if (importStatus.value == 'success' || importStatus.value == 'fail') {
      importStatus.value = 'default';
      await closeModal();
    } else {
      importStatus.value = 'default';
    }
  }
  async function startUpload(id) {
    if (id) {
      console.log('🚀 ~ file: ImportModal.vue:197 ~ onChange ~ id:', id);
      timer.value = setInterval(async function () {
        const importStats = await excelSheetDetail(id);
        console.log('importStats', importStats);
        // const percent = (importStats.failCount + importStats.successCount) / importStats.totalCount;
        // 进度条
        console.log('进度条：', importProgress.value);
        if (
          importStats.status == 'parsing' ||
          importStats.status == 'parsingSuccess' ||
          importStats.status == 'importing'
        ) {
          importProgress.value = 90;
          return;
        }
        if (importStats.status == 'importFail') {
          clearInterval(timer.value);
          importStatus.value = 'fail';
          createMessage.error('取消导入');
          return;
        }
        if (importStats.status == 'importSuccess') {
          importProgress.value = 100;
          setTimeout(function () {
            importStatus.value = 'success';
            showOkBtn.value = true;
            clearInterval(timer.value);
            exportFileId.value = importStats.exportFileId;
            importFail.fail = importStats.failCount;
            importFail.success = importStats.successCount;
            importFail.total = importStats.totalCount;
            importProgress.value = 30;
          }, 1000 * 1);
        }
      }, 1000 * 3);
    }
  }
  async function handleBeforeUpload(file) {
    console.log('file', file);
    importStatus.value = 'progress';
    const res = await uploadApi.value(
      {
        data: {},
        file,
        filename: file.name,
      },
      async function onUploadProgress(progressEvent: ProgressEvent) {
        isComplete.value = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
      },
    );
    if (isComplete.value == 100) {
      importProgress.value = 50;
      await startUpload(res.data.data);
      isComplete.value = 0;
    }
    return false;
  }
  async function exportExcel() {
    const res = await getDownloadUrl(exportFileId.value);
    // console.log('res', res);
    downloadByUrl({ url: res });
  }
  async function downloadFile() {
    const res = await exportApi.value([]);
    downloadByBase64(res.base64, res.fileName);
  }
</script>

<style lang="less" scoped>
  .wrap {
    width: 480px;
    height: 180px;
    background: #fff;
    border-radius: 2px;
    border-width: 1px;
    padding: 8px;
    margin: 20px auto;

    &-cnt {
      height: 100%;
      padding-top: 25px;
    }
  }

  .cnt {
    &-icon {
      font-size: 24px;
      margin-right: 4px;

      &_success {
        color: #19be6b;
      }

      &_fail {
        color: #ff5d39;
      }
    }

    &-tit {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 18px;
      font-weight: 500;
      color: #000a18;
      line-height: 25px;
      text-align: center;
      margin-bottom: 10px;
    }

    &-desc {
      font-size: 14px;
      color: #515a6e;
      line-height: 20px;
      text-align: center;
      margin-bottom: 24px;

      &_link {
        font-size: 14px;
        color: #006dff;
        text-decoration-line: underline;
      }
    }

    &-detail {
      text-align: center;
    }
  }

  ::v-deep(.ant-progress-line) {
    width: 152px;
  }

  ::v-deep(.ant-progress-inner) {
    background-color: #fff;
  }
</style>
