<template>
  <div class="cus-appendix" :class="{'cus-appendix-btn': isButton}">
    <div class="" @click.stop="isButton ? showActions() : ''">
      <slot ></slot>
    </div>
    <div v-if="isButton === false" class="co-transverse-scroll co-appendix" style="min-height: 50px;" :style="{'width': returnWidth() + 'vw'}">
      <div class="co-scorll" :style="{width: (100 / 5 * datas.length) + 'vw'}">
        <div class="co-appendix-item co-appendix-item-no-name" v-for="(item, i) in datas">
          <span @click.stop="openFile(item.url)" v-if="returnIcon(item.url)" class="xs-icon" :class="returnIcon(item.url)"></span>
          <img @click.stop="openFile(item.url)" :src="params.service + item.url" v-if="!returnIcon(item.url)" />
          <i class="coicon coicon-delete_fill" v-if="isDelete" @click.stop="deleteFn(i)"></i>
        </div>
      </div>
    </div>
    <div v-if="isButton === false" class="add">
      <a href="javascript:void(0);" @click.stop="showActions()" class="coicon coicon-add"></a>
    </div>
    <co-actionsheet :actions="actions" v-model="sheetVisible"></co-actionsheet>
  </div>
</template>
<script>
export default {
  name: 'cus-appendix',
  data() {
    return {
      sheetVisible: false,
      actions: [
        {
          name: '拍照',
          method: this.takePhoto
        },
        {
          name: '从相册中选择',
          method: this.openAlbum
        },
        {
          name: '音频',
          method: this.takeAudio
        }
      ]
    };
  },
  props: {
    isButton: {
      'type': Boolean,
      'default': false
    }, // 按钮
    params: {
      'type': Object,
      'default': {}
    }, // 上传接口
    datas: {
      'type': Array,
      'default': []
    },
    isDelete: { // 是否需要删除按钮
      'type': Boolean,
      'default': false
    }
  },

  methods: {
    openFile(pathUrl) {
      let suffix = pathUrl.substring(pathUrl.lastIndexOf('.') + 1, pathUrl.length).toLocaleLowerCase();
      let suffixType = '';
      if ('.jpg|.jpeg|.gif|.bmp|.png|'.indexOf(suffix + '|') > -1) {
        /* 图片*/
        suffixType = 'IMAGE';
      } else if ('.mp4|.mov|'.indexOf(suffix + '|') > -1) {
        /* 视频*/
        suffixType = 'VEDIO';
      } else if ('.amr|.wav|'.indexOf(suffix + '|') > -1) {
        /* 音频*/
        suffixType = 'AUDIO';
      } else if ('.txt|.doc|.xls|.ppt|.pptx|.pdf|.docx|.xlsx|'.indexOf(suffix + '|') > -1) {
        /* 办公*/
        suffixType = 'OFFICE';
      } else if ('.html|.jsp|.php|.asp|.js|.css|'.indexOf(suffix + '|') > -1) {
        /* 网页*/
        suffixType = 'WEBSITE';
      } else {
        this.$messagebox.alert('对不起，app不支持该附件类型！', '提示');
        return;
      }
      if (suffixType === 'IMAGE') {
        window.corNative.showPhotos({
          'path': [this.params.service + pathUrl]
        });
        return;
      }
      let params = {
        path: this.params.service + pathUrl,
        suffix: pathUrl.substring(pathUrl.lastIndexOf('.') + 1, pathUrl.length),
        type: suffixType
      };
      window.corMPortal.openFile(params);
    },
    returnWidth() {
      let width = 100 / 5 * this.datas.length;
      if (width > 84) {
        width = 84;
      }
      return width;
    },
    returnIcon(pathUrl) {
      let suffix = pathUrl.substring(pathUrl.lastIndexOf('.') + 1, pathUrl.length).toLocaleLowerCase();
      let icon = '';
      if ('.jpg|.jpeg|.gif|.bmp|.png|'.indexOf(suffix + '|') > -1) {
        /* 图片*/
        icon = '';
      } else if ('.amr|.wav|.mp3|'.indexOf(suffix + '|') > -1) {
        icon = 'xs-icon-audio';
      } else if ('.mp4|.mov|'.indexOf(suffix + '|') > -1) {
        /* 视频*/
        icon = 'xs-icon-vedio';
      } else if ('.doc|.docx|'.indexOf(suffix + '|') > -1) {
        icon = 'xs-icon-word';
      } else if ('.xls|.xlsx|'.indexOf(suffix + '|') > -1) {
        icon = 'xs-icon-excel';
      } else if ('.ppt|.pptx|'.indexOf(suffix + '|') > -1) {
        icon = 'xs-icon-ppt';
      } else if ('.pdf|'.indexOf(suffix + '|') > -1) {
        icon = 'xs-icon-pdf';
      } else if ('.zip'.indexOf(suffix + '|') > -1) {
        /* 办公*/
        icon = 'xs-icon-zip';
      } else {
        // 对不起，app不支持该附件类型！
        icon = 'xs-icon-not-other';
      }
      return icon;
    },
    showActions() {
      this.sheetVisible = true;
    },
    deleteFn(index) {
      let datas = this.datas || [];
      datas.splice(index, 1);
      this.$emit('appendixInput', datas);
    },
    takePhoto() {
      // 拍照
      this.$indicator.open({ className: 'co-indicator-default' });
      window.corNative.photoForCamera({'destinationType': 'path'}, (error, result) => {
        if (error === 0 && result.status && result.data && result.data.path) {
          this.goUpload(result.data.path);
        } else {
          this.$indicator.close();
          console.log('--------取消-------');
        }
      });
    },
    openAlbum() {
      // 相册
      this.$indicator.open({ className: 'co-indicator-default' });
      window.corNative.photoForAlbum({'destinationType': 'path'}, (error, result) => {
        if (error === 0 && result.status && result.data && result.data.length > 0) {
          this.goUpload(result.data[0].path);
        } else {
          this.$indicator.close();
          console.log('--------取消-------');
        }
      });
    },
    takeAudio() {
      // 音频
      this.$indicator.open({ className: 'co-indicator-default' });
      window.corNative.openRecord((error, result) => {
        if (error === 0 && result.status && result.data && result.data.length > 0) {
          this.goUpload(result.data[0].path);
        } else {
          this.$indicator.close();
          console.log('--------取消-------');
        }
      });
    },
    uploadSuccess(error, result) {
      if (error === 0) {
        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();
          setTimeout(() => {
            this.$indicator.close();
          }, 10);
          let datas = this.datas || [];
          datas.push(result.data.file);
          this.$emit('appendixInput', datas);
        } else if (result.data.reqCode === 1) {
          // KND.NativeAPI.closeLoading();
          setTimeout(() => {
            this.$indicator.close();
          }, 10);
          this.$messagebox.alert('上传失败，请重试！', '提示');
        }
      } else {
        setTimeout(() => {
          this.$indicator.close();
        }, 10);
        this.$messagebox.alert('上传失败，请重试！', '提示');
      }
    },
    goUpload(filePath) {
      // 上传
      let uploadData = {
        file: {
          fPath: filePath,
          fType: filePath.split('.').pop(),
          fName: new Date().getTime() + '.' + filePath.split('.').pop()
        }
      };
      let uploadJson = this.params;
      uploadJson.url = uploadJson.action;
      uploadJson.data = uploadData;
      if (!this.params.contentName) {
        this.params.contentName = 'files';
      }
      if (!this.params.url) {
        this.params.url = window.tools.server_host + '/upload-file';
      }
      window.corMPortal.upload(uploadJson, this.uploadSuccess);
    }
  }
};
</script>
