<template>
  <div class="upload-container">
    <div class="tips" v-if="!options.disabled">
      请上传小于{{ options.limitSize }}M，格式为{{
        options.accept
      }}格式的图片，最多可上传{{ options.limit }}张
    </div>
    <div class="card-list-box">
      <div v-for="(file, i) in localValue" :key="'upload-BaseImage' + i" class="card-item-box">
        <BaseImage :src="file.address" fit="contain" class="card-img" :code="options.reqParams.code"
          :filePath="filePath" @handleDelete="handleDeleteImg(file, i)"
          @handleSetCover="handleSetCover(file, i)" :isSetCover="cmpOption.isSetCover" :forIndex="i" :onforIndex="onforIndex"/>
        <div v-show="!options.disabled && !cmpOption.isSetCover" title="删除" class="delete-box"
          @click="handleDeleteImg(file, i)">
          <i class="el-icon-close"></i>
        </div>
      </div>
      <div v-for="(file, i) in reactiveData.filesIng" :key="i" class="card-item-box">
        <div v-show="reactiveData.status === 'uploading'" class="uploading-box flex-col-center-center">
          <el-progress v-if="reactiveData.lengthComputable" type="circle" :width="50"
            :percentage="uploadPercentage()" />
          <template v-else>
            <i class="el-icon-loading"></i>
            {{ reactiveData.message }}
          </template>
        </div>
      </div>
      <div style="position: relative;">
        <input style="opacity: 0;position: absolute;" :id="inputtype" ref="fileInput" type="file" :multiple="true"
        @change="handleUploadFile" />
        <div v-if="
            localValue && localValue.length < options.limit && !options.disabled
          " title="点击上传" class="card-action-box" @click="handleUpload">
          <i class="el-icon-plus"></i>
          <span class="card-action-text">点击上传图片</span>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
  //   import { uploadFiles, uploadStraightFile } from '@/api/commonApi/file';
  import {
    miniioupload
  } from '@/api/commodityLease.js'
  import BaseImage from '@/components/BaseImage/index.vue';

  export default {
    components: {
      BaseImage,
    },
    name: 'BaseUpload',
    props: {
      value: {
        type: String,
        default: '',
      },
      cmpOption: {
        type: Object,
        default: () => ({
          disabled: false,
          isSetCover: true,
        }),
      },
      filePath: {
        type: String,
        default: 'other',
      },
      inputtype: {
        type: String,
        default: '',
      },
      limit: {
        type: Number,
        default: 10,
      },
    },
    data() {
      return {
        fileList:[],
        onforIndex:0,
        localValue: [],
        options: {
          limitSize: 10,
          accept: '.bmp,.jpg,.jpeg,.png',
          multiple: false,
          limit: 10,
          disabled: false,
          field: 'files',
          reqParams: {
            code: 2000
          },
        },
        reactiveData: {
          files: [],
          filesIng: [],
          status: 'uploading',
          message: '上传中...',
          total: 0,
          loaded: 0,
          lengthComputable: false,
        },
      };
    },
    watch: {
      limit: {
        handler() {
          this.options.limit= this.limit
        },
        immediate: true,
      },
      cmpOption: {
        handler() {
          this.setOptions();
        },
        immediate: true,
      },
      value: {
        handler(val) {
          if (val && val !='') {
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',')
            // 然后将数组转为对象数组
            this.fileList = list
            this.localValue = list.map(item => {
              if (typeof item === 'string') {
                item = {
                  address: item,
                }
              }
              return item
            })
          } else {
            this.localValue = []
            this.fileList = []
            return []
          }
        },
        immediate: true,
      },
    },
    methods: {
      async handleUploadFile(value) {
        const files = value.target.files
        if (!this.filesCheck(files)) {
          return;
        }
        this.reactiveData.filesIng = new Array(files.length);
        this.reactiveData.lengthComputable = false;
        this.reactiveData.status = 'uploading';
        this.reactiveData.total = 0;
        this.reactiveData.loaded = 0;
        let c1 =  await this.asyncFileUpload(Array.from(files));
        console.error('-----------')
        console.error(this.localValue)
        console.error(c1)
        let list = []
        for (let i = 0; i < c1.length; i++) {
          let info = {
            address:c1[i]
          }
          list.push(info)
        }
        console.error(list)
        this.localValue = [...this.localValue,...list]
        this.reactiveData.filesIng = []
        this.fileList = []
        for (let i = 0; i < this.localValue.length; i++) {
          this.fileList.push(this.localValue[i].address)
        }
        let urlstr = this.fileList.join(',')
        this.$emit('changimg',urlstr)
        
      },
      setOptions() {
        this.options = {
          ...this.options,
          ...this.cmpOption
        };
      },
      uploadPercentage() {
        return parseInt(String(this.reactiveData.loaded / (this.reactiveData.total / 100)));
      },
      handleUpload() {
        const input = document.querySelector('#'+this.inputtype)
        input.click()
      },
      async asyncFileUpload(formDataArray) {
        console.error(formDataArray)
        try {
          // 初始化上传状态
          this.reactiveData.status = 'uploading';
          this.reactiveData.filesIng = formDataArray.map(() => ({
            status: 'pending',
            loaded: 0,
            total: 0
          }));
          this.reactiveData.lengthComputable = false;
          this.reactiveData.total = 0;
          this.reactiveData.loaded = 0;
          let list = []
          // 循环遍历每个文件并进行上传
          for (let i = 0; i < formDataArray.length; i++) {
            const fileData = formDataArray[i];

            // 创建一个新的 FormData 对象
            let fd = new FormData();
            fd.append('file', fileData); // 假设 formData 包含文件
            fd.append('filePath', this.filePath);

            // 更新当前文件的上传状态
            this.reactiveData.filesIng[i].status = 'uploading';

            // 调用 miniioupload 方法并等待响应
            const res = await miniioupload(fd);
            list.push(res.data)
            // 处理成功响应
            this.reactiveData.filesIng[i].status = 'success';
       
          }

          // 所有文件上传完成
          this.reactiveData.status = 'success';
          this.$message.success('文件上传成功');
          console.error(list)
          return list
        } catch (error) {
          // 处理错误
          console.error('上传失败:', error);
          this.reactiveData.status = 'error';
          this.reactiveData.filesIng = formDataArray.map(() => ({
            status: 'error',
            loaded: 0,
            total: 0
          }));
          this.$message.error('上传失败');
          return []
        }
      },
      async handleDeleteImg(file, i) {
        let modelValue_ = this.localValue.filter((value, index) => index != i);
        this.localValue = modelValue_
        this.fileList = []
        for (let i = 0; i < this.localValue.length; i++) {
          this.fileList.push(this.localValue[i].address)
        }
        let urlstr = this.fileList.join(',')
        this.$emit('changimg',urlstr)
      },
      async handleSetCover(file, i) {
        console.error(file, i)
        this.onforIndex = i
      },
      filesCheck(files) {
        const {
          limitSize,
          accept,
          limit
        } = this.options;
        if (this.reactiveData.files.length + files.length > limit) {
          this.$message.error(`最多上传${limit}个文件`);
          return false;
        }
        for (let index = 0; index < files.length; index++) {
          const file = files[index];
          if (!this.checkFileType(file)) {
            this.$message.error(`请上传${accept}等格式`);
            return false;
          }
          if (!this.checkSize(file)) {
            this.$message.error(`文件大小不能超过 ${limitSize}MB!`);
            return false;
          }
        }

        return true;
      },
      checkSize({
        size
      }) {
        return size <= this.options.limitSize * 1024 * 1024;
      },
      checkFileType(file) {
        console.error(file)
        let {
          accept
        } = this.options;
        if (!accept || accept === '*') {
          return true;
        }
        accept = accept.toLowerCase().replace(/\s/g, '');
        const acceptTypeList = accept.split(',');
        const fileType = file.name.match(/\.\w*$/)?.shift() ?? '';
        return acceptTypeList.includes(fileType.toLowerCase());
      },
    },
  };
