<template>
  <el-popover :visible="visible" placement="bottom" :width="400" trigger="click">
    <template #reference>
      <slot name="default" :show="() => (visible = true)"></slot>
    </template>
    <el-result
      v-if="successStatus"
      class="enter-x"
      icon="success"
      :title="$t('sys.api.operationSuccess')"
      :sub-title="`成功上传${fileList.length}个文件`"
    >
      <template #extra>
        <el-button type="primary" @click="handleClose">{{ `${$t("common.okText")}(${toCloseTime})` }}</el-button>
      </template>
    </el-result>
    <template v-else>
      <header class="flx-justify-between mb-12">
        <el-button class="flx-1" :disabled="uploading" @click="visible = false">
          {{ $t("common.cancelText") }}
        </el-button>
        <el-button class="flx-1" :disabled="uploading" :loading="uploading" type="primary" @click="confirm">
          {{ `${$t("common.upload")}${fileList.length > 0 ? "(" + fileList.length + ")" : ""}` }}
        </el-button>
      </header>
      <el-upload
        v-model:file-list="fileList"
        v-loading="uploading"
        class="upload-demo"
        drag
        action="#"
        multiple
        :auto-upload="false"
        v-bind="$attrs"
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          {{ $t("business.tips.file.dropFileHere") }} or <em>{{ $t("business.tips.file.clickUpload") }}</em>
        </div>
        <!-- <template #tip>
          <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
        </template> -->
      </el-upload>
    </template>
  </el-popover>
</template>

<script setup lang="tsx" name="LjFileUploadWidget">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import { UploadFile } from "@/api/modules/common";
import type { FileParams } from "../index.vue";

interface UploadWidgetProps {
  limit?: number;
  params: FileParams;
}

const props = withDefaults(defineProps<UploadWidgetProps>(), {
  limit: 0
});

const emit = defineEmits(["uploaded"]);

const fileList = ref([]);
// const popoverRef = ref();
const visible = ref(false);
const uploading = ref(false);
const successStatus = ref(false);
const closeTimer = ref();
const toCloseTime = ref(3);

/**
 * @description 上传文件
 * @param data
 */
const afterReader = async (data: any) => {
  console.log("afterReader :>> ", data);

  await UploadFile({
    fileList: data
  });

  // setTimeout(() => {
  ElMessage.success("上传成功");
  successStatus.value = true;
  closeTimer.value = setInterval(() => {
    toCloseTime.value--;
    if (toCloseTime.value <= 0) {
      handleClose();
    }
  }, 1000);
  // }, 2000);
};

const confirm = () => {
  toCloseTime.value = 3;
  console.log("fileList :>> ", fileList.value);
  if (!fileList.value.length) {
    ElMessage.warning("请选择文件");
    return;
  }
  uploading.value = true;
  // 读取文件内容
  let base64List: any = [];
  let successKey = 0;
  fileList.value.map((item: any, index: number) => {
    console.log("fileList item :>> ", item, item.raw);
    // 创建FileReader对象
    const reader = new FileReader();
    // 读取文件内容
    reader.readAsDataURL(item.raw);
    // 当文件读取完成时的回调函数, 将文件内容转换为base64格式
    reader.onload = () => {
      let netIndex = item.name.lastIndexOf("."); // 获取最后一个.的位置
      let file = {
        ...props.params,
        fileName: item.name.substring(0, netIndex),
        fileType: item.name.substring(netIndex + 1),
        base64: reader.result,
        ClassID: props.params.classid
      };
      base64List.push(file);
      successKey++;
      // 将文件内容转换为base64格式
      console.log("reader.result :>> ", index, successKey, reader.result);
      if (successKey == fileList.value.length) {
        afterReader(base64List);
      }
    };
  });
};

const handleClose = () => {
  clearInterval(closeTimer.value);
  uploading.value = false;
  fileList.value = [];
  emit("uploaded");
  visible.value = false;
  successStatus.value = false;
};
</script>
