<template>
    <!-- 弹窗组件 -->
    <el-dialog title="Upload files" v-model="dialogVisible" width="30%">
      <div>
        <input type="file" webkitdirectory @change="handleFileSelect" multiple lang="en" accept="*/*"/>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="uploadFiles">Upload</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import eventBus from "@/api/eventBus";
import { base_img_url2 } from "@/api/config";
import { getFileExt } from "@/utils/util";
import OSS from "ali-oss";
import { ElMessage } from "element-plus";

const props = defineProps({
  stsToken: {
    type: Object,
    required: true,
  },
  task:{
    type: Object,
    required: true,
  },
  dialogVisible:{
    type: Boolean,
    default: false,
  }
});

const { accessKeyID, secretAccessKey, sessionToken, region, cloudBucketName,storePath, callbackParam } = props.stsToken;
const {id,terra2dJobId,resourceId} = props.task;
let dialogVisible = ref(props.dialogVisible);
let ossClient = new OSS({
  accessKeyId: accessKeyID,
  accessKeySecret: secretAccessKey,
  stsToken: sessionToken,
  bucket: cloudBucketName,
  region: region,
});


const selectedFiles = ref([]);

// 显示弹窗
const showDialog = () => {
  dialogVisible.value = true;
};

// 处理文件选择
const handleFileSelect = (event) => {
  selectedFiles.value = Array.from(event.target.files);
};

// 上传文件
const uploadFiles = async () => {
  let res = await VE_API.task.uploadedFileList({taskId:id})
  //获取已上传文件列表
  let uploadedFiles = res.data
  if (selectedFiles.value.length === 0) {
    ElMessage.error("Please select the file you want to upload");
    return;
  }
  let i = 0;
  for (const file of selectedFiles.value) {
    if(uploadedFiles.findIndex(item => item === file.name) > -1){
      i++;
      continue;
    }
    try {
      const result = await ossClient.put(`${storePath.replace('{fileName}',file.name)}`, file);
      let etag = result.res.headers.etag
      let params = {file:[{name:file.name, etag:etag ,checksum:etag}],resourceUUID:resourceId,callbackParam:callbackParam, jobId:id};
      VE_API.task.associate(params).then(({code,msg})=>{
        if(code === 0){
          ElMessage.success(`The file association was successful`);
        }else{
          ElMessage.error('File association failed')
        }
      })
      ElMessage.success(`${file.name} Uploaded successfully。${i+1}files have been uploaded，There are${selectedFiles.value.length-i-1}remaining files`);
      i++;
    } catch (e) {
      ElMessage.error(`${file.name} Upload failed: ${e.message}`);
    }
  }



  // 清空文件选择和关闭弹窗
  selectedFiles.value = [];
  dialogVisible.value = false;
  VE_API.task.updateStatus({id,status:1}).then(()=>{
    emit('updateCallback')
  })

};

const emit = defineEmits(['updateCallback'])

// 将showDialog暴露出去，以便在父组件中调用
defineExpose({ showDialog });
</script>

<style scoped>
/* 根据需要添加样式 */
</style>