</script>

<style lang="scss" scoped>
  .upload-container {
    width: 100%;

    .tips {
      color: #0006;
      font: 14px 'Alibaba PuHuiTi 2.0-55 Regular';
      line-height: 38px;
    }

    .action-box {
      cursor: pointer;
      padding-left: 10px;

      .default-action {
        color: #3f9b6a;
      }
    }

    .card-list-box {
      width: 100%;
      display: flex;
      flex-wrap: wrap;

      .card-item-box {
        position: relative;
        width: 112px;
        height: 112px;
        border: 1px dotted #dcdfe6;
        border-radius: 2px;
        overflow: hidden;
        margin: 0 10px 10px 0;

        .delete-box {
          padding: 2px 5px;
          position: absolute;
          right: 0;
          top: 0;
          line-height: normal;
          background-color: #000;
          color: #fff;
          border-radius: 50%;
          transform: translate(40%, -30%);

          .el-icon-close {
            font-size: 12px;
            transform: translate(-30%, 20%);
          }
        }
      }

      .card-action-box {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 112px;
        height: 112px;
        border: 1px dashed #cdd0d6;
        border-radius: 2px;
        overflow: hidden;
        // margin-bottom: 10px;
        background-color: #fafafa;
        cursor: pointer;
        font-size: 12px;
        color: #00000066;

        .el-icon-plus {
          font-size: 20px;
        }

        &:hover {
          border-color: #3f9b6a;
          color: #3f9b6a;
        }
      }
    }

    .text-list-box {
      .text-item-box {
        padding: 0 5px;
        border-radius: 2px;
        overflow: hidden;

        .file-name {
          flex: 1;
        }

        .text-icon {
          flex-shrink: 0;
          padding-right: 10px;
        }

        .el-icon-close {
          cursor: pointer;
          padding-left: 10px;
          flex-shrink: 0;
        }

        &:hover {
          background-color: rgba(63, 155, 106, 0.2);

          .file-name {
            color: #3f9b6a;
          }
        }

        &:nth-child(n + 2) {
          margin-top: 10px;
        }
      }
    }

    .uploading-box {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      color: #fff;
      background-color: #c0c4cc;
    }

    .progress-box {
      width: 100%;
      height: 100%;
      position: relative;

      .el-progress {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
</style>
