<template>
  <div class="uploadpic">
      <el-upload
        ref="upload"
        :action="imgAction"
        :headers="headers"
        :file-list="fileList"
        :before-upload="imgBeforeUpload"
        :list-type="listtype"
        :on-preview="handlePreview"
        :limit="limit"
        :class="objClass"
        :auto-upload="true"
        :on-remove="handelDelete"
        :on-error="handleError"
        :on-success="handleSuccess"
        :on-exceed="handleExceed"
      >
        <el-button  v-if="fileName=='步骤照片' || fileName=='文档' || fileName=='附件上传' " size="small" type="primary">点击上传</el-button>
        <!-- <el-button  v-if="fileName=='步骤照片' || fileName=='文档'" size="small" type="primary">导入模板</el-button> -->
        <div v-else > 
          <i slot="default" class="el-icon-plus"></i>
          <!--class="picetucard" <div slot="tip" class="el-upload__tip">点击上传
            最多可上传{{ limit }}个文件，文件请选用jpg,png格式
            请选用png,jpg,jpeg格式
          </div> -->
        </div>
    </el-upload>
   
    <div v-if="imageVisible&& fileName!='文档'"> 
      <div v-if="fileName!='附件上传'">
        <el-image-viewer  :on-close="closeViewer" :url-list="[dialogImageUrl]" z-index="5000" />
      </div>
    </div>
   
  </div>
</template>

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

