<template>
  <div>
    <el-upload
      ref="upload"
      :action="imgAction"
      :headers="headers"
      :file-list="fileList"
      :before-upload="imgBeforeUpload"
      list-type="picture-card"
      :on-preview="handlePreview"
      :on-change="handleChange"
      :limit="limit"
      :auto-upload="true"
      :on-remove="handelDelete"
      :on-error="handleError"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip">
        <!-- 最多可上传{{ limit }}个文件，文件请选用jpg,png格式 -->
        请选用png,jpg,jpeg格式
      </div>
    </el-upload>
    <el-image-viewer
      v-if="imageVisible"
      :on-close="closeViewer"
      :url-list="[dialogImageUrl]"
      z-index="5000"
    />
  </div>
</template>

<script>
// import { getToken } from "@/utils/auth";
import {mapGetters} from "vuex";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import emitter from 'element-ui/src/mixins/emitter';

export default {
  name: "MultiUpload",
  components: { ElImageViewer },
  model: {
    prop: "value",
  },
  mixins: [emitter],
  props: {
    //配合v-model 加载初始值
    value: {
      type: Array,
      default: () => [],
    },
    limit: Number,
    fileName: String,
    serverAddr: String,
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg'],
    },
  },
  computed:{
      ...mapGetters(['token'])
  },
  data() {
    return {
      fileList: [],
      filePath: "",
      imageVisible: false,
      dialogImageUrl: "",
      // imgAction: "/upload",//本地
      imgAction: process.env.VUE_APP_BASE_API + "/upload",
      progressPercent: 0,
      imageType: "",
      minSize: 1 * 1024,
      maxSize: 50 * 1024 * 1024,
      minSizeTip: "1KB",
      maxSizeTip: "50MB",
    };
  },
  computed: {
    ...mapGetters(['token']),
    headers() {
      return { Authorization: "Bearer " + this.token };
    },
  },
  created() {
    // console.log('this.value',this.value)
    if(this.value&&this.value.length>0){
      let imglist=[]
      imglist.push(this.value[0])
      this.setFileList(imglist);
      // this.setFileList(this.value.splice(0,1));
    }
    // console.log('this.value',this.value,this.value[0],this.value.splice(0,1))
    
    // if(this.value&&this.value.length>0){
    //   console.log('11111')
    //   let imglist=[]
    //   imglist.push(this.value[0])
    //   this.setFileList(imglist);
    
    // }else{
    //   console.log('2222',this.setFileList(this.value.splice(0,1)))
      this.setFileList(this.value);
    // }
    // console.log('上传地址process.env.VUE_APP_BASE_API + ',process.env.VUE_APP_BASE_API)
  },
  // //监听父组件值是否在变化
  // watch: {
  //   //有些页面初始初始src没有赋值
  //   value(newValue, oldValue) {
  //     this.setFileList(newValue);
  //   },
  // },
  methods: {
    // 效验方法
    imgBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(`请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }

      let isAccept = true;
      let isRightSize = file.size <= this.maxSize;
      if (!isRightSize) {
        this.$message.error("文件大小不能超过" + this.maxSizeTip);
        return false;
      }
      isRightSize = file.size >= this.minSize;
      if (!isRightSize) {
        this.$message.error("文件大小不能小于" + this.minSizeTip);
        return false;
      }
      return isRightSize && isAccept;
    },
    // 文件上传时
    handlePreview(file) {
      this.imageVisible = true;
      this.dialogImageUrl = file.url;
    },
    // 关闭放大查看
    closeViewer() {
      this.imageVisible = false;
    },
    // 删除时方法
    handelDelete(file, fileList) {
      //imgBeforeUpload校验失败会触发此方法
      if (file && file.status === "success") {
        this.$emit("input", this.file2Path(fileList));
        // this.$emit("blur", this.file2Path(fileList));
        // this.$emit("change", this.file2Path(fileList), this.fileList);
        this.dispatch('ElFormItem', 'el.form.change', this.file2Path(fileList));

        //filePath start
        this.filePath = "";
        for (let file in fileList) {
          this.filePath += "," + fileList[file].filePath;
        }
        if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
          this.filePath = this.filePath.substr(1, this.filePath.length);
        this.$emit("setImgPath", this.filePath);
        //filePath end
      }
    },
    // 上传成功
    handleSuccess(response, file) {
      // console.log('上传成功',response)
      file.percentage = 100;
      file.filePath = response.filePath;

      this.value.push(file.filePath);
      // this.$emit("input", this.file2Path(this.fileList));//TODO why not work???
      this.dispatch('ElFormItem', 'el.form.change', this.file2Path(this.value));

      //filePath start
      this.filePath += "," + response.filePath;
      if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
        this.filePath = this.filePath.substr(1, this.filePath.length);
        console.log('this.filePath',this.filePath)
      this.$emit("setImgPath", this.filePath);
      //filePath end
    },
    //上传失败
    handleError() {
      this.$message.error("文件上传失败，请重新上传或联系管理员");
    },
    // 文件超出个数限制
    handleExceed() {
      this.$message.error("最多只能上传" + this.limit + "个文件");
    },
    handleChange() {},

    //通过父组件传过来的value更新子组件
    setFileList(stringList) {
      console.log('stringList--',stringList)
      
      let detailFile = [];
      if (stringList && stringList.length > 0) {
        let imglist=[]
          imglist.push(stringList[0])
        for (let index in imglist) {
          detailFile.push({
            name: this.fileName,
            url: this.serverAddr + imglist[index],
            filePath: imglist[index],
          });
        }
      }
      this.fileList = detailFile;

      //filePath start
      for (let file in this.fileList) {
        this.filePath += "," + this.fileList[file].filePath;
      }
      if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
        this.filePath = this.filePath.substr(1, this.filePath.length);
      this.$emit("setImgPath", this.filePath);
      //filePath end
    },
    fileList2PathStrList(fList, strList) {
      strList.length = 0;
      if (fList && fList.length > 0) {
        for (let index in fList) {
          strList.push(fList[index].filePath);
        }
      }
    },
    file2Path(fList) {
      let strList = [];
      if (fList && fList.length > 0) {
        for (let index in fList) {
          strList.push(fList[index].filePath);
        }
      }
      return strList;
    },
    reset() {
      this.fileList = [];
      this.filePath = '';
    }
  }
};
</script>

<style scoped>
</style>
