<script setup lang="ts">
import type { AxiosRequestConfig } from "axios";
import { ref } from "vue";
import request, { download, REQUEST } from "~/utils/request";

const props = defineProps<{ url: string; d: Object }>();
const emits = defineEmits(["success"]);
const loading = ref(false);
const percentage = ref(0);

const handleTableRowBtns_import = ({ file }: { file: File }) => {
  loading.value = true;
  return REQUEST.import({
    $type: "import",
    url: `${props.url}/import`,
    data: { file, ...props.d },
    onUploadProgress(progressEvent: { loaded: number; total: number }) {
      percentage.value = ~~(
        ((progressEvent.loaded / progressEvent.total) * 100) |
        0
      );
    },
  } as AxiosRequestConfig).then((res: any) => {
    loading.value = false;
    emits("success");
    return res;
  });
};
const handleTableRowBtns_export = () => {
  download(`${props.url}/index`, { limit: 1, ...props.d });
};
</script>

<template>
  <el-popover width="330px" trigger="click">
    <template #reference>
      <el-button :loading="loading" type="primary">
        <template #loading>
          <el-progress class="mr-4px" :width="26" :stroke-width="2" status="success" type="circle" :percentage="percentage">
            <template #default="{ percentage }">
              <span class="percentage-value">{{ percentage }}</span>
            </template>
          </el-progress>
        </template>
        <slot name="text">导 入</slot>
      </el-button>
    </template>
    <p>
      <slot name="tips">请上传正确的格式</slot>
    </p>
    <div class="flex justify-end">
      <el-button type="primary" text class="mr-20px" @click="handleTableRowBtns_export">下载模板</el-button>
      <el-upload :http-request="handleTableRowBtns_import" class="inline-block">
        <el-button>选择文件</el-button>
        <template #file><span></span></template>
      </el-upload>
    </div>
  </el-popover>
</template>

<style lang="scss" scoped>
:deep(.el-progress) {
  .el-progress__text {
    color: var(--el-color-white);
    min-width: min-content;
  }
}
</style>
