<template>
  <div class="co-attach">
    <ul class="co-attach-list">
      <li v-for="(img,index) in imgs" >
        <img :src="img.src || img.imgPath" @click="imgClick(index, img)"/>
        <span @click="del(index)" class="co-attach-del-btn" v-if="edit"></span>
      </li>
      <li class="co-attach-add-btn" @click="openBtn()" v-show="showAddIcon" v-if="edit"></li>
    </ul>
    <div class="co-attach-overlay" v-if="openApp">
      <ul>
        <li class="co-attach-bar1" @click="open('photo')">拍照</li>
        <li class="co-attach-bar2" @click="open('imgLibrary')">从相册中选择</li>
        <li class="co-attach-bar3"></li>
        <li class="co-attach-bar4" @click="close()">关闭</li>
      </ul>
    </div>
  </div>
</template>

<script>
/**
 * co-attach
 * @module components/attach
 * @desc 图片上传组件
 * @param {String} [action] - 上传目标URL
 * @param {Number} [maxLength] - 最大上传文件数量, [1,9]
 * @param {Boolean} [edit] - 是否可编辑
 * @param {Object} [imgClick] - 图片被点击触发
 * @param {Object} [imgUpload] - 图片上传完成触发
 *
 * @example
 * <co-attach maxLength="9" action="http://app.coracle.com:10026/upload-file"></co-attach>
 */

// import '../../../src/utils/corAPI';
// import '../../../src/utils/common';
// import '../../../src/utils/util';
const EVENT_CLICK = 'imgClick';
const EVENT_UPLOAD = 'imgUpload';

if (process.env.NODE_ENV === 'component') {
  require('CoUI/packages/cell/style.css');
}
export default {
  name: 'co-attach',
  props: {
    action: {
      type: String,
      default: ''
    },
    maxLength: {
      type: Number,
      default: 9
    },
    edit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      imgs: [],
      showAddIcon: true,
      openApp: false
    };
  },

  watch: {
    'imgs': 'changeLength'
  },

  methods: {
    openBtn: function(i) {
      this.openApp = true;
    },
    del: function(i) {
      this.imgs.splice(i, 1);
      this.showAddIco();
    },
    close: function() {
      this.openApp = false;
    },
    open: function(type) {
      var self = this;
      this.openApp = false;
      // 拍照
      var attachPictureFinish = function(json) {
        console.log(json);
        if (json.status === true) {
          self.goUpload(json.data[0].path, function(_data) {
            console.dir(_data);
          });
        } else {
          console.log('拍照失败');
        }
      };

      // 图库
      var attachAlbumFinish = function(json) {
        if (json.status === true) {
          for (let j = 0; j < json.data.length; j++) {
            self.goUpload(json.data[j].path, function(_data) {
              console.dir(_data);
            });
          }
        } else {
          console.log('获取图片失败');
        }
      };

      switch (type) {
        // 拍照
        case 'photo':
          window.corNative.photoForCamera({}, function(error, data) {
            if (error === 0) {
              attachPictureFinish(data);
            } else {
              console.log('corNative photoForCamera error');
            }
          });
          break;
        // 相册
        case 'imgLibrary':
          window.corNative.photoForAlbum({maxNumber: this.maxLength - this.imgs.length}, function(error, data) {
            if (error === 0) {
              attachAlbumFinish(data);
            } else {
              console.log('corNative photoForAlbum error');
            }
          });
          break;
      }
    },
    changeLength: function() {
      this.showAddIco();
    },
    imgClick: function(i, img) {
      var imgs = this.imgs.map(function(a) {
        return a.imgPath;
      });
      var json = {
        path: imgs,
        index: i + 1
      };
      this.$emit(EVENT_CLICK, img);
      window.corNative.showPhotos(json);
    },
    goUpload: function(filePath, cb) {
      var uploadData;
      var uploadJson;
      var self = this;
      window.uploadSuccess = function(aObj, result) {
        if (result.data.reqCode === 2) {
          // 上传中
          // var params = {
          //     title: '上传进度【' + parseInt(result.data.progress, 10) + '%】'
          // };
          // 执行
          // if (result.data.progress < 100) {
          //   KND.NativeAPI.showLoading(params);
          // }
        } else if (result.data.reqCode === 0) {
          // 上传成功
          // KND.NativeAPI.closeLoading();
          cb(window.tools.parse(result.data.file));
          var uploadResult = window.tools.parse(result.data.file);
          var _obj = {
            serverPath: uploadResult.url,
            imgPath: window.tools.server_host + uploadResult.url,
            title: uploadResult.fileName
          };
          self.addImg(_obj);
        } else if (result.data.reqCode === 1) {
          // KND.NativeAPI.closeLoading();
          console.log('上传文件失败');
        }
      };
      uploadData = {
        file: {
          fPath: filePath,
          fType: filePath.split('.').pop(),
          fName: new Date().getTime() + '.' + filePath.split('.').pop()
        }
      };
      uploadJson = {
        url: this.action || window.tools.server_host + '/upload-file',
        data: uploadData,
        contentName: 'files'
      };
      window.corMPortal.upload(uploadJson, window.uploadSuccess);
    },
    addImg: function(obj) {
      this.imgs.push(obj);
      this.$emit(EVENT_UPLOAD, this.imgs);
      this.showAddIco();
    },
    showAddIco: function() {
      this.showAddIcon = this.imgs.length < this.maxLength;
    }
  }
};
</script>

