<template>
  <div>
    <div class="cameraDiv1">
      <div class="imgPre" v-if="imgArr && imgArr.length">
        <van-icon
          class="photobrowsing"
          name="expand-o"
          size="22px"
          color="#1989fa"
          @click="deleteImgs" />
        <img :src="imgUrlArr[0]" alt="" />
      </div>
      <p class="coverImg" @click="uploadImg">
        <van-icon class="photo ico" name="photograph" size="16px" color="#969696">{{
          imgText
        }}</van-icon>
      </p>
    </div>
    <p style="text-align: center">{{ imgText }}</p>
    <div class="mask" v-if="progressFlag">
      <el-progress
        type="circle"
        :percentage="percentage"
        :show-text="true"
        :format="format"></el-progress>
      <div class="progressClose" @click="progressClose">取消</div>
    </div>
    <!-- 图像识别弹框 -->
    <imageAIVerifyErr
      v-if="imageAIVerifyFlag"
      :imageAIVerifyFlag="imageAIVerifyFlag"
      :imageAIVerifyData="imageAIVerifyData"
      @confirmUpload="confirmUpload"
      @uploadImgFun="uploadImg"
      :source="'newCreated'"
      @normalFlow="normalFlow"
      @close="close"></imageAIVerifyErr>
  </div>
</template>

<script>
import { ImagePreview } from 'vant';
import axios from 'axios';
import { uploadImagev } from '@/api/index';
import imageAIVerifyErr from './imageAIVerifyErr';
export default {
  name: 'uploadImg',
  components: { imageAIVerifyErr },
  props: {
    uploadid: {
      type: String,
      default: '',
    },
    imgText: {
      type: String,
      default: '',
    },
    visitsId: {
      type: String,
      default: '',
    },
    taskId: {
      type: String,
      default: '',
    },
    collectionId: {
      type: String,
      default: '',
    },
    type: {
      type: Number,
      default: 1,
    },
    imgArr: {
      type: [String, Array],
      default: '',
    },
    count: {
      type: Number,
      default: 1,
    },
    disabled: {
      // 是否可以添加或修改 true:不可以
      type: Boolean,
      default: false,
    },
    photoIdentifyType: {
      // 图匠识别目的(1:店招内容识别,2:门店代码识别,3:调色机识别,4:更换店招)
      type: String,
      default: '',
    },
  },
  data() {
    return {
      shows: false,
      url: '',
      localIds: [],
      num: 0,
      serverIdArr: [],
      imgUrlArr: [],
      progressFlag: false,
      percentage: 0,
      timeFlag: null,
      imageAIVerifyFlag: false,
      imageAIVerifyData: null, //图匠校验返回的数据
      controller: null, //取消请求状态
    };
  },
  watch: {
    imgArr: {
      handler(val) {
        if (val) this.imgUrlArr = val.split(',');
      },
      immediate: true,
    },
  },
  methods: {
    deleteImgs() {
      ImagePreview(this.imgUrlArr);
    },
    uploadImg() {
      if (this.disabled) return;
      if (localStorage.getItem('chainName') == null) {
        this.$toast('请输入名称！');
        return;
      }
      console.log(this.wx);
      console.log(this.wx.ready);
      this.wx.ready(() => {
        console.log(this.wx.chooseImage);
        this.wx.chooseImage({
          count: this.count,
          sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
          defaultCameraMode: 'normal', //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。从3.0.26版本开始支持front和batch_front两种值，其中front表示默认为前置摄像头单拍模式，batch_front表示默认为前置摄像头连拍模式。（注：用户进入拍照界面仍然可自由切换两种模式）
          isSaveToAlbum: 0,
          success: (chooseRes) => {
            this.localIds = chooseRes.localIds;
            console.log('count=' + this.count);
            console.log('chooseRes=' + chooseRes);
            console.log('localIds=' + this.localIds);
            // if (chooseRes.localIds != undefined) {
            //   localIds = chooseRes.localIds[0];
            // } else {
            //   localIds = chooseRes.localId;
            // }
            this.num = 0;
            this.serverIdArr = [];
            this.forUploadImage();
          },
        });
      });
    },
    forUploadImage() {
      this.wx.uploadImage({
        localId: this.localIds[this.num],
        isShowProgressTips: 1,
        success: (uploadRes) => {
          this.serverIdArr.push(uploadRes.serverId);
          console.log('serverId=' + uploadRes.serverId);
          this.num++;
          if (this.num == this.localIds.length) {
            this.uploadImagev(this.serverIdArr.join(','));
          } else {
            this.forUploadImage();
          }
        },
      });
    },
    uploadImagev(meidaId) {
      // 初始化重置 图匠校验
      this.resetProgress();
      this.close();
      var that = this;
      var form = {
        mediaId: meidaId,
        storeName: localStorage.getItem('chainName'),
        locationRemark: localStorage.getItem('locationRemark'),
        deptName: localStorage.getItem('deptName'),
      };
      this.controller = null;
      // 需要图匠校验的添加参数和loading
      if (this.photoIdentifyType) {
        form.photoIdentifyType = this.photoIdentifyType;
        this.progress();
        this.controller = new AbortController(); //取消请求
      } else {
        this.toastLoading(0, '上传中...', true);
      }
      uploadImagev(form, this.controller ? this.controller.signal : null)
        .then((res) => {
          this.toastLoading().clear();
          if (res.code == -1) {
            // 图匠图片校验接口超时
            this.requestTimeOut(res);
          } else if (res.code == 200) {
            // 图匠校验结果返回
            if (this.photoIdentifyType) {
              // 重置loaidng状态
              this.resetProgress();
              this.imageAIVerifyFlag = true;
              console.log('res.data=' + JSON.stringify(res.data));
              this.imageAIVerifyData = res.data;
            } else {
              // 正常流程
              this.normalFlow(res);
            }
          } else {
            this.resetProgress();
            that.$toast('上传失败！');
          }
        })
        .catch((error) => {
          if (error.message === 'canceled') {
            this.$toast('取消上传');
            console.log('请求被取消:', error.message);
          }
          this.resetProgress();
        });
    },
    progress() {
      // 后端接口20000ms后失效，每1000m progress加10，到90停止；
      this.progressFlag = true;
      this.percentage = 10;
      this.timeFlag = setInterval(() => {
        this.percentage = this.percentage + 10;
        if (this.percentage == 90) clearInterval(this.timeFlag);
      }, 1000);
    },
    format(percentage) {
      return `${percentage} %\n图像识别中`;
    },
    requestTimeOut(res) {
      this.resetProgress();
      this.close();
      this.$dialog
        .confirm({
          title: '系统提示',
          message: res.msg,
          showCancelButton: false,
        })
        .then(() => {
          this.normalFlow(res);
        });
    },
    // 正常流程
    normalFlow(res) {
      let imgArr = [];
      let businessId = [];
      res.data.forEach((item) => {
        imgArr.push(item.url);
        if (item.businessId) businessId.push(item.businessId);
      });
      this.$toast('上传成功！');
      this.$emit('newimgarr', {
        fileUrl: imgArr.join(','),
        type: this.type,
        businessId: businessId.join(','),
      });
    },
    // 重置loaidng状态
    resetProgress() {
      this.percentage = 100;
      clearInterval(this.timeFlag);
      this.progressFlag = false;
      this.percentage = 0;
    },
    // 取消图片上传
    progressClose() {
      this.controller.abort();
    },
    confirmUpload(res) {
      this.normalFlow(res);
    },
    close() {
      this.imageAIVerifyFlag = false;
    },
  },
};
</script>

