<template>
  <div style="text-align: center;">
    <div class="demo-upload-list" v-for="item in uploadList" style="text-align: center;width:157px;height: 220px">
      <img :src="item.url">
      <div class="demo-upload-list-cover">
        <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
        <Icon type="ios-trash-outline" @click.native="handleRemove(item)" v-if="'view'!=flag"></Icon>
      </div>
    </div>
    <Upload
      ref="upload"
      :show-upload-list="false"
      :default-file-list="uploadList"
      :on-success="handleSuccess"
      :format="['jpg','jpeg','png']"
      :max-size="maxSize"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      :multiple="false"
      type="drag"
      action="/"
      style="display: inline-block;width:58px;margin-top:100px;">
      <div style="width: 58px;height:58px;line-height: 58px;" v-if="'view'!=flag">
        <Icon type="ios-cloud-upload" size="20"></Icon>
      </div>
    </Upload>
    <Modal title="查看大图" v-model="visible" :footerHide="true">
      <img :src="viewImage" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>

<script>

  import userImage from '../../assets/images/user.png';
  import config from '@/config'

  const systemPrefix = config.deploymentStandAlone?'':'cas/'

  let _this;
  export default {
    name: 'bcUploadImage',
    props: {
      flag:{
        type: String,
        default: ''
      },
      maxFiles: {
        type: Number,
        default: 1
      },
      maxSize: {
        type: Number,
        default: 2048
      },
      defaultFileList: {
        type: Array,
        default: function(){
          return null
        }
      }
    },
    data() {
      return {
        viewImage: '',
        imgName: '',
        visible: false,
        uploadList: [{'name': 'user','url': userImage}]
      }
    },
    methods: {
      handleView (file) {
        this.imgName = file.name;
        this.visible = true;
        this.viewImage = file.url;
      },
      handleRemove (file) {
        let fileIndex = this.uploadList.indexOf(file);
        this.uploadList.splice(fileIndex, 1);
        this.$emit("uploadImageCallback", this.uploadList);
      },
      handleSuccess (res, file) {
        file.url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1600752966821&di=655dee0120e12667e5dd660926d60343&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F36%2F48%2F19300001357258133412489354717.jpg';
        file.name = '7eb99afb9d5f317c912f08b5212fd69a';
      },
      handleFormatError (file) {
        this.$Notice.warning({
          title: '文件格式错误',
          desc: '文件' + file.name + '的格式错误, 请选择正确的图片格式.'
        });
      },
      handleMaxSize (file) {
        this.$Notice.warning({
          title: '文件格式错误',
          desc: '文件' + file.name + '文件太大, 不要超过2M.'
        });
      },
      handleBeforeUpload (file) {
        let imageName = file.name;

        if(!(imageName.toUpperCase().indexOf(".JPG")>-1||imageName.toUpperCase().indexOf(".PNG")>-1)){
          this.$Notice.warning({
            title: '只能上传jpg、png格式的图片'
          });
          return false;
        }

        let fileSize = file.size;
        let fileRealSize = 0;
        if(fileSize){
          fileRealSize = fileSize/1024;//KB
        }
        if(fileRealSize>this.maxSize){
          this.$Notice.warning({
            title: '文件大小不能超过'+(this.maxSize/1024)+'MB'
          });
          return false;
        }
        const nocheck = (this.maxFiles>1)&&(this.uploadList.length >= this.maxFiles);
        if (nocheck) {
          this.$Notice.warning({
            title: '只能上传'+this.maxFiles+'个文件'
          });
          return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file)
        reader.onload = e => {
          let _file = e.target.result
          let base = _file.split(",")[1]
          let params = {
            base64: base,
            fileName:file.name
          }
          this.$post('/api/v1/attach/base64',params).then(response=>{
            if(response.status&&response.result.id){
              this.$Message.success("文件上传成功!")
              let fileId = response.result.id;
              let fileName = response.result.newName;

              if(this.maxFiles>1){
                this.uploadList.push(
                  {fileId: fileId, name: fileName, url: systemPrefix+'api/v1/attach/download/'+fileId+'/?access_token='+this.$getToken()}
                );
              }else{
                this.uploadList = [
                  {fileId: fileId, name: fileName, url: systemPrefix+'api/v1/attach/download/'+fileId+'/?access_token='+this.$getToken()}
                ];
              }
              this.$emit("uploadImageCallback", this.uploadList);
            }else{
              this.$Message.error('文件上传失败！')
            }
          }).catch(err=>{
            this.$Message.error('文件上传失败<br>错误信息：'+err)
          });
        }

        return nocheck;
      }
    }, mounted: function () {
      _this = this;
    }, watch: {
      defaultFileList: {
        immediate: true,
        handler: function () {
          if(this.defaultFileList&&this.defaultFileList.length>0){
            this.uploadList = [];
            this.defaultFileList.forEach(f=>{
              this.uploadList.push({fileId: f.fileId, name: '', url: systemPrefix+'api/v1/attach/download/'+f.fileId+'/?access_token='+this.$getToken()});
            });
          }else{
            this.uploadList = [{'name': 'user','url': userImage}];
          }
        }
      }
    }
  }
</script>

<style scoped>
  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
