<script setup lang="ts">
/**
 * execl上传
 */
import { ref } from "vue";
import { ElMessage, ElUpload, UploadFile, UploadProps } from "element-plus";
import { httpUpload } from "/@/api/InvoiceSales/capitalClaim";
import { useUserStore } from "/@/store/modules/user";
import { useResponseHandle } from "/@/hooks";

const visible = ref(false);
const loading = ref(false);
const uploadRef = ref<InstanceType<typeof ElUpload>>(null);
const execlFile = ref<UploadFile | null>(null);
const responseHandle = useResponseHandle();
const userStore = useUserStore();

//上传成功关闭dialog
const handleUploadSccess = async () => (visible.value = false);

//上传文件改变
const handleChange: UploadProps["onChange"] = uploadFile =>
  (execlFile.value = uploadFile);

//删除穿文件
const handleRemove: UploadProps["onRemove"] = () => (execlFile.value = null);

//上传方法
const handleRequeset: UploadProps["httpRequest"] = async ({ file }) => {
  const formData = new FormData();
  formData.append("excel", file);
  formData.append("token", userStore.token);
  const { message, code } = await httpUpload(formData);

  responseHandle({
    message,
    code,
    handler: () => ElMessage.success("导入文件成功")
  });
};

const handleClose = () => {
  execlFile.value = null;
  uploadRef.value.clearFiles();
};

//提交
const handleSubmit = () => {
  if (!execlFile.value) return ElMessage.error("请选择上传文件");
  uploadRef.value.submit();
};

defineExpose({
  onDisplay: () => (visible.value = true)
});
</script>

<template>
  <el-dialog v-model="visible" title="导入表格数据" center @close="handleClose">
    <el-upload
      ref="uploadRef"
      action="#"
      class="execl-uploader"
      accept=".xls,.xlsx"
      :auto-upload="false"
      :http-request="handleRequeset"
      @change="handleChange"
      @remove="handleRemove"
      @success="handleUploadSccess"
    >
      <div class="el-upload__text" v-if="!execlFile">点击此处,上传文件</div>
    </el-upload>

    <div flex justify-end mt-2 gap-2>
      <el-button type="primary" :loading="loading" @click="handleSubmit"
        >保存</el-button
      >
      <el-button>取消</el-button>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.execl-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;
  flex-direction: column;
  justify-content: center;

  &:hover {
    border-color: var(--el-color-primary);
  }

  .el-upload__text {
    line-height: 200px;
    font-size: 22px;
  }
}
</style>