<style scoped>
.cameraDiv1 {
  position: relative;
  height: 164px;
  width: 100%;
  background-color: white;
}

.cameraDiv1 img {
  position: absolute;
  width: 100%;
  display: block;
  height: 164px;
  top: 0;
}

.imgPre {
  height: 164px;
  width: 100%;
  background-color: white;
  border-radius: 6px;
  overflow: hidden;
}

.photos1 {
  margin: 70px auto;
  left: 50%;
  margin-left: -14px;
}

.photobrowsing {
  position: absolute;
  padding: 4px;
  right: 0;
  top: 0;
  z-index: 99;
  background-color: rgba(255, 255, 255, 0.8);
  border-bottom-left-radius: 3px;
  border-top-left-radius: 3px;
}

.coverImg {
  text-align: center;
  position: absolute;
  top: 0;
  left: 0;
  height: 164px;
  width: 100%;
}

.coverImg .ico {
  top: 42%;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99999999;
  display: flex;
  flex-direction: column;
  .progressClose {
    width: 70px;
    text-align: center;
    background: #67c23a;
    color: #fff;
    height: 30px;
    line-height: 30px;
    border-radius: 5px;
    margin-top: 5px;
    font-size: 12px;
  }
}
</style>
<style lang="scss">
.mask {
  .el-progress__text {
    white-space: pre-wrap;
  }
}
</style>
