<!-- 上传组件 -->
<template>
  <div class="oa-upload-com">
    <template v-if="placement !== 'bottom'&&showFlag!=='1'&&showFlag!=='2'&&showFlag!=='3'&&showFlag!=='004'">
      <ul class="oa-upload-img" v-if="imgDataList && imgDataList.length>0&&showFlag!=='001'">
        <li v-for="(item, index) in imgDataList" :key="'img_' + index">
          <img :src="$store.state.imgBaseUrl + item.name" :alt="item.filename">
          <div class="oa-upload-img-bg" @click="showImg(item)"></div>
          <span class="st-icons st-icons-deleter oa-upload-img-del" @click.stop="delImg(index)"></span>
        </li>
      </ul>
      <ul class="oa-upload-file" v-if="imgDataList && imgDataList.length>0&&showFlag==='001'">
        <li v-for="(item, index) in imgDataList" :key="'img_' + index" class="st-ellipsis">
          <a target="_blank" :href="$store.state.fileBaseUrl + item.name">{{ item.filename }}</a>
          <img style="height: 30px;width: 30px;position: absolute;top:10px;left: 20px;"
               :src="$store.state.imgBaseUrl + item.name" class="ivu-table-ellipsis" :alt="item.filename" @click="showImg(item)">
          <span class="st-icons st-icons-x2" @click="delImg(index)"></span>
        </li>
      </ul>
      <ul class="oa-upload-file" v-if="fileDataList && fileDataList.length>0">
        <li v-for="(item, index) in fileDataList" :key="'file_' + index" class="st-ellipsis"
            :class="{'oa-upload-no-border': fileListBorder }">
          <a target="_blank" :href="$store.state.fileBaseUrl + item.name">{{ item.filename }}</a>
          <span class="st-icons st-icons-file"></span>
          <span class="st-icons st-icons-x2" @click="delFile(index)"></span>
        </li>
      </ul>
    </template>
    <template v-if="placement !== 'bottom'&&showFlag==='1'&&showFlag!=='004'">
      <ul v-if="imgDataList && imgDataList.length>0&&showFlag!=='3'">
        <div class="email-get-heightShowb" v-for="(item, index) in imgDataList" :key="'img_' + index">
          <span class="st-icons st-icons-file2 email-get-positionShowa"></span>
          <p class="email-get-positionShowb">{{item.filename}}</p>
          <p class="email-get-positionShowb"><a @click="delImg(index)">删除</a></p>
        </div>
      </ul>
      <ul v-if="fileDataList && fileDataList.length>0" style="padding-bottom: 10px;">
        <div class="email-get-heightShowb" v-for="(item, index) in fileDataList" :key="'file_' + index">
          <span class="st-icons st-icons-file2 email-get-positionShowa"></span>
          <p class="email-get-positionShowb">{{item.filename}}</p>
          <p class="email-get-positionShowb"><a @click="delFile(index)">删除</a></p>
        </div>
      </ul>
    </template>
    <div v-if="showFlag!=='3'&&showFlag!=='004'">
      <Upload
        ref="upload"
        :action="$store.state.fileUploadUrl"
        :on-success="fileUploadSuccess"
        :on-error="fileUploadError"
        :max-size="1024 * 500"
        :on-exceeded-size="fileUploadMaxSize"
        :show-upload-list="false"
        :default-file-list="defaultList"
        :before-upload="fileUploadBefore"
        :with-credentials="true"
        style="line-height: normal; cursor: pointer;">
        <span style="display: inline-block; overflow: hidden;">
          <span class="st-icons st-icons-upload" title="上传附件" style="float:left;"></span>
          <span style="float:left; display: inline-block; height: 18px; color: #555; margin-left: 4px;">上传附件</span>
        </span>
      </Upload>
      <ul class="oa-upload-upled" v-if="uploadingList && uploadingList.length>0">
        <li class="" v-for="(item, index) in uploadingList" :key="'upli_'+index">
          <p>{{item.name}}</p>
          <Progress :percent="item.percentage" :stroke-width="5"></Progress>
        </li>
      </ul>
    </div>
    <div v-if="showFlag==='3'&&thisImageFile.name===undefined">
      <Upload
        ref="upload"
        :action="$store.state.fileUploadUrl"
        :on-success="fileUploadSuccess"
        :on-error="fileUploadError"
        :max-size="1024 * 500"
        :format="['jpg','jpeg','png']"
        :on-exceeded-size="fileUploadMaxSize"
        :show-upload-list="false"
        :default-file-list="defaultList"
        :before-upload="fileUploadBefore"
        :with-credentials="true"
        style="line-height: normal; cursor: pointer;">
         <span v-if="showFlag2!=='4'" class="st-icon-config st-config-nonePicture" style="position: relative;">
              <span style="position: absolute;top:80px;left:100px;">点击添加图片</span>
            </span>
        <span class="st-icons st-icons-simg" v-else></span>
      </Upload>
      <ul class="oa-upload-upled" v-if="uploadingList && uploadingList.length>0&&showFlag2!=='4'">
        <li class="" v-for="(item, index) in uploadingList" :key="'upli_'+index">
          <p>{{item.name}}</p>
          <Progress :percent="item.percentage" :stroke-width="5"></Progress>
        </li>
      </ul>
    </div>
    <div v-if="showFlag==='004'">
      <Upload
        ref="upload"
        :action="$store.state.fileUploadUrl"
        :on-success="fileUploadSuccess"
        :on-error="fileUploadError"
        :max-size="1024 * 500"
        :on-format-error="formatError"
        :format="['xlsx','xls']"
        :on-exceeded-size="fileUploadMaxSize"
        :show-upload-list="false"
        :default-file-list="defaultList"
        :before-upload="fileUploadBefore"
        :with-credentials="true"
        style="line-height: normal; cursor: pointer;">
        <Button class="oa-search-header-form-b2" type="primary">导入</Button>
      </Upload>
    </div>
    <div v-if="thisImageFile.name!==undefined&&showFlag==='3'&&showFlag!=='004'" class="oa-upload-list">
        <img :src="$store.state.imgBaseUrl + thisImageFile.name">
        <div class="oa-upload-list-cover">
          <Icon type="ios-eye-outline" @click.native="handleView()"></Icon>
          <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
        </div>
    </div>
    <template v-if="placement === 'bottom'&&showFlag!=='1'&&showFlag!=='2'&&showFlag!=='004'">
      <ul class="oa-upload-img" v-if="imgDataList && imgDataList.length>0">
        <li v-for="(item, index) in imgDataList" :key="'img_' + index">
          <img :src="$store.state.imgBaseUrl + item.name" :alt="item.filename">
          <div class="oa-upload-img-bg" @click="showImg(item)"></div>
          <span class="st-icons st-icons-deleter oa-upload-img-del" @click.stop="delImg(index)"></span>
        </li>
      </ul>
      <ul class="oa-upload-file" v-if="fileDataList && fileDataList.length>0">
        <li v-for="(item, index) in fileDataList" :key="'file_' + index" class="st-ellipsis"
            :class="{'oa-upload-no-border': fileListBorder }">
          <a target="_blank" :href="$store.state.fileBaseUrl + item.name">{{ item.filename }}</a>
          <span class="st-icons st-icons-file"></span>
          <span class="st-icons st-icons-x2" @click="delFile(index)"></span>
        </li>
      </ul>
    </template>
    <!-- 显示图片Modal -->
    <Modal v-model="imgModal" width="800" class="ivu-modal-no-hfc" :closable="false">
      <div slot="header" style="display:none;"></div>
      <div style="padding: 12px; text-align: center;">
        <img v-if="imgModalObj.name" :src="$store.state.imgBaseUrl + imgModalObj.name" :title="imgModalObj.filename"
             style="max-height: 100%; max-width: 100%;">
      </div>
      <div slot="footer" style="display:none;"></div>
    </Modal>
  </div>
