<template>
  <div class="questionNamep">
    <!-- 0=企业微信，1=H5相机 -->
    <!-- 企业微信拍照 -->
    <div class="cameraDiv" @click="uploadImg" v-if="userInfo.photoMethod == '0'">
      <van-icon class="photo photos" name="plus" size="22px" color="#969696" />
      <span style="font-size: 10px">添加图片</span>
    </div>
    <!-- 原生自带拍照 -->
    <H5Camera
      @getImg="getImg"
      ref="H5Camera"
      :objectType="objectType"
      :capture="pictureSource == '1' ? '' : 'camera'"
      v-else />
    <div id="allmap"></div>
    <imageAIVerifyErr
      v-if="imageAIVerifyFlag"
      :imageAIVerifyFlag="imageAIVerifyFlag"
      :imageAIVerifyData="imageAIVerifyData"
      @confirmUpload="confirmUpload"
      @uploadImgFun="uploadImgFun"
      :source="'visit'"
      @normalFlow="normalFlow"
      @close="close"></imageAIVerifyErr>
    <!-- 图像识别白名单弹框提示 -->
    <imageWhiteStore
      v-if="imageWhiteStoreFlag"
      :imageWhiteStoreFlag="imageWhiteStoreFlag"
      :imageWhiteStoreData="imageWhiteStoreData"
      @normalFlow="normalFlow"
      @close="close">
    </imageWhiteStore>
    <!-- 上传动画 -->
    <div class="uploadImgDemoMask" v-show="uploadImgFlag">
      <div class="uploadImgDemo">
        <div class="ring-area" id="d2area" style="display: flex">
          <div class="ring-wrap">
            <svg width="90" height="90" viewBox="0 0 90 90">
              <circle class="ring-bg" cx="45" cy="45" r="40" />
              <circle class="ring-progress" id="d2ring" cx="45" cy="45" r="40" />
            </svg>
            <div class="ring-text">
              <span class="ring-pct" id="d2pct">0%</span>
              <span class="ring-sub" id="d2sub">上传中</span>
            </div>
          </div>
          <div class="ring-info">
            <div class="ring-filename" id="d2name"></div>
            <div class="ring-list" id="d2dots">
              <div
                v-for="(value, index) in uploadImgTotal"
                class="ring-dot"
                :id="`dot${index}`"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addPhotoBatch, addVisitsPosition, addPhotoToDB, buryingPoint } from '@/api/index';
import imageAIVerifyErr from './imageAIVerifyErr';
import imageWhiteStore from './imageWhiteStore';
import H5Camera from '@/components/H5Camera';
import axios from 'axios';
import uploadAliOss from '@/utils/uploadAliOss';
import { addH5Photo } from '@/api/H5Camera';
import { mapState } from 'vuex';

