<template>
  <div>
    <el-upload
      :disabled="disabledUp"
      :action="uploadFileUrl"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :multiple="false"
      :file-list="fileList"
      :headers="headers"
      :on-success="onSuccess"
      :data="{type:this.type}"
      :limit="maxFiles"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <span class="msg" v-show="isShowTip">最多可上传{{this.maxFiles}}张现场照片,允许上传的文件大小限制{{this.fileSize}}（MB）</span>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import store from "@/store";

export default {
  name: 'localImageUpload',
  props: {
    uploadedFileNames: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: "device",
    },
    // 数量限制
    maxFiles: {
      type: Number,
      default: 3,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 是否显示提示
    disabledUp: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API +  "/udiwms/upload/register/file",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [], // 上传文件列表
      dialogImageUrl: '',
      dialogVisible: false,
      uploadDisabled: false,
      }
    },
  methods:{
    beforeUpload(file) {
      const isJPG = false;
      if (this.fileType.find(type => type === file.type)) {
        return  true;
      }
      const isLt2M = file.size / 1024 / 1024 < this.fileSize;
      if (!isJPG) {
        let extensionsString = this.fileType.join(',');
        this.$message.error('上传图片只能是【 '+extensionsString+' 】格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 ' + this.fileSize + 'MB!');
      }
      return isJPG && isLt2M
    },
    handleExceed(file, fileList) {
      // 文件超出个数限制时的钩子
      this.$message.warning(`最多可上传3张现场照片!`);
    },
    // 上传成功
    onSuccess(response, file, fileList) {
      if (response.code === 20000) {
        fileList[fileList.length - 1].url = this.BASE_URL + "/udiwms/image/register/file/getImage?type="+this.type+ "&name=" + response.data.name
        fileList[fileList.length - 1].upName = response.data.name
        this.updateUploadedFileNames(response.data.name);
        if(fileList.length >=3){ this.uploadDisabled = true; }else {this.uploadDisabled = false;}
      } else {
        this.$message.error(response.msg)
      }
      this.$emit("changeComponent1Data", this.uploadedFileNames)
    },
    // 更新已上传文件名列表
    updateUploadedFileNames(name) {
      if (this.uploadedFileNames) {
        this.uploadedFileNames += ',' + name
      } else {
        this.uploadedFileNames = name
      }
      // 去除首尾可能的逗号
      this.uploadedFileNames = this.uploadedFileNames.trim().replace(/(^,)|(,$)/g, '');
    },
    // 删除图片
    handleRemove(file, fileList) {
      // if (!fileList.some(files => files.upName.includes(file.upName))) return;
      // console.log("fileList1",fileList)
      // console.log("file1",file)
      // console.log("this.uploadedFileNames1",this.uploadedFileNames)
      this.uploadedFileNames = ''
      fileList.map((fileName) => {
        // 清理文件名并去除空格
        this.uploadedFileNames  += ',' + fileName.upName.trim()
        return;
      })
      this.uploadedFileNames = this.uploadedFileNames.trim().replace(/(^,)|(,$)/g, '');
      // console.log("fileList2",fileList)
      // console.log("file2",file)
      // console.log("this.uploadedFileNames2",this.uploadedFileNames)
      //     // 从 uploadedFileNames 中移除文件名
      // const names = this.uploadedFileNames.split(',');
      // names.splice(file.index, 1); // 注意这里的 index 可能与 fileList 不对应，因为 names 是按顺序的
      // this.uploadedFileNames = names.join(',');
      // this.uploadedFileNames = this.uploadedFileNames.trim().replace(/(^,)|(,$)/g, '');
      //
      if (fileList.length >= 3) {
        this.uploadDisabled = true
      } else {
        this.uploadDisabled = false
      }
      this.$emit("changeComponent1Data", this.uploadedFileNames)
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 解析文件名并添加到 fileList 数组中
    parseFileNames() {
      // 分割字符串为文件名数组
      if (this.uploadedFileNames != null && this.uploadedFileNames != '' && this.uploadedFileNames != "null"){
        const fileNames = this.uploadedFileNames.split(',');
        // 遍历文件名数组并创建文件对象
        this.fileList = fileNames.map((fileName) => {
          // 清理文件名并去除空格
          const trimmedFileName = fileName.trim();

          // 创建一个文件对象（这里只是一个简单的示例，您可以根据需要添加更多属性）
          return {
            name: trimmedFileName,
            url: this.BASE_URL + "/udiwms/image/register/file/getImage?type="+this.type+ "&name=" + trimmedFileName,
            // 可以添加其他属性，如 id、size、type 等
            // id: someUniqueIdGenerator(),
            // size: 0,
            // type: 'image/jpeg', // 假设所有都是图片，但可以根据实际情况设置
            // ...
          };
        });
      }
    },
  },
  created() {
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token,
    };
    this.parseFileNames()
  },

}
</script>

<style scoped>

</style>