</template>
<script>
// upload
export default {
  props: ['showFlag2', 'placement', 'fileListBorder', 'resetUpload', 'resetUpload2', 'showFlag', 'deleteIndex', 'annexList', 'imagePath'],
  data () {
    return {
      imgDataList: [],
      fileDataList: [],
      imgModal: false,
      imgModalObj: {},
      thisImageFile: {},
      defaultList: [],
      uploadingList: []
    }
  },
  watch: {
    // 需要修改的annexList
    annexList () {
      /*
       file对象格式：
       {
       "name":"/image-temp/20170804/346835header背景.png",
       "path":"MjAxNzA4MDQvMzQ2ODM1aGVhZGVy6IOM5pmvLnBuZw ==",
       "filename":"header背景.png",
       "filetime":"2017-08-07 11:16:09",
       "filetype":".png"
       }
       */
      this.imgDataList = [];
      this.fileDataList = [];
      for (let i in this.annexList) {
        this.annexList[i].name = typeof this.annexList[i].save_path !== 'undefined' ? this.annexList[i].save_path : this.annexList[i].annex_path;
        this.annexList[i].path = this.annexList[i].save_path;
        this.annexList[i].filename = this.annexList[i].annex_name;
        if (this.annexList[i].is_image === '1' || this.annexList[i].is_img === '1') {
          this.imgDataList.push(this.annexList[i]);
        } else {
          this.fileDataList.push(this.annexList[i]);
        }
      }
    },
    // 删除
    deleteIndex () {
      if (this.deleteIndex !== -1) {
        if (this.deleteIndex > this.fileDataList.length - 1) {
          let imgIndex = this.deleteIndex - this.fileDataList.length;
          this.imgDataList.splice(imgIndex, 1);
        } else {
          this.fileDataList.splice(this.deleteIndex, 1);
        }
      }
    },
    // 重置
    resetUpload () {
      this.imgDataList = [];
      this.fileDataList = [];
      // this.uploadingList = [];
    },
    imagePath () {
      if (this.imagePath !== '' && this.imagePath !== undefined) {
        this.thisImageFile = {name: this.imagePath};
      }
    },
    resetUpload2 () {
      this.thisImageFile = {};
    },
    imgDataList () {
      if (this.showFlag !== '3') {
        this.$emit('uploadDataListChanged', {
          images: this.imgDataList,
          files: this.fileDataList
        });
      } else {
        this.$emit('uploadDataListChanged2', {
          images: this.imgDataList
        });
      }
    },
    fileDataList () {
      this.$emit('uploadDataListChanged', {
        images: this.imgDataList,
        files: this.fileDataList
      });
    }
  },
  methods: {
    handleView () {
      this.showImg(this.thisImageFile);
    },
    handleRemove () {
      this.thisImageFile = Object.assign({}, {});
      this.imgDataList = [];
    },
    fileUploadError () {
      this.$Notice.warning({
        title: '上传失败'
      });
    },
    fileUploadBefore (file) {
      let filename = file.name;
      let iLen = _charLength(filename, 3);
      if (iLen > 36) {
        this.$Notice.warning({
          title: '文件名过长',
          desc: '文件名不能超过36个字符（一个中文占3个字符）'
        });
        return false;
      }
      return true;
    },
    formatError (file, fileList) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '请选择Excel文件!'
      });
    },
    fileUploadSuccess (response, file, fileList) {
      /*
       file对象格式：
       {
       "name":"/image-temp/20170804/346835header背景.png",
       "path":"MjAxNzA4MDQvMzQ2ODM1aGVhZGVy6IOM5pmvLnBuZw ==",
       "filename":"header背景.png",
       "filetime":"2017-08-07 11:16:09",
       "filetype":".png"
       }
       */
      // 从 upload 实例删除数据
      const oldList = this.$refs.upload.fileList;
      if (this.showFlag !== '3') {
        setTimeout(() => this.$refs.upload.fileList.splice(oldList.indexOf(file), 1), 200);
      }
      if (response && response.rows && response.rows[0]) {
        let oFile = response.rows[0];
        let sExt = oFile.filetype;
        if (sExt) {
          sExt = sExt.toLowerCase();
          // 图片
          if (sExt === '.png' || sExt === '.jpeg' || sExt === '.jpg' || sExt === '.gif') {
            if (this.showFlag !== '3') {
              this._pushImg(oFile);
            } else {
              if (this.showFlag2 !== '4') {
                this.thisImageFile = Object.assign({}, oFile);
                this._pushImg(oFile);
              } else {
                this.$emit('getAImage', Object.assign({}, oFile));
              }
            }
          } else {
            this._pushFile(oFile);
          }
        } else {
          this._pushFile(oFile);
        }
        // 文件
      } else {
        this.$Notice.warning({
          title: '上传失败',
          desc: '请确保文件真实有效'
        });
      }
    },
    _pushImg (oFile) {
      setTimeout(() => this.imgDataList.push(oFile), 250);
    },
    _pushFile (oFile) {
      setTimeout(() => this.fileDataList.push(oFile), 250);
    },
    delFile (index) {
      this.fileDataList.splice(index, 1);
    },
    // 显示图片
    showImg (oImg) {
      this.imgModalObj = oImg;
      this.imgModal = true;
    },
    delImg (index) {
      this.imgDataList.splice(index, 1);
    },
    fileUploadMaxSize (file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过500MB。'
      });
    }
  },
  mounted () {
    this.uploadingList = this.$refs.upload.fileList;
  }
}
/**
 * 字符长度，处理中文
 * utf-8以三个字节存储中文；gbk以二个字节存储中文。
 */
