!<!-- 上传附件 -->
<template>
  <div class="attachment" :class="disabled?'':'limitWidth'">
    <el-upload
      v-if="!disabled"
      ref="upload"
      :action="$store.state.uploadUrl"
      :headers="$store.state.uploadHeader"
      :data="$store.state.uploadData"
      :show-file-list="false"
      :multiple = "ismultiple"
      :before-upload="beforeUpload"
      :on-progress="uploadProgress"
      :on-success="uploadSuccessful"
			:accept="uploadTypeInfo"
      :limit="maxCount"
      :on-exceed="fileOverLimit"
    >
      <el-button size="small">
        <i class="iconfont icon-icon_upload"></i>上传文件
      </el-button>
      <span slot="tip" class="el-upload__tip">({{uploadTipInfo}})</span>
    </el-upload>
    <div class="attachment_title" v-else-if="disabled&&showTitle">
      <i class="el-icon-paperclip"></i>
      <span>附件（{{fileListFile.length}}）</span>
    </div>
    <ul :class="[disabled?'attachment_list_wrapper':'attachment_lists', 'pre_line_' + perLineNumber]">
      <li class="attachment_list" :class="{'uploadError':item.status==='exception'}" v-for="(item,index) in fileListFile" :key="index">
        <div class="attachment_list_file flex">
          <div class="file_line" @click.stop="preview(fileListFile, index)">
            <img v-if="item.fileType==='pdf'" src="../../images/icon_pdf.png" />
            <img v-else-if="item.fileType==='zip'||item.fileType=='rar'" src="../../images/icon_zip.png" />
            <img v-else-if="item.fileType==='ppt'||item.fileType==='pptx'" src="../../images/icon_ppt.png" />
            <img v-else-if="item.fileType==='doc'||item.fileType==='word'||item.fileType==='txt'||item.fileType==='docx'" src="../../images/icon_word.png" />
            <img v-else-if="item.fileType==='xlsx'||item.fileType==='xls'||item.fileType==='excel'" src="../../images/icon_excel.png" />
            <img v-else-if="item.fileType==='png'||item.fileType==='jpg'||item.fileType==='jpeg'||item.fileType==='jfif'" src="../../images/icon_pngjpg.png" />
            <img v-else src="../../images/icon_common.png" />
            <div class="file_info">
              <p>{{item.fileName}}</p>
              <p v-if="disabled">{{Math.floor(item.fileSize/1024)}}kb</p>
            </div>
          </div>
          <div class="btn">
            <i class="iconfont icon-icon_viewpicture_download" v-if="item.id&&isDownload" @click="downLoadFile(item)"></i>
            <i class="iconfont icon-icon_annex_delet1" v-if="item.id&&!disabled" @click="deleteFile(index)"></i>
          </div>
        </div>
        <el-progress class="progress" :percentage="item.percentage||0" :show-text="false" :status="item.status" v-if="item.loading"></el-progress>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'enoAttachment',
  data() {
    return {
      filesId: [],
      limitCount: 0,
      fileListFile:[]
    }
  },
  props: {
    disabled: Boolean,
    value: String,
    files: [Array, String],
    showTitle: {
      type: Boolean,
      default: true,
    },
    isDownload: {
      type: Boolean,
      default: true,
    },
    ismultiple: {
      type: Boolean,
      default: false,
    },
    perLineNumber: {
      type: Number,
      default: 4,
    },
	uploadType: {
		type: String,
		default: ''
	},
	uploadTip: {
		type: String,
		default: '文件大小需要小于20M'
	},
    url:{
      type: String,
      default: 'platform.downloadFIleOne'
    },
    controlData: {
      type: Object
    },
    limitMaxSize: {
      type: [Number,String],
      default: 20
    },
    limitMinSize: {
      type: [Number,String],
      default: 0
    }
  },
  components: {},
  computed: {
    // fileListFile() {
    //   if (!this.files) {
    //     this.$emit('update:files', [])
    //     return []
    //   }
    //   if (typeof this.files === 'string') {
				// this.$emit('update:files', JSON.parse(this.files))
    //     return JSON.parse(this.files)
    //   } else {
    //     return this.files
    //   }
    // },
    uploadTipInfo(){
      let data;
      if(this.controlData&&Object.keys(this.controlData).length&&this.controlData.maxValue){
        data = `文件大小需要小于${this.controlData.maxValue}M`
      } else {
        data = this.uploadTip
      }
      return data;
    },
    uploadTypeInfo(){
      let data;
      if(this.controlData&&Object.keys(this.controlData).length&&this.controlData.fileType){
        data = this.controlData.fileType
      } else {
        data = this.uploadType
      }
      return data;
    },
    maxCount() {
      let count = this.controlData&&Object.keys(this.controlData).length ? Number(this.controlData.attachmentNumber) : 2000000;
      this.limitCount = count;
      return count
    }
  },
  watch: {
    fileListFile(val){
      // debugger
    },
    files(val){
      if (typeof val === 'string') {
        this.fileListFile = JSON.parse(val)
      	this.$emit('update:files', JSON.parse(val))

      } else {
        this.fileListFile = val
      }
    }
  },

  created() {

  },
  methods: {
	preview(attachmentList, index){
      attachmentList.forEach((file)=>{
        file.name = file.fileName
      })
			this.$eno.preview(this, attachmentList, index,this.url)
	},
    downLoadFile(item) {
      this.$eno.downFileUrl(this, item.id);
      // this.$eno.downLoadFile(item, item.fileType, item.fileName)
    },

    deleteFile(index) {
      this.fileListFile.splice(index, 1)
      this.$emit('update:files', this.fileListFile)
      this.$refs.upload.$data.uploadFiles.splice(index, 1)
    },

    beforeUpload(file) {
      // 不能上传可执行文件
      let fileType = file.name.split('.').pop().toLowerCase();
      if (['bat', 'exe', 'sys', 'com', 'dll'].includes(fileType)) {
        this.$message.error('上传格式有误');
        return false
      }
      if(this.controlData&&Object.keys(this.controlData).length&&this.controlData.fileType){
        if(this.controlData.fileType.indexOf(fileType) == -1){
          this.$message.error('上传格式有误');
          return false
        }
      }
      // 附件大小校验
      if(this.controlData&&Object.keys(this.controlData).length&&(this.controlData.minValue||this.controlData.maxValue)){
        if (!this.$eno.checkFileSize(this, file.size, this.controlData.minValue, '', this.controlData.maxValue)) {
          return false
        }
      } else {
        if (!this.$eno.checkFileSize(this, file.size, this.limitMinSize, '', this.limitMaxSize)) {
          return false
        }
      }
      // 附件数量校验
      let allFile = this.$eno.deepClone(this.fileListFile);
      allFile.push({fileName:file.name});
      if(this.controlData&&Object.keys(this.controlData).length&&allFile.length>Number(this.controlData.attachmentNumber)){
        this.$message.error(`上传的附件数量不能超过配置数量${this.controlData.attachmentNumber}`)
        return false
      }

			this.fileListFile.push({
				fileName: file.name,
				fileSize: file.size,
				percentage: file.percentage,
				status: 'success',
				loading: true,
				fileType: file.name.split('.').pop().toLowerCase(),
			})
      return true
    },
    fileOverLimit() {
      this.$message({ type: 'error', message: `最多可上传${this.limitCount}个文件` });
      return false;
    },
    uploadProgress(event, file, fileList) {
      this.fileListFile.forEach((val) => {
        if (file.name === val.fileName) {
          val.percentage = file.percentage
        }
      })
    },

    uploadSuccessful(response, file) {
      if(response.code == '200'){
        this.fileListFile.forEach((val) => {
          if (file.name === val.fileName) {
            val.status =
              file.response && file.response.code !== '200'
                ? 'exception'
                : 'success'

            val.id =
              file.response && file.response.code === '200'
                ? file.response.data
                : ''

            val.loading = false

            this.filesId.push(val.id)
          }
        })
        this.$message.success('上传成功')
        this.$emit('input', this.filesId.join(','))
        this.$emit('update:files', this.fileListFile)
      } else {
        this.fileListFile.splice(this.fileListFile.length-1,1)
        this.$message.error(response.data)
      }
    },
  },
}
</script>

