<template>
  <view
    class="cv-upload-img-wrap"
    :style="{
      marginTop: uploadType == 'one' ? '5px' : ''
    }"
  >
    <block v-if="uploadType == 'big'">
      <view class="cv-upload-imgbig_view" @tap="imgChoose" v-if="localSrc == ''">
        <view class="cv-upload-imgbig-left">
          <view class="cv-upload-imgbig-left__title">{{ uploadTitle }}</view>
          <view>{{ uploadTip.dimension }}</view>
          <view>{{ uploadTip.format }}</view>
          <view>{{ uploadTip.size }}</view>
        </view>
        <view class="cv-upload-imgbig-right">
          <view class="cv-upload-imgbig-right__upload">
            <cv-icons type="circlePlusFilled" size="36" color="#999999"></cv-icons>
            <view>添加图片</view>
          </view>
        </view>
      </view>
      <view class="cv-upload-imgbig_view cv-upload-img_noborder" v-else>
        <view class="cv-upload-img__bd bigimg">
          <image
            class="cv-upload-img-preview"
            lazy-load="true"
            mode="aspectFit"
            :src="localSrc[0]"
            @tap="imgShowbig"
            :data-src="localSrc[0]"
          />
          <cv-icons
            class="cv-uoload-img-remove"
            type="circleError"
            size="20"
            color="#FF0101"
            @tap="imgRemove(0)"
            v-if="!disabled"
          ></cv-icons>
        </view>
      </view>
    </block>
    <block v-else>
      <view class="cv-upload-imgmore_img">
        <block v-if="localSrc != ''">
          <block v-for="(item, index) in localSrc" :key="index">
            <view class="cv-upload-img__bd" :class="(index + 1) % 3 !== 0 ? 'cv-upload-img_img__body__mar' : ''">
              <image
                class="cv-upload-img-preview"
                lazy-load="true"
                mode="aspectFit"
                :src="item"
                @tap="imgShowbig"
                :data-src="item"
              />
              <cv-icons
                class="cv-uoload-img-remove"
                type="circleError"
                size="20"
                color="#FF0101"
                @tap="imgRemove(index)"
                v-if="!disabled"
              ></cv-icons>
            </view>
          </block>
        </block>
        <view class="cv-upload-img__bd" v-if="localSrc.length < allowUploadNum">
          <view class="cv-upload-img-choose" @tap="imgChoose">
            <cv-icons :size="settAdd.size" :color="settAdd.color" :type="settAdd.icon"></cv-icons>
            <view>可{{ settAdd.text }}{{ surplusUploadNum }}张</view>
          </view>
        </view>
      </view>
    </block>
  </view>