export default {
  // name: "MultiUpload",
  components: { ElImageViewer },
  model: {
    prop: "value",
  },
  props: {
    //配合v-model 加载初始值
    value: {
      type: Array,
      default: () => [],
    },
    limit: Number,
    fileName: String,
    serverAddr: String,
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg'],
    },
  },
  data() {
    return {
      objClass: {
					upLoadShow: true,
					upLoadHide: false,
          wendangHide:false
				},
      fileList: [],
      filePath: "",
      imageVisible: false,
      dialogImageUrl: "",
      imgAction: process.env.VUE_APP_BASE_API + "/upload",
      progressPercent: 0,
      imageType: "",
      minSize: 1 * 1024,
      maxSize: 50 * 1024 * 1024,
      minSizeTip: "1KB",
      maxSizeTip: "50MB",
      listtype:'',
    };
  },
  computed: {
    ...mapGetters(['token']),
    headers() {
      return { Authorization: "Bearer " + this.token };
    },
  },
    //监听父组件值是否在变化
  watch: {
    //有些页面初始初始src没有赋值&& newValue.length==0
    
    value(newValue, oldValue) {
      // console.log('新的数据--',newValue,)
      if(this.fileName=='附件上传'){

        this.setFileList(newValue);
      }
      if(this.value.length==0 || this.value.length==1){
          // this.setFileList(this.value);
          this.objClass.upLoadHide = false;//上传图片后置upLoadHide为真，隐藏上传框
          this.objClass.upLoadShow = true;
      }
      if(this.value.length==1){
          // this.setFileList(this.value);
          this.objClass.upLoadHide = true;//上传图片后置upLoadHide为真，隐藏上传框
          this.objClass.upLoadShow = false;
       
      }
    },
  },
  created() {
    // console.log('附件上传---',this.fileName)
    // console.log('this.value---',this.value)
    // console.log('this.valuddlimitd--',this.limit)
    // console.log('this.valudddde-d--文档===',this.value)
    if(this.value&&this.value.length>0){
      if(this.fileName=='文档'){
        // this.value=[{url:this.value[0],name:'文档'}];
        this.value=[{url:this.value[0].url,name:'附件'}];
      }
      // console.log('this.value---',this.value)
      if(this.value.length>1&&this.value[0]){
        this.value.splice(1,1)
      }
      this.setFileList(this.value);
      // console.log('this.value---',this.value)
    }else{
      this.setFileList(this.value);
      // console.log('this.value---',this.value)
    }
    if((this.fileName=='用户头像' || this.fileName=='组织标识')){
      if(this.value&&this.value.length>0){
        this.objClass.upLoadHide = true;//上传图片后置upLoadHide为真，隐藏上传框
        this.objClass.upLoadShow = false;
      }
    }
    if((this.fileName!='用户头像' || this.fileName!='组织标识')){
      if(this.value&&this.value.length>0){
        this.objClass.upLoadHide = true;//上传图片后置upLoadHide为真，隐藏上传框
        this.objClass.upLoadShow = false;
      }
    }
    if(this.fileName=='文档' || this.fileName=='步骤照片' ){
      this.objClass.wendangHide = true;
    }
    // console.log('父组件传过来的地址数据----',this.value)
    if(this.fileName=='步骤照片' || this.fileName=="文档" || this.fileName=="附件上传"){
      this.listtype='text' 
    }else{
      this.listtype='picture-card'
    }
    // console.log('上传地址process.env.VUE_APP_BASE_API + ',process.env.VUE_APP_BASE_API)
  },

  mounted(){
    // console.log('this.fileName',this.fileName)
  },
  methods: {
    // 效验方法
    imgBeforeUpload(file) {
      // 校检文件类型
      // console.log('this.fileType',this.fileType)
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        // console.log('照片文件的后缀---',fileExtension)
        // 判断后缀是否在this.fileType里面
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        // 不在this.fileType里面提示 
        if (!isTypeOk) {
          this.$message.warning(`请上传${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;
    },
       // 上传成功
    handleSuccess(response, file) {
      // console.log('上传成功---',)
      // console.log('上传成功---===',response,file)
      file.percentage = 100;
      file.filePath = response.filePath;
      // console.log('file.filePath---',this.value,file.filePath)
      this.value.push(file.filePath);
      this.filePath=file.filePath
      // let filename=response.data[0].name;
      // let filedoculist=[{url:this.filePath,name:filename}];
      let filelisr=[];
      filelisr.push(this.filePath)
      // console.log('wendang---',filedoculist)
      //filePath start
      // this.filePath += "," + response.data[0];
      // if (this.filePath.length > 0 && this.filePath.indexOf(",") == 0)
      // this.filePath = this.filePath.substr(1, this.filePath.length);
      // console.log('setImgPath---',this.filePath)
      // if(this.fileName=="附件上传"){
      //   let valuedata=[{url:this.filePath,name:'附件'}];
      //   this.$emit("setImgPath", valuedata);
      // }else{
        
      // }
      this.$emit("setImgPath", this.filePath);
      // if(this.fileName!='文档'){
      //   this.$emit("setImgPath", filelisr);
      // }else{
      //   this.$emit("setImgPath", filedoculist);
      // }
      this.objClass.upLoadHide = true;//上传图片后置upLoadHide为真，隐藏上传框
			this.objClass.upLoadShow = false;
      //filePath end
    },
    // 关闭放大查看
    closeViewer() {
      this.imageVisible = false;
    },
    // 删除时方法
    handelDelete(file, fileList) {
      // console.log('file---fileList',file,fileList)
      // imgBeforeUpload校验失败会触发此方法
      if (file && file.status === "success") {
        this.filePath = "";
        // console.log('删除1',this.filePath)
        this.$emit("setImgPath",this.filePath);
        //filePath start
        this.filePath = "";
        if(fileList.length>0){
          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);
            // console.log('删除2',this.filePath)
            this.$emit("setImgPath",this.filePath);
        }else{
          this.value=[]
          // this.$emit("setImgPath", this.filePath);
        }
        // filePath end
      }
      // console.log('e.filePath--===--=',this.filePath)
      this.objClass.upLoadShow = true;//删除图片后显示上传框
			this.objClass.upLoadHide = false;
    },
 
    //上传失败
    handleError() {
      this.$message.error("文件上传失败，请重新上传或联系管理员");
    },
    // 文件超出个数限制
    handleExceed() {
      this.$message.error("最多只能上传" + this.limit + "个文件");
    },
    //通过父组件传过来的value更新子组件
    setFileList(stringList) {
      // console.log('通过父组件传过来的value更新子组件1---',stringList)
      if(this.fileName!='文档'){
          let detailFile = [];
          if (stringList && stringList.length > 0) {
            for (let index in stringList) {
              detailFile.push({
                // name: this.fileName,
                // url: this.serverAddr + stringList[index],
                // filePath: stringList[index],
                url: stringList[index],
              });
            }
          }
          this.fileList = detailFile;
          // console.log('编辑时的地址---', this.fileList)
          //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);
          if(this.fileList.length>0){
            this.filePath=this.fileList[0].filePath
            this.$emit("setImgPath", this.filePath);
          }
      }else{
          this.fileList=[];
          let detailFile = [];
          if (stringList && stringList.length > 0) {
            stringList.forEach(item=>{
              this.fileList.push({name:item.name,url:item.url})
            })
            // for (let index in stringList) {
            //   detailFile.push({
            //     name: stringList[index].name,
            //     url: stringList[index].url,
            //   });
            // }
          }
          // this.fileList = detailFile;
          // console.log('编辑时的地址=---',detailFile, this.fileList)
          if(this.fileList.length>0){
            // this.filePath=this.fileList[0].filePath
            this.$emit("setImgPath", this.fileList);
          }
      }
    },
    reset() {
      this.fileList = [];
      this.filePath = '';
    }
  }
};
</script>

<style scoped>
  .uploadpic>>>.el-upload--picture-card{
    background-color:transparent;
    border:1px dashed #34b2ed
  }
  .uploadpic>>>.el-upload--picture-card i{
        color: #34b2ed
  }
  .el-upload__tip{
    color: #34b2ed
  }
  .uploadpic>>>.el-upload-list__item-name{
    color: #34b2ed;
    /* width:135px; */
    width:80px;
  }
  .uploadpic>>>.el-upload-list{
    /* width: 200px; */
    width:80px;
    /* margin-left:20px; */
  }
  .uploadpic>>>.el-button{
        background:#0066EB;
        color:#FFFFFF;
        /* width:40px; */
        height:33px;
        /* line-height:30px; */
        text-align: center;
        font-size:15px;
        border-radius:3px;
        border:1px solid transparent;
    }
  .picetucard{
    border:1px dashed #34b2ed;
    width: 148px;
    height: 148px;
    line-height: 146px;
    text-align:center;
    border-radius:6px;
  }
  .picetucard i{
        color: #34b2ed;
        width:28px;
        height:28px;
  }
  .uploadpic>>>.el-upload-list__item-name [class^=el-icon]{
    color: #34b2ed;
  }
  /*当upLoadShow为true时，启用如下样式，即上传框的样式，若为false则不启用该样式*/
    .uploadpic>>>.upLoadShow .el-upload {
      /* width: 148px;
      height: 148px;
      line-height: 146px; */
    }

     /*当upLoadHide为true时，启用如下样式，即缩略图的样式，若为false则不启用该样式*/
    .uploadpic>>>.upLoadHide .el-upload-list--picture-card .el-upload-list__item {
      width: 148px;
      height: 148px;
      line-height: 146px;
    }
     /*当upLoadHide为true时，启用如下样式，即上传框的样式，若为false则不启用该样式*/
    .uploadpic>>>.upLoadHide .el-upload {
      display: none;
    }
    
    .uploadpic>>>.wendangHide .el-upload {
      width: 148px;
      height:33px;
      line-height:33px;
    }
    .uploadpic>>>.el-progress__text{
      color: #67C23A
    }
    /* .uploadpic>>>.el-upload .el-upload--text{
      height: 50px;
      line-height: 1px;
    } */
</style>