<style scoped lang='less'>
  .attachment {
    width: calc(100% - 40px);
    &.limitWidth {
      max-width: 300px;
    }
    .el-upload__tip {
      color: @textThirdColor;
      padding-left: 20px;
    }

    .attachment_title {
      color: #878787;
      padding-bottom: 12px;
      span {
        padding-left: 6px;
      }
    }

    .attachment_lists {
      margin-top: 20px;
      .attachment_list {
        height: 40px;
        border: 1px solid #ebebeb;
        padding: 0 4px 0 8px;
        margin-bottom: 8px;
        position: relative;
        .attachment_list_file {
          width: 100%;
          height: 100%;

          .file_line {
            display: flex;
            align-items: center;
						line-height: 20px;
            img {
              display: inline-block;
              width: 40px;
              height: 40px;
            }
            p {
              max-width: 150px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              padding-top: 4px;
            }
          }
          .btn {
            i {
              cursor: pointer;
            }
          }
        }
        &.uploadError {
          border-color: @wrongColor;
          color: @wrongColor;
        }

        .progress {
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          z-index: 2;

          /deep/.el-progress-bar {
            width: 100%;
            height: 100%;

            .el-progress-bar__outer {
              height: 100% !important;
              border-radius: 0;
              opacity: 0.3;

              .el-progress-bar__inner {
                border-radius: 0;
                background-color: rgba(72, 128, 255,.5);
              }
            }
          }
        }
      }

      .icon-icon_viewpicture_download,
      .icon-icon_annex_delet1 {
        font-size: 16px;
        cursor: pointer;
      }
      .icon-icon_viewpicture_download{
        margin-right: 6px;
      }
    }
    .pre_line_1 {
      grid-template-columns: repeat(1, 50%);
    }

    .pre_line_2 {
      grid-template-columns: repeat(2, 50%);
    }

    .pre_line_3 {
      grid-template-columns: repeat(3, 33%);
    }

    .pre_line_4 {
      grid-template-columns: repeat(4, 25%);
    }

    .attachment_list_wrapper {
      display: grid;
      grid-gap: 13px 13px;
      .attachment_list {
        cursor: pointer;
        padding: 12px;
        background-color: #f2f2f2;
        .file_line {
          display: flex;
          align-items: center;
          width: calc(100% - 30px);
		      line-height: 20px;
          img {
            display: inline-block;
            width: 40px;
            height: 40px;
          }
          .file_info {
            width: calc(100% - 40px);
            p {
              padding-left: 10px;
              max-width: 100%;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              &:nth-last-of-type(1) {
                font-size: 12px;
                color: #575757;
              }
            }
          }
        }
        .icon-icon_viewpicture_download {
          color: #878787;
        }
      }
    }

    .icon-icon_excel1 {
      color: #66c239;
    }

    .icon-icon_pdf {
      color: #e6a23c;
    }

    .icon-icon_ppt1 {
      color: #fa5555;
    }

    .icon-icon_word1 {
      color: #4e8ed7;
    }

    .icon-icon_common1 {
      color: #828282;
    }
  }
</style>