export default {
  name: 'uploadImg',
  components: { imageAIVerifyErr, H5Camera, imageWhiteStore },
  props: {
    storeGroupId: {
      type: String,
      default: '',
    },
    visitsId: {
      type: String,
      default: '',
    },
    taskList: {
      type: Array,
      default() {
        return [];
      },
    },
    objectType: {
      type: String,
      default: '',
    },
    putInCode: {
      type: String,
      default: '',
    },
    photoIdentifyType: {
      // 图匠识别目的(1:店招内容识别(不能连拍和多选),3:调色机识别(不能连拍和多选),6:陈列SKU图片识别(不需要图匠实时识别))
      type: String,
      default: '',
    },
    pictureSource: {
      // 是否允许从相册选择图片 1:允许；0:不允许
      type: String,
      default: '0',
    },
    continuousShoot: {
      // 是否允许连拍/相册多选 1:允许；0:不允许
      type: String,
      default: '0',
    },
    collectionItemId: {
      type: [String, Number],
      default: '',
    },
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  data() {
    return {
      shows: false,
      url: '',
      imageAIVerifyFlag: false,
      imageAIVerifyData: null, //图匠校验返回的数据
      mediaId: '', //当前上传图片id
      addressesRemark: '', //当前位置信息
      controller: null, //取消请求状态
      fileUrl: '',
      imageWhiteStoreData: null,
      imageWhiteStoreFlag: false,
      localIdsArr: [],
      uploadImgFlag: false, //上传图片中
      uploadImgTotal: 0, // 上传图片总数
      d2running: false,
      d2count: 0,
      d2timer: null,
      interfaceUsageTime: null,
    };
  },
  activated() {
    this.resetDemo2();
  },
  methods: {
    // 原生H5拍照图片
    // url: base64
    getImg(base64) {
      // 图片名称：用户名-时间戳
      let username = localStorage.getItem('loginName');
      let imgName = username + '-' + new Date().getTime();
      uploadAliOss(base64, imgName)
        .then((res) => {
          if (res.url && res.url.indexOf('http') != -1) {
            this.fileUrl = res.url;
            this.uploadImagev();
          }
        })
        .catch((err) => {
          console.log('err:' + err);
        });
    },
    uploadImgFun() {
      // 0=企业微信，1=H5相机
      if (this.userInfo.photoMethod == '0') {
        this.uploadImg();
      } else {
        this.$refs.H5Camera.camera();
      }
    },
    uploadImg() {
      var map = new TMap.Map('allmap', {
        zoom: 14,
        center: new TMap.LatLng(39.986785, 116.301012),
      });

      var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
      var markers = new TMap.MultiMarker({
        map: map,
        geometries: [],
      });
      markers.setGeometries([]);

      let url = window.location.href;
      let that = this;
      let wx = this.wx;
      let qiyeData;
      this.addressesRemark = '';
      const instance = axios.create();
      instance.defaults.headers.common['userId'] = localStorage.getItem('loginName');
      instance
        .get(process.env.VUE_APP_BASE_API + 'mobile/wx/ticket', {
          params: {
            url: url,
          },
        })
        .then((response) => {
          if (response.status == 200) {
            qiyeData = response.data.data;
            wx.config({
              beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: qiyeData.appId, // 必填，企业微信的corpID
              timestamp: qiyeData.timestamp, // 必填，生成签名的时间戳
              nonceStr: qiyeData.nonceStr, // 必填，生成签名的随机串
              signature: qiyeData.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
              jsApiList: ['ready', 'chooseImage', 'uploadImage', 'getLocation'], // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
            });
            wx.ready(function () {
              wx.getLocation({
                type: 'gcj02',
                success: function (res) {
                  var location = new TMap.LatLng(res.latitude, res.longitude);
                  map.setCenter(location);
                  markers.updateGeometries([
                    {
                      id: 'main', // 点标注数据数组
                      position: location,
                    },
                  ]);
                  geocoder.getAddress({ location: location }).then(
                    function (result) {
                      var addresses = result.result.formatted_addresses;
                      that.addressesRemark = addresses.recommend;
                    },
                    function (err) {
                      that.addressesRemark = '';
                    },
                  );
                },
                fail: function () {
                  that.$dialog.alert({
                    message: 'GPS未开启',
                  });
                },
              });
              console.log(that.pictureSource);
              let sourceType = that.pictureSource == '1' ? ['album', 'camera'] : ['camera'];
              let count = 1;
              // 1:店招内容识别(不能连拍和多选),3:调色机识别(不能连拍和多选) 需要实时识别的不支持连拍和多选
              if (that.photoIdentifyType != 1 && that.photoIdentifyType != 3) {
                count = that.continuousShoot == '1' ? 20 : 1; //是否允许连拍/相册多选 最多5张
              }
              wx.chooseImage({
                count: count,
                sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
                defaultCameraMode: count == 1 ? 'normal' : 'batch', //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。从3.0.26版本开始支持front和batch_front两种值，其中front表示默认为前置摄像头单拍模式，batch_front表示默认为前置摄像头连拍模式。（注：用户进入拍照界面仍然可自由切换两种模式）
                // defaultCameraMode: 'normal', //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。从3.0.26版本开始支持front和batch_front两种值，其中front表示默认为前置摄像头单拍模式，batch_front表示默认为前置摄像头连拍模式。（注：用户进入拍照界面仍然可自由切换两种模式）
                isSaveToAlbum: 0, //整型值，0表示拍照时不保存到系统相册，1表示自动保存，默认值是1
                success: function (res) {
                  that.toastLoading(0, '上传中...', true);
                  let localIds = res.localIds;
                  that.interfaceUsageTime = Date.now();
                  that.localIdsArr = [];
                  // that.$emit('newimgarr', {
                  //   localIds: localIds,
                  //   locationRemark: that.addressesRemark,
                  //   collectionItemId: that.collectionItemId,
                  //   source: 'weixin',
                  // });
                  that.uploadImgFlag = true;
                  that.uploadImgTotal = localIds.length;
                  that.startDemo2();
                  that.syncUpload(localIds);
                },
              });
            });
          }
        });
    },
    syncUpload(localIds) {
      if (!localIds.length) {
        this.uploadImagev();
      } else {
        var localId = localIds.pop();
        wx.uploadImage({
          localId: localId,
          isShowProgressTips: 0, // 默认为1，显示进度提示
          success: (res) => {
            this.localIdsArr.push(res.serverId);
            this.syncUpload(localIds);
          },
        });
      }
    },
    uploadImagev() {
      this.close();
      var that = this;
      var form = {
        mediaIds: [], //	是	List<String>	图片素材id集合
        visitSource: '1', //	是	Long	拜访模式
        storeGroupId: that.storeGroupId, //	是	string	门店任务组，多个用逗号隔开
        visitsId: that.visitsId, //	是	string	拜访id
        taskList: that.taskList, //	是	List	任务id数组
        collectionItemId: that.collectionItemId, //	是	string	采集项id
        objectType: that.objectType, //	是	string	照片类型，取任务上的照片类型，如果没有则取手动选择的照片类型
        locationRemark: that.addressesRemark, //	是	String	当前地址信息
        firstCollectionId: '', //	否	Long	第一级采集项id，取当前采集项的字段就行
        secondCollectionId: '', //	否	Long	第二级采集项id，取当前采集项的字段就行
        putInCode: that.putInCode, //投放编号
        deviceCode: '', //	否	String	当前任务对应的设备编号
        photoIdentifyType: that.photoIdentifyType, //	否	String	图片识别类型：字典-photo_identify_type
        equipmentCode: '', //	否	String	当前任务对应的资产编号
        inStore: '否', //	否	String	机器是否在店：传选项中文内容，是、否
      };
      // 0=企业微信，1=H5相机
      if (this.userInfo.photoMethod == '0') {
        form.mediaIds = this.localIdsArr; //	string	图片素材id
      } else {
        form.fileUrl = this.fileUrl; //	string	图片素材id
      }
      this.controller = null;
      // 需要图匠校验的添加参数和loading
      if (
        this.photoIdentifyType &&
        (this.photoIdentifyType == '1' || this.photoIdentifyType == '3')
      ) {
        form.photoIdentifyType = this.photoIdentifyType;
        this.controller = new AbortController(); //取消请求
      } else {
        this.toastLoading(0, '上传中...', true);
      }
      addPhotoBatch(form, this.controller ? this.controller.signal : null)
        .then((res) => {
          if (this.userInfo.photoMethod == '0') {
            if (this.interfaceUsageTime) {
              this.interfaceUsageTime = Number(
                ((Date.now() - this.interfaceUsageTime) / 1000).toFixed(0),
              );
            }
            buryingPoint({
              systemModel: '门店拜访',
              buryingPointType: 8,
              buryingPointValue: form.mediaIds.length,
              buryingPointName: '陈列奖励案图片上传',
              buryingPointPosition: '门店拜访-陈列奖励案任务',
              interfaceUsageTime: this.interfaceUsageTime,
            });
          }
          this.requestThen(res);
        })
        .catch((error) => {
          this.resetDemo2();
          this.requestCatch(error);
        });
    },
    // 公用请求then
    requestThen(res) {
      this.toastLoading().clear();
      if (res.code == -1) {
        // 图匠图片校验接口超时
        this.requestTimeOut(res);
      } else if (res.code == 200) {
        // 图匠校验结果返回
        if (
          this.photoIdentifyType &&
          (this.photoIdentifyType == '1' || this.photoIdentifyType == '3')
        ) {
          this.imageAIVerifyFlag = true;
          this.imageAIVerifyData = res.data[0];
        } else {
          // 正常流程
          // 图像识别白名单用户弹出框提示
          if (res.data[0].whiteStore) {
            this.imageWhiteStoreFlag = true;
            this.imageWhiteStoreData = res.data[0];
          } else {
            this.normalFlow(res);
          }
        }
      } else {
        this.resetDemo2();
        that.$toast('上传失败！');
      }
    },
    // 公用请求catch
    requestCatch(error) {
      if (error.message === 'canceled') {
        this.$toast('取消上传');
        console.log('请求被取消:', error.message);
      }
    },
    // 正常流程
    normalFlow(res) {
      if (this.d2timer) {
        clearTimeout(this.d2timer);
      }
      try {
        this.runD2(500, false, () => {
          this.resetDemo2();
          this.$toast('上传成功！');
          let fileInfoList = [];
          res.data.forEach((val) => {
            fileInfoList.push({
              fileUrl: val.url,
              id: val.fileId,
              type: 2,
            });
          });
          this.$emit('newimgarr', {
            fileInfoList: fileInfoList,
            photoIdentifyType: this.photoIdentifyType,
            source: 'H5',
          });
        });
      } catch (error) {
        this.resetDemo2();
      }
    },
    resetDemo2() {
      if (this.d2timer) {
        clearTimeout(this.d2timer);
      }
      this.d2running = false;
      this.d2count = 0;
      this.uploadImgTotal = 0;
      if (document.getElementById('d2ring')) {
        document.getElementById('d2ring').style.strokeDashoffset = 251.2;
      }
      if (document.getElementById('d2pct')) {
        document.getElementById('d2pct').textContent = '0%';
      }
      if (document.getElementById('d2sub')) {
        document.getElementById('d2sub').textContent = '上传中';
      }
      if (document.getElementById('d2name')) {
        document.getElementById('d2name').textContent = '正在上传。。。';
      }
      this.uploadImgFlag = false;
    },
    // 照片是否入库，1.照片识别三次不通过仍要上传，2.照片识别通过
    // isUpdate:是否更新店招照片，只有门店店招需要更新
    confirmUpload(res) {
      if (
        this.photoIdentifyType &&
        (this.photoIdentifyType != '6' || this.photoIdentifyType != '7')
      ) {
        var form = {
          mediaIds: [], //	是	List<String>	图片素材id集合
          visitSource: '1', //	是	Long	拜访模式
          storeGroupId: this.storeGroupId, //	是	string	门店任务组，多个用逗号隔开
          visitsId: that.visitsId, //	是	string	拜访id
          taskList: this.taskList, //	是	List	任务id数组
          collectionItemId: that.collectionItemId, //	是	string	采集项id
          objectType: that.objectType, //	是	string	照片类型，取任务上的照片类型，如果没有则取手动选择的照片类型
          locationRemark: this.addressesRemark, //	是	String	当前地址信息
          firstCollectionId: '', //	否	Long	第一级采集项id，取当前采集项的字段就行
          secondCollectionId: '', //	否	Long	第二级采集项id，取当前采集项的字段就行
          putInCode: that.putInCode, //投放编号
          deviceCode: '', //	否	String	当前任务对应的设备编号
          photoIdentifyType: that.photoIdentifyType, //	否	String	图片识别类型：字典-photo_identify_type
          equipmentCode: '', //	否	String	当前任务对应的资产编号
          inStore: '否', //	否	String	机器是否在店：传选项中文内容，是、否
        };
        // 0=企业微信，1=H5相机
        if (this.userInfo.photoMethod == '0') {
          form.mediaIds = this.localIdsArr; //	string	图片素材id
        } else {
          form.fileUrl = this.fileUrl; //	string	图片素材id
        }
        if (res.isUpdate) {
          form.isUpdate = 'true';
        }
        addPhotoToDB(form).then((resData) => {
          if (resData.code == 200) {
            console.log(resData);
            res.data.fileId = resData.data[0].fileId;
            res.data = [res.data];
            this.normalFlow(res);
          }
        });
      }
    },
    close() {
      this.imageAIVerifyFlag = false;
      this.imageWhiteStoreFlag = false;
    },
    requestTimeOut(res) {
      this.close();
      this.$dialog
        .confirm({
          title: '系统提示',
          message: res.msg,
          showCancelButton: false,
        })
        .then(() => {
          this.confirmUpload(res);
        });
    },
    // ===== Demo 2 =====
    startDemo2() {
      if (this.d2running) return;
      this.d2running = true;
      this.d2count = 0;
      this.runD2(1100, true);
    },
    runD2(delay, isFirst, callback) {
      //   this.NAMES = Array.from(
      //     { length: this.uploadImgTotal },
      //     (_, i) => `IMG_${String(2001 + i).padStart(4, '0')}.jpg`,
      //   );
      if (this.d2count >= this.uploadImgTotal) {
        document.getElementById('d2sub').textContent = '完成';
        document.getElementById('d2name').textContent = '全部上传成功 ✅';
        callback && callback();
        return;
      }
      if (this.uploadImgTotal >= 2) {
        this.d2timer = setTimeout(() => {
          if (this.d2count > 0) {
            document.getElementById(`dot${this.d2count - 1}`).className = 'ring-dot done';
          }
          document.getElementById(`dot${this.d2count}`).className = 'ring-dot active';
          document.getElementById('d2name').textContent = '正在上传。。。';
          this.d2count++;
          const pct = Math.round((this.d2count / this.uploadImgTotal) * 100);
          document.getElementById('d2pct').textContent = pct + '%';
          const offset = 251.2 * (1 - this.d2count / this.uploadImgTotal);
          document.getElementById('d2ring').style.strokeDashoffset = offset;
          document.getElementById('d2sub').textContent = `${this.d2count}/${this.uploadImgTotal}`;
          // this.d2count >= Math.floor(this.uploadImgTotal * (0.4 + Math.random() * 0.5))
          if (this.d2count >= Math.floor(this.uploadImgTotal * 0.9) && isFirst) {
            clearTimeout(this.d2timer);
            return;
          }
          this.runD2(delay, isFirst, callback);
        }, delay);
      } else {
        this.$nextTick(() => {
          document.getElementById(`dot0`).className = 'ring-dot active';
          document.getElementById('d2name').textContent = '正在上传。。。';
          this.d2count++;
          document.getElementById('d2pct').textContent = '50%';
          document.getElementById('d2ring').style.strokeDashoffset = 50;
          document.getElementById('d2sub').textContent = `0/${this.uploadImgTotal}`;
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.questionNamep {
  font-size: 16px;
  color: #484848;
  box-sizing: border-box;
  position: relative;

  .cameraDiv {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .photo {
      /*margin-top: 9px;*/
      float: right;
    }
    .camera {
      width: 60px;
      height: 100%;
      position: absolute;
      right: 0;
      top: 0;
      opacity: 0;
      z-index: 89;
    }
  }
}
#allmap {
  width: 10px;
  height: 10px;
  left: -1000px;
  position: absolute;
}
</style>
<style lang="scss">
/* ===== 样例2：圆形进度环 ===== */
.uploadImgDemoMask {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9998;
}
.uploadImgDemo {
  width: 95%;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  background: #fff;
  padding: 10px 5px;
  border-radius: 8px;
}
.uploadImgDemo .ring-area {
  display: none;
  // margin-top: 16px;
  align-items: center;
  gap: 20px;
}
.uploadImgDemo .ring-wrap {
  position: relative;
  width: 90px;
  height: 90px;
  flex-shrink: 0;
}
.uploadImgDemo .ring-wrap svg {
  transform: rotate(-90deg);
}
.uploadImgDemo .ring-bg {
  fill: none;
  stroke: #e0f7f4;
  stroke-width: 8;
}
.uploadImgDemo .ring-progress {
  fill: none;
  stroke: url(#greenGrad);
  stroke-width: 8;
  stroke-linecap: round;
  stroke-dasharray: 251.2;
  stroke-dashoffset: 251.2;
  transition: stroke-dashoffset 0.35s ease;
}
.uploadImgDemo .ring-text {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.uploadImgDemo .ring-pct {
  font-size: 18px;
  font-weight: 700;
  color: #11998e;
}
.uploadImgDemo .ring-sub {
  font-size: 10px;
  color: #aaa;
}
.uploadImgDemo .ring-info {
  flex: 1;
}
.uploadImgDemo .ring-filename {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 160px;
}
.uploadImgDemo .ring-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-top: 8px;
}
.uploadImgDemo .ring-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #e0e0e0;
  transition: background 0.3s;
}
.uploadImgDemo .ring-dot.done {
  background: #11998e;
}
.uploadImgDemo .ring-dot.active {
  background: #38ef7d;
  animation: pulse2 0.8s infinite;
}
@keyframes pulse2 {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.4);
  }
}
</style>