<style lang="css">
  @import "../../../src/style/var-ios9.css";

  @component-namespace co {
    @component attach {
      font-size: 0.75rem;

      li {
        list-style: none;
        padding: 0;
        margin: 0;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          left: 0;
          bottom: 0;
          right: auto;
          top: auto;
          height: 1px;
          width: 100%;
          background-color: #e7e7e7;
          display: block;
          z-index: 15;
          -webkit-transform-origin: 50% 100%;
          transform-origin: 50% 100%;
        }
      }

      @descendent list {
        align-self: center;
        display: flex;
        box-lines: single;
        flex-wrap: wrap;
        background: #fff;
        padding: 0 0 0.5rem 0;

        li {
          margin: 0.5rem 0 0 0.5rem;
          width: 3.2rem;
          height: 3.2rem;
          -webkit-box-flex: 1;
          -ms-flex: 1;

          > img {
            width: 100%;
            height: 100%;
            border-radius: 5px;
            border: none;
          }
        }
      }

      @descendent add-btn {
        width: 3.2rem;
        height:3.2rem;
        background: url(../../../example/assets/add.png);
        background-size: 3.2rem;
      }

      @descendent del-btn {
        position: absolute;
        top: 0;
        right: 0;
        width: 1.2rem;
        height: 1.2rem;
        display: inline-block;
        padding: 0.2rem;
        text-align: center;
        line-height: 0.7rem;
        border:1px solid #eee;
        border-radius: 50%;

        &::before {
          font-family: 'knd-font-icon' !important;
          content: "\1612";
          font-size: 0.6rem;
          position: relative;
          top: -2px;
        }
      }

      @descendent overlay {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.4);
        z-index: 10600;
        transition-duration: 400ms;

        ul {
          margin: 0 auto;
          position: absolute;
          bottom: 10px;
          width: 94%;
          background: initial;
          left: 3%;
          line-height: 3rem;
          text-align: center;
          border-radius: 8px 8px 0 0;

          li {
            background: rgba(243, 243, 243, 0.95);
            line-height: 2.15rem;
            font-size: 1rem;
            color: #0894ec;
          }
        }
      }

      @descendent bar1 {
        border-radius: 5px 5px 0px 0px;
        border: 1px solid #e6e6e6;
      }

      @descendent bar2 {
        border-radius: 0px 0px 5px 5px;
      }

      @descendent bar3 {
        background: rgba(243, 243, 243, 0.01) !important;
        line-height: 2.15rem;
        font-size: 1rem;
        color: #0894ec;
        height: 10px !important;
      }

      @descendent bar4 {
        border-radius: 5px;
      }

    }

  }
</style>