</template>
<script>
import mpMixin from '../../libs/mixin/mpMixin.js';
import mixin from '../../libs/mixin/mixin.js';
export default {
  mixins: [mpMixin, mixin],
  name: 'cvUploadImg',
  emits: ['input', 'update:modelValue'],
  props: {
    value: {
      type: [Array, Object, String],
      default() {
        return [];
      }
    },
    modelValue: {
      type: [Array, Object, String],
      default() {
        return [];
      }
    },
    uploadTitle: {
      type: [String],
      default: ''
    },
    // 风格：one单图，more多图，big大图
    uploadType: {
      type: String,
      default: 'one'
    },
    uploadTip: {
      type: Object,
      default() {
        return {
          dimension: '长*宽：750*375像素;',
          format: '格式：jpg/png;',
          size: '大小：小于2MB'
        };
      }
    },
    //默认输入框
    src: {
      type: [Array, Object, String],
      default(newVal) {
        return [];
      }
    },
    maxlength: {
      type: [String, Number],
      default: 1
    },
    addType: {
      type: String,
      default: 'add'
    },
    filename: {
      type: String,
      default: ''
    },
    uploadParam: {
      type: Object,
      default: () => {
        return {};
      }
    },
    apiFunc: {
      type: Function,
      default: null
    },
    disabled: {
      type: [Boolean, String],
      default() {
        return false;
      }
    }
  },
  data() {
    return {
      localVal: null,
      localSrc: [],
      settAdd: {
        text: '添加',
        //icon颜色
        color: '#999999',
        //图标类型，默认相机
        icon: this.addType == 'camera' ? 'mediaCameraFilled' : 'media-image-filled',
        // 图标
        size: 26
      },
      // 每次选择图片数量
      chooseNum: 1,
      // 剩余允许上传数量
      allowUploadNum: 1,
      surplusUploadNum: 1
    };
  },
  watch: {
    value(newVal) {
      this.localVal = newVal;
    },
    modelValue(newVal) {
      this.localVal = newVal;
    },
    src(newVal) {
      this.localSrc = this._dealSrc(newVal);
      this._dealNum();
    }
  },
  created() {
    this.localVal = this.value;
    this.localSrc = this._dealSrc(this.src);
    this.allowUploadNum = parseInt(this.maxlength);
    this._dealNum();
  },
  methods: {
    _currShowToast(msg) {
      uni.showToast({
        title: msg,
        duration: 1200,
        icon: 'none'
      });
    },
    _dealNum() {
      this.surplusUploadNum = this.allowUploadNum - (this.localSrc.length || 0);
    },
    _dealSrc(oldSrc) {
      let newSrc = [];
      if (this.uploadType == 'big') {
        if (typeof oldSrc == 'string') {
          newSrc.push(oldSrc);
        }
      } else if (this.uploadType == 'one') {
        if (typeof oldSrc == 'string') {
          newSrc.push(oldSrc);
        }
      } else {
        if (typeof oldSrc == 'object') {
          return oldSrc;
        }
      }
      return newSrc;
    },
    /** 图片选择 ：从本地相册选择图片或使用相机拍照 */
    // async
    async _chooseImage(type, source = 'album') {
      uni.chooseImage({
        count: this.surplusUploadNum, // 选择照片的总数
        sizeType: ['compressed', 'original'], // 可选择原图或压缩后的图片
        sizeType: ['compressed'], // 默认二者都有,original 原图，compressed 压缩图
        sourceType: ['album', 'camera'], // 可选择性开放访问相册、相机
        sourceType: [source], // 从相册选择 album 从相册选图，camera 使用相机
        success: (res) => {
          // console.warn(res.tempFilePaths);
          // console.warn(res.tempFiles[0].path);

          let uploadChooseNum = res.tempFilePaths.length;
          let uploadCurrIndex = 0; //当前index
          let uploadAlreadyNum = 0; //当前已上传页数

          if (uploadChooseNum >= 9) {
            uni.showToast({ icon: 'none', title: '超出9张~' });
            return false;
          }
          if (uploadChooseNum > this.surplusUploadNum) {
            uni.showToast({ icon: 'none', title: '已超过剩余数量~' });
            return false;
          }

          var timer = setInterval(() => {
            if (this.surplusUploadNum == 0) {
              uni.showToast({
                icon: 'none',
                title: '已上传',
                duration: 1000,
                mask: true
              });
              uni.hideToast();
              uni.hideLoading();
              // TODO 追加到数组
              clearInterval(timer);
            } else if (uploadAlreadyNum < uploadChooseNum) {
              uploadAlreadyNum++;
              // TODO 上传
              uni.showToast({
                icon: 'loading',
                title: '正在上传(' + uploadAlreadyNum + '/' + uploadChooseNum + ')',
                duration: 3000000,
                mask: true
              });
              this._uploadImage(res.tempFilePaths[uploadCurrIndex]);
              uploadCurrIndex++;
              this.surplusUploadNum--;
            } else {
              uni.hideToast();
              uni.hideLoading();
            }
          }, 1000);

          // for (let [index, val] of res.tempFilePaths.entries()) {
          //   this._uploadImage(val); //上传图片
          //   this.surplusUploadNum--;
          // }
        },
        fail: (res) => {}
      });
    },
    /** 图片验证 */
    _imgCheck(imgItem) {
      let imgSize = imgItem.size || 0;
      if (imgSize > 2048) {
      }
    },
    /** 图片上传 */
    _uploadImage(tempFilePaths, type) {
      let filename = this.filename || 'uni-upload'; // 'file_name'
      let uploadParam = Object.assign(
        {},
        {
          file_name: filename,
          savesign: 'uni-upload'
        },
        this.uploadParam
      );

      //将本地资源上传到开发者服务器，客户端发起一个 POST 请求，其中 content-type 为 multipart/form-data。
      this.apiFunc({
        //要上传文件资源的路径。
        filePath: tempFilePaths,
        //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
        name: filename,
        //HTTP 请求中其他额外的 form data
        formData: uploadParam
      })
        .then((uploadRes) => {
          // let resData = JSON.parse(uploadRes.data);
          let resData = uploadRes.data || {};
          if (this.uploadType == 'more') {
            //图集
            if (this.localSrc.length >= 9) return;
            this.localSrc.push(resData.img_cdn);
            this.localVal.push(resData.img_time);
          } else {
            //单图
            this.localSrc.push(resData.img_cdn);
            this.localVal = resData.img_time;
          }
          // this.$forceUpdate();
          this.$emit('input', this.localVal);
          this.$emit('update:modelValue', this.localVal);
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
    // 删除引客卷图片
    imgRemove(imgIndex) {
      if (this.uploadType == 'more') {
        this.localSrc.splice(imgIndex, 1);
        this.localVal.splice(imgIndex, 1);
      } else {
        this.localSrc.splice(imgIndex, 1);
        this.localVal = '';
      }
      this.surplusUploadNum++;
    },
    // 预览大图
    imgShowbig(src) {
      let srcUrl = src.currentTarget.dataset.src;
      uni.previewImage({
        urls: [srcUrl]
        // current: srcUrl,
      });
    },
    imgChoose() {
      if (!this.apiFunc) {
        this._currShowToast('上传方法错误');
        return;
      }
      if (this.uploadType != 'more') {
        this.allowUploadNum = 1;
      }
      if (this.localSrc.length + 1 > this.allowUploadNum) {
        this._currShowToast('超出图片上传个数...');
        return false;
      }
      return new Promise((resolve, reject) => {
        this._chooseImage();
        // this.$emit('input', this.localVal);
        // this.$emit('update:modelValue', this.localVal);
      });
    }
  }
};
</script>
<style>
.cv-upload-img-wrap {
  width: 100%;
}

.cv-upload-img-hd {
  color: #181818;
  font-size: 15px;
  margin-bottom: 10px;
}
/** 选择 */
.cv-upload-img-choose {
  font-size: 12px;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  justify-content: center;
  color: #888888;
}
/** 上传后预览 */
.cv-upload-img-preview {
  width: 100%;
  height: 100%;
  border-radius: 10px;
}
/** 移除 */
.cv-uoload-img-remove {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 997;
  background: #fff;
  border-radius: 50%;
}
/* .cv-upload-img-choose icon {
  font-size: 12px;
  margin-bottom: 10px;
  color: #c8c7cc;
} */
.cv-upload-imgmore_img {
  display: flex;
  flex-wrap: wrap;
}

.cv-upload-img__bd {
  width: 88px;
  height: 66px;
  border: 1px dashed #99999999;
  border-radius: 10px;
  margin-bottom: 5px;
  position: relative;
}

.cv-upload-img__bd.bigimg {
  width: 100%;
  height: 100%;
}

.cv-upload-img_img__body__mar {
  margin-right: 45rpx;
}

.cv-upload-img_noborder {
  border: 0px !important;
  padding: 0px !important;
}
.cv-upload-imgbig_view {
  height: 170px;
  padding: 10px 20px;
  display: flex;
  border: 1px dashed #c7c7c7;
  color: #888888;
  border-radius: 5px;
  justify-content: space-between;
  font-size: 24rpx;
  margin-bottom: 5px;
}
.cv-upload-imgbig-left {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.cv-upload-imgbig-left view {
  max-width: 400rpx;
  overflow: hidden;
  text-overflow: ellipsis;
}
.cv-upload-imgbig-left__title {
  color: #181818;
  font-size: 34rpx;
  margin-bottom: 10rpx;
}
.cv-upload-imgbig-right {
  display: flex;
  align-items: center;
}
.cv-upload-imgbig-right__upload {
  border-radius: 20rpx;
  background: #e5e5e1;
  width: 180rpx;
  height: 180rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>
