<template>
  <div class="webuploader-container">
    <div :id="'uploader' + upId">
      <el-row>
        <!-- <div class="btntext upname wenjian">{{ gfname }}</div> -->
        <div
          class="btntext upname"
          :id="'picker' + upId"
          style="width: 28px; height: 24px"
        >
          <img :src="imgSrc" alt="upload icon" class="custom-icon" />
        </div>
      </el-row>

      <!-- <el-row v-for="(fileObj, key) in files" :key="key" class="disflex">
        <el-col :span="6">{{ fileObj.name }} </el-col>
        <el-col :span="8"
          ><el-progress :percentage="fileObj.percentage"></el-progress
        ></el-col>
        <el-col :span="5">{{ fileObj.msg }}</el-col>
        <el-col :span="5">
          <el-button
            type="danger"
            @click="fileDel(fileObj.id)"
            :icon="Delete"
            circle
        /></el-col>
      </el-row> -->
      <!-- <el-button size="mini" @click="uploader.upload()">开始上传</el-button> -->
    </div>
  </div>
</template>
<script setup>
import $ from "jquery"
// import WebUploader from 'webuploader';
import store from "@/store"
import { request, uploadFile } from "@/utils/request"
import { ElMessage, ElButton, ElDialog } from "element-plus"
import { Check, Delete, Edit, Message, Search, Star } from "@element-plus/icons-vue"
const props = defineProps({
  projectId: Number,
  solverType: String,
  accept: String,
  upId: String,
  name: String,
  namelist: Array, //文件名的集合
  gfname: String,
  imgSrc: String // 按钮logo
})
let emit = defineEmits(["Gassaddgfid", "Gassaddbfid", "upload-success", "update-fileName", "update-percentage","upload-status"])
let runupboolen = ref(true)
let uploader = ref(undefined)
let fileName = ref(undefined)
let md5 = ref("1212")
let files = ref([])
let gfid = ref("")
let bfid = ref("")
let msg = ref()
let nmllist = ref([])
let gridFileId = ref("")
let boundaryFileId = ref("")
let uuid = ref("")
let nmlid = ref("")
let hcfdBoundarys = ref([])
onMounted(() => {
  initup()
})
const initup = () => {
  getUUID()
  uuid.value = getUUID()
  console.log('uuid.value',uuid.value);
  
  initWebUploader()
}
const getUUID = () => {
  return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
//fembdf绑定
const fembdf = (bfid) => {
  let params = {
    transCode: "FEM001",
    pid: props.projectId,
    gridFileId: bfid
  }

  request(params)
    .then((res) => {
      console.log("绑定成功")
    })
    .catch((err) => {})
}
const initWebUploader = () => {
  files.value = []
  uploader.value = WebUploader.create({
    // swf文件路径
    swf: "./js/Uploader.swf",
    // 文件接收服务端。
    server: import.meta.env.VITE_BASE_URL + "/TransServlet",
    //文件上传请求的参数表，每次发送都会发送此对象中的参数。
    formData: {},
    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: {
      id: "#picker" + props.upId,
      multiple: false
    },
    // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
    resize: false,
    // 开起分片上传。
    chunked: true,
    chunkSize: 2 * 1024 * 1024, // 2M
    threads: 4
  })
  // 当有文件被添加进队列的时候

  uploader.value.on("fileQueued", (file) => {
    fileName.value = file.name
    console.log('fileName.value', fileName.value)
    emit('update-fileName', fileName.value)
    // 文件上传类型
    if (props.accept && props.accept.trim() !== "") {
      const ext = fileName.value.split('.').pop().toLowerCase();
      const acceptList = props.accept.split(',').map(e => e.trim().toLowerCase());
      if (!acceptList.includes('.' + ext)) {
        uploader.value.reset();
        ElMessage.error(`只支持 ${props.accept} 格式文件!`);
        return;
      }
    }
    uploader.value
      .md5File(file)
      .progress((percentage) => {
        //显示加密进度
        console.log("Percentage:", percentage)
      })
      .then((hash) => {
        // 完成
        md5.value = hash
      })
    if (files.value.length > 0) {
      uploader.value.removeFile(files.value[0].id)
      files.value = []
    }

    files.value.push({
      id: file.id,
      name: file.name,
      msg: "等待上传...",
      percentage: 0
    })
    uploader.value.upload()
  })

  /**文件发送前
             *  object {Object}
                data {Object}默认的上传参数，可以扩展此对象来控制上传参数。
                headers {Object}可以扩展此对象来控制上传头部
             */
  uploader.value.on("uploadBeforeSend", (file, data, headers) => {
    data.chunk = file.chunk
    data.chunks = file.chunks
    data.bfid = uuid.value
    data.fileName = fileName.value
    //  data.fid=v_this.projectId;
    //    data.solverType=v_this.solverType;
    //    data.md5=v_this.md5;
    //    data.uploadFlag=2;//1 普通 2覆盖 3续传
    data.channelNo = "service"
    data.clientToken = "e47b87eec69545559d1e81e56626da68"
    data.transCode = "B00028"
    data.userId = "5f06c8bc77234f969d13e160b54c27e3"
    headers.Content = "multipart"
    headers.Type = "form-data"
  })
  // 文件上传过程中创建进度条实时显示。
  uploader.value.on("uploadProgress", (file, percentage) => {
    let prage = Math.floor(percentage * 100)
    files.value.forEach((fileObj) => {
      if ((fileObj.id === file.id)) {
        fileObj.msg = "上传中"
        emit('upload-status', "上传中")
        }
      msg.value = fileObj.msg
      fileObj.percentage = prage
      // 更新进度条
      emit('update-percentage', prage);
      
    })
  })
  uploader.value.on("uploadSuccess", (file, response) => {
    console.log("文件信息：", file)
    console.log("返回值：", response)
    gridFileId.value = response.bfid
    
    let params = {
      transCode: "B00029",
      bfid: response.bfid
    }
    request(params)
      .then((res) => {
        console.log(res)
        files.value.forEach((fileObj) => {
          if (fileObj.id === file.id) {
            fileObj.msg = "已上传"
            emit('upload-status', "上传成功")
            emit("upload-success", {
              bfid: response.bfid,
              fname: file.name,
            })
            uuid.value = getUUID()
            msg.value = fileObj.msg
            runupboolen.value = false
          }
          if (file.ext == "x") {
            gfid.value = response.bfid
            emit("Gassaddgfid", gfid.value)
          } else if (file.ext == "inp") {
            bfid.value = response.bfid
            emit("Gassaddbfid", bfid.value)
          }
        })
      })
      .catch((err) => {})
  })
  //
  /**
             * 当某个文件上传到服务端响应后，会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为false, 则此文件将派送server类型的uploadError事件。
             * object {Object}
                ret {Object}服务端的返回数据，json格式，如果服务端不是json格式，从ret._raw中取数据，自行解析
             */
  uploader.value.on("uploadAccept", (object, res) => {
    if (res.returnCode == "000000000") {
      return true
    } else {
      ElMessage.error(res.returnMsg)
      return false
    }
  })
  uploader.value.on("uploadError", (file, reason) => {
    $("#" + file.id).text(file.name + "上传出错")
    emit('upload-status', "上传失败")
    getUUID()
    uuid.value = getUUID()
  })

  uploader.value.on("uploadComplete", (file) => {
    // $( '#'+file.id ).find('.progress').fadeOut();
  })
}
const uploaderClear = () => {
  uploader.value.reset();
  files.value = [];
  files.value.forEach(file => file.percentage = 0);
};
const fileDel = (fileId) => {
  console.log(fileId)
  getUUID()
  uuid.value = getUUID()
  files.value = files.value.filter((fileObj) => {
    if (fileObj.id == fileId) {
      console.log(fileObj)
      fileObj.name = fileObj.name
      msg.value = ""
      uploader.value.removeFile(fileId)
    }
    return fileObj.id != fileId
  })
}
defineExpose({ gfid, bfid, initWebUploader, files, msg })
</script>
<style>
.webuploader-container {
  position: relative;
}
.webuploader-pick {
  color: #fff !important;
}
.webuploader-element-invisible {
  position: absolute !important;
  clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  clip: rect(1px, 1px, 1px, 1px);
}
.webuploader-pick {
  position: relative;
  display: inline-block;
  cursor: pointer;
  padding: 1px 2px;
  font-size: 12px;
  color: #606266;
  text-align: center;
  border-radius: 3px;
  overflow: hidden;
}
.webuploader-pick-hover {
  background: #00a2d4;
}

.webuploader-pick-disable {
  opacity: 0.6;
  pointer-events: none;
}
.disflex {
  display: flex;
  
}
.text_color .webuploader-pick {
  color: #d5d5d5;
}
/* .el-progress__text {
  color: #d5d5d5 !important;
} */
.disflex .el-col {
  color: #fff;
}
.disflex .el-icon {
  font-size: 20px;
}
.wenjian {
  color: #fff;
  padding-right: 10px;
}
.webuploader-container .el-icon {
  color: #fff;
}

.custom-icon {
  width: 100%;
  height: auto;
  display: block;
}
</style>