function _charLength (str, chineseLen) {
  if (!str || str.length <= 0) {
    return 0;
  }
  // str = mytrim(str);
  var chineseLength = 3; // utf-8编码，中文长度
  if (chineseLen && chineseLen > 0) {
    chineseLength = chineseLen
  }
  var objValue = str;
  var objLength = 0;
  var compareChar = '';
  var regExp = new RegExp("^[A-Za-z0-9 -_`~!@#$%^&*()-+=|,<.>/?;:'\\\"]$");
  for (var count = 0; count < objValue.length; count++) {
    compareChar = objValue.substring(count, count + 1);
    if (regExp.test(compareChar)) {
      objLength += 1;
    } else if (compareChar === '\\') {
      objLength += 1;
    } else {
      objLength += chineseLength;
    }
  }
  return objLength;
}
</script>
<style scoped>
  .st-icons-forum-upfile {
    margin-left: 0;
  }

  .oa-upload-com {
  }

  .oa-upload-file {
    padding-top: 10px;
  }
  .oa-upload-list{
    display: inline-block;
    width: 300px;
    height: 190px;
    text-align: center;
    line-height: 190px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
  }
  .oa-upload-list img{
    width: 100%;
    height: 100%;
  }
  .oa-upload-list:hover .oa-upload-list-cover{
    display: block;
  }
  .oa-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .oa-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .oa-upload-file > li {
    position: relative;
    padding: 10px 60px 10px 60px;
    margin-bottom: 15px;
    height: 50px;
    line-height: 30px;
    vertical-align: middle;
    border: 1px solid #d9d9d9;
  }

  .oa-upload-file > li:hover {
    background-color: #f6f6f6;
  }

  .oa-upload-file > li > .st-icons-file {
    position: absolute;
    top: 10px;
    left: 20px;
  }

  .oa-upload-file > li > .st-icons-x2 {
    position: absolute;
    top: 10px;
    right: 20px;
    cursor: pointer;
  }

  .email-get-heightShowb {
    position: relative;
    height: 50px;
    padding: 5px 0 0 50px;
  }

  .email-get-positionShowa {
    position: absolute;
    top: 12px;
    left: 5px;
  }

  .email-get-positionShowb {
    height: 20px;
    line-height: 20px;
    vertical-align: middle;
    text-align: left
  }

  .oa-upload-img {
    padding-top: 10px;
    overflow: hidden;
  }

  .oa-upload-img > li {
    float: left;
    position: relative;
    width: 100px;
    height: 80px;
    line-height: 80px;
    vertical-align: middle;
    text-align: center;
    cursor: pointer;
    overflow: hidden;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #f6f6f6;
    border-radius: 2px;
  }

  .oa-upload-img > li > img {
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
  }

  .oa-upload-img-bg {
    display: none;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
    background-color: #000;
    opacity: .1;
  }

  .oa-upload-img-del {
    display: none;
    position: absolute;
    right: 2px;
    top: 2px;
    z-index: 1;
  }

  .oa-upload-img > li:hover .oa-upload-img-bg {
    display: block;
  }

  .oa-upload-img > li:hover .oa-upload-img-del {
    display: block;
  }

  .oa-upload-upled {
    line-height: normal;
    padding-top: 10px;
  }

  .oa-upload-upled > li {
    padding-top: 5px;
  }

  .oa-upload-no-border {
    border: 0 !important;
  }
</style>
