<!-- Excel上传组件 -->
<template>
  <el-dialog v-model="dialogVisible" title="文件上传" :destroy-on-close="true" width="580px" draggable top="1vh">
    <el-row justify="end">
      <el-col :span="24" style="text-align: center;">
        <el-text size="large">注意事项：上传文件必须符合模板格式要求，点此<el-link type="primary" @click="downloadFile"><el-text type="primary" size="large">下载模板</el-text></el-link >！ </el-text>
      </el-col>
    </el-row>
    <el-upload ref="fileUpload" :headers="ht" :data="props.data" drag :auto-upload="false" :show-file-list="true" :action="props.uploadUrl" :on-success="excelUploadSuccess" :on-error="excelUploadError"  :before-upload="beforeExcelUpload">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
    </el-upload>
    
    <el-row v-show="''!==uploadResult" style="margin-top:10px" justify="end">
      <el-col :span="24" style="text-align: right;">
        <el-alert type="success" :closable="false">
          <template #default>
            <el-text >
              上传结果:本次一共导入数据[<el-text type="primary">{{ uploadResult.totalNum }}</el-text>]条,
              成功[<el-text type="success" >{{ uploadResult.successNum }}</el-text>]条,
              <el-text v-if="uploadResult.updateNum>0" >修改[<el-text type="success" >{{ uploadResult.updateNum }}</el-text>]条,</el-text>
              失败[<el-text type="warning" >{{ uploadResult.failureNum }}</el-text>]条,
              <el-link type="primary" v-if="uploadResult.filePath!==''" :href="uploadResult.filePath" target="_blank">下载错误信息</el-link>
            </el-text>
          </template>
        </el-alert>
        
      </el-col>
    </el-row>
    <el-row style="margin-top:10px" justify="end">
      <el-col :span="12" style="text-align: right;">
        <el-button type="primary" @click="submitFile">上传</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup lang="ts">
import type {UploadRawFile } from 'element-plus'
import { getAllHeader } from "@/framework/store/modules/user";


const fileUpload=ref()

const ht=getAllHeader()

let props = defineProps({
  //上传时附带的额外参数
  data: {},
  //模板名称（模板需要放在public/templete）
  templateName: { type: String, default: '', },
  //文件上传地址
  uploadUrl: String,
  //是否自定义结果处理
  customResultHandle:{ type: Boolean, default: false },
  //上传文件最大值，单位(MB)
  uploadMaxSize: { type: Number, default: 0 },
})

const dialogVisible = ref(false)

// 下载模板
const downloadFile = () => {
  if (props.templateName === '') {
    return ElMessage({ type: 'error', message: '未配置模板下载路径' })
  }
  let dom = document.createElement("a");
  dom.style.display = 'none'
  dom.target = '_blank'
  dom.href = `./templete/${props.templateName}`
  document.body.appendChild(dom);
  dom.click();
  document.body.removeChild(dom);
}

const submitFile = () => {
  fileUpload.value.submit()
}

/**
 * @description 文件上传之前判断
 * @param file 上传的文件
 * */
const beforeExcelUpload = (file: UploadRawFile) => {
  uploadResult.value=''
  if(!['xls', 'xlsx'].includes(file.name.split('.').pop())){
    ElMessage.warning('上传文件只能是 xls / xlsx 格式' )
    return false;
  }
  if(props.uploadMaxSize>0&&file.size>(props.uploadMaxSize*1024*1024)){
    ElMessage.warning('上传文件大小不能超过'+props.uploadMaxSize+'MB！')
    return false;
  }
  return true;
};
const uploadResult = ref('')

const emit = defineEmits(['updateCheck','resultHandleEvent'])
const excelUploadSuccess = (response: any) => {
  const { message,status,data } = response;
  if(200===response.status){
    if(props.customResultHandle){
      dialogVisible.value=false
      emit('resultHandleEvent', data)
    }else{
      if(data.handleSuccess){
        uploadResult.value=data
      }else{
        ElMessage.error("Excel文件处理失败:"+data.message);
      }
      
    }
  }else{
    if (status === 401) {
      ElMessage.error('未通过身份验证');
    }
    const temp = String(status)[0]
    if (temp === '9') {
      ElMessage.error(message || '系统出错');
      console.error('系统异常', response.data);
      return
    }else{
      ElMessage.error('系统异常');
      console.error('系统异常', response.data);
      return
    }
  }  
}

// 上传错误提示
const excelUploadError = (response: any) => {
  console.error(response);
  if (response.status === 401) {
    ElMessage.error('未通过身份验证');
  }else{
    ElMessage.error('文件上传服务异常');
  }
  
};

defineExpose({
  dialogVisible
});
onMounted(() => {
  uploadResult.value=''
});

</script>
<style lang="scss" scoped>
</style>
