<template>
  <LJDialog ref="DialogRef">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      v-model:file-list="fileList"
      drag
      action="#"
      :auto-upload="false"
      v-bind="$attrs"
      :on-change="handelChange"
      :on-exceed="handleExceed"
      :limit="1"
      :format="['xls', 'xlsx']"
      accept=".xls, .xlsx"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
    </el-upload>
    <div style="text-align: right">
      <el-button class="ml-3" type="success" :loading="uploading" @click="confirm"> 导入 </el-button>
    </div>
  </LJDialog>
</template>

<script setup lang="tsx" name="ImportPrice">
import { ref, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { ImportMtrlPrice } from "@/api/modules/basicinfo";
import LJDialog from "@/components/LjDialog/index.vue";
import { base64 } from "js-md5";
import { ElNotification } from "element-plus";
import { TYPE, useToast, POSITION } from "vue-toastification";
import ToastErrCopy from "@/components/ToastWidget/ToastErrCopy/index.vue";
//import type { FileParams } from "../index.vue";

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

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

const emit = defineEmits(["uploaded", "closed"]);
const basedata = ref();
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);
const DialogRef = ref();
const uploadRef = ref();
/**
 * @description 上传文件
 * @param data
 */
const afterReader = async (data: any) => {
  console.log("afterReader :>> ", data);

  let res = await ImportMtrlPrice({
    filename: data[0].fileName,
    base64: data[0].base64
  });
  console.log("afterReader res :>> ", res);

  let errmsg = "";
  if (res?.messageList.length > 0) {
    errmsg = `,以下类别或物料不存在 <br />` + res.messageList.join(" <br />");
  }
  // ElNotification({
  //   title: "温馨提示",
  //   message: `读取${res.allqty}条数据，成功录入${res.successqty}个价格，失败${res?.messageList.length}个物料` + errmsg,
  //   type: "warning"
  // });

  const toast = useToast();
  toast(
    {
      component: ToastErrCopy,
      props: {
        type: "info",
        title: "温馨提示",
        message: `读取${res.allqty}条数据，成功录入${res.successqty}个价格，失败${res?.messageList.length}个物料` + errmsg
      }
    },
    {
      position: POSITION.TOP_RIGHT,
      icon: false,
      timeout: 0,
      closeButton: true,
      toastClassName: "longjoe-toast"
    }
  );
  // setTimeout(() => {
  ElMessage.success("导入成功");
  successStatus.value = true;
  setTimeout(() => {
    DialogRef.value.hide();

    emit("closed");
  }, 500);

  uploading.value = false;
  //   closeTimer.value = setInterval(() => {
  //     toCloseTime.value--;
  //     if (toCloseTime.value <= 0) {
  //       handleClose();
  //     }
  //   }, 1000);
  // }, 2000);
};

const confirm = async () => {
  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);
    //reader.readAsArrayBuffer(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),
        fileName: item.name,
        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);
      } else {
        uploading.value = false;
      }
    };
  });
};
const handelChange = (file: any) => {};
const handleExceed = (files: any) => {
  uploadRef.value.clearFiles();
  nextTick(() => {
    uploadRef.value.handleStart(files[0]);
  });
};
const handleClose = () => {
  clearInterval(closeTimer.value);
  uploading.value = false;
  fileList.value = [];
  emit("uploaded");
  //visible.value = false;
  successStatus.value = false;
  DialogRef.value.hide();
};
const show = () => {
  DialogRef.value.show();
  fileList.value = [];
};
defineExpose({
  show
});
</script>
