<template>
  <div
    class="injuriousInsect-background injuriousInsect-box"
    :style="'height:' + fullHeight + 'px'"
  >
    <img src="../../../static/16.jpg" alt class="injuriousInsect-img1" />
    <!-- 页头 -->
    <div>
      <el-page-header class="injuriousInsect-el-page-header" title @back="goBack" content="虫害"></el-page-header>
    </div>

    <div class>
      <el-card class="box-card1" shadow="always">
        <!-- 识别图片 -->
        <div class="injuriousInsect-img">
          <el-upload
            class="avatar-uploader"
            action="/app_insect"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <div
              class="demo-image__preview"
              v-loading="loading"
              style="width: 100%; height: 5.5rem"
            >
              <el-image
                style="width: 100%; height: 5.5rem"
                :src="imageUrl"
                v-if="imageUrlA"
                preview
                preview-text="描述文字"
              ></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </div>
        <!-- 虚线 -->
        <div class="injuriousInsect-frame"></div>

        <div class="injuriousInsect-result">
          <div class="injuriousInsect-result-box">
            <img src="../../assets/imageOne/38.png" alt class="injuriousInsect-result-box-img" />
            <div class="injuriousInsect-txt">识别结果</div>
          </div>

          <div class="injuriousInsect-name">
            害虫名称：
            <span class="injuriousInsect-hai">{{this.textA}}</span>
            <span class="injuriousInsect-check" @click="dialogVisible = true" v-show="check">查看</span>
            <div class="injuriousInsect-hai-txt">{{this.textB| ellipsis}}</div>
          </div>
        </div>
      </el-card>

      <!-- 查看弹出框 -->
      <el-dialog title="详情" :visible.sync="dialogVisible" width="75%" :before-close="handleClose">
        <span>{{this.textB}}</span>
      </el-dialog>

      <!-- 圆 -->
      <div class="circle"></div>
      <div class="circle1"></div>

      <!-- 自动定位当前位置 -->
      <div class="selectAdress">
        <div class="selectAdressMain">
          <div class="amap-page-container">
            <div class="search-box border-bottom-1px"></div>
            <div class="amap-demos">
              <el-amap
                vid="amapDemo"
                :plugin="plugin"
                :center="center"
                :zoom="zoom"
                class="amap-demo"
                :events="events"
              >
                <el-amap-marker
                  v-for="(marker, index) in markers"
                  :key="marker.index"
                  :position="marker.position"
                  :animation="marker.animation"
                  :events="marker.events"
                  :vid="index"
                ></el-amap-marker>
                <el-amap-info-window
                  v-for="(marker, index) in markers"
                  :position="marker.position"
                  :content="sendPosition"
                  :key="index"
                ></el-amap-info-window>
              </el-amap>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传图片 -->
    <div class="v-simple-cropper">
      <slot></slot>
      <div class="v-cropper-layer" ref="layer">
        <div class="layer-header">
          <button class="cancel" @click="cancelHandle">取消</button>
          <button class="confirm" @click="confirmHandle">裁剪</button>
        </div>
        <img ref="cropperImg" />
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.min.css";

export default {
  name: "injuriousInsect",
  //限时数据文本的字数限时
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 100) {
        return value.slice(0, 100) + "...";
      }
      return value;
    }
  },
  data() {
    let self = this;
    return {
      imageUrl: "",
      imageUrlA: false,
      fullHeight: document.documentElement.clientHeight,
      textA: "", //识别txt名称
      textB: "", //识别txt详情
      check: false, //查看按钮
      dialogVisible: false, //查看弹出框状态
      loading: false, //加载
      tu: "", //用户选择的图片
      //自动定位地址
      sendPosition: "",
      searchOption: {
        city: "昆明",
        citylimit: false
      },
      center: [102.685, 25.00981],
      zoom: 12,
      markers: [
        {
          position: [102.685, 25.00981],
          animation: "AMAP_ANIMATION_DROP",
          events: {
            click(o) {
              // console.log("oooo", o);
            }
          }
        }
      ],
      plugin: [
        //一些工具插件
        {
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 100, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          extensions: "all",
          pName: "Geolocation", //定位
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.sendPosition = result.formattedAddress;
                  // console.log(self.sendPosition)
                  localStorage.setItem("location", result.formattedAddress); //把定位的地址存到本地
                  self.lng = result.position.lng; //设置经度
                  self.lat = result.position.lat; //设置维度
                  localStorage.setItem("shibieJing", result.position.lng); //经度
                  localStorage.setItem("shibieWei", result.position.lat); //纬度
                  self.center = [self.lng, self.lat]; //设置中心坐标
                  self.markers[0].position = [self.lng, self.lat];
                  self.loaded = true; //load
                  var geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                  });
                  geocoder.getAddress([self.lng, self.lat], function(
                    status,
                    result
                  ) {
                    if (status === "complete" && result.info === "OK") {
                      if (result && result.regeocode) {
                        self.loaded = true;
                        self.sendPosition = result.regeocode.formattedAddress;
                        self.$nextTick();
                      }
                    }
                  });
                  self.$nextTick(); //页面渲染好后
                }
              });
            }
          }
        },
        {
          pName: "ToolBar", //工具栏
          events: {
            init(instance) {
              // console.log('1111', instance)
            }
          }
        },
        {
          pName: "Scale", //比例尺
          events: {
            init(instance) {
              // console.log(instance)
            }
          }
        }
      ],
      //这是点击地图上的图标实现定位的事件
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          self.markers[0].position = [self.lng, self.lat];

          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                self.loaded = true;
                self.sendPosition = result.regeocode.formattedAddress;
                self.$nextTick();
              }
            }
          });
        }
      },
      lng: 0,
      lat: 0,
      loaded: false
    };
  },
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    }
  },
  mounted() {
    this.get_boderHeight();
    this.init(); //图片剪切
  },
  methods: {
    // 初始化裁剪插件
    init() {
      let cropperImg = this.$refs["cropperImg"];
      this.cropper = new Cropper(cropperImg, {
        viewMode: 1,
        dragMode: "none",
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: ".before",
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false
      });
    },

    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    goBack() {
      let _this = this;
      localStorage.removeItem("shibieWei");
      localStorage.removeItem("shibieJing");
      localStorage.removeItem("location");
      // _this.$router.push("/discern");
      _this.$router.replace("/discern");
    },

    //上传前
    beforeAvatarUpload(file) {
      let _this = this;
      this.fileA = file; //传递给data中
      this.filename = file["name"];
      let URL = window.URL || window.webkitURL;
      this.$refs["layer"].style.display = "block";
      this.cropper.replace(URL.createObjectURL(file));
      _this.loading = true;
      return false;
    },

    // 取消上传
    cancelHandle() {
      var _this = this
      _this.loading = false
      this.cropper.reset();
      this.$refs["layer"].style.display = "none";
      this.$refs["file"].value = "";
    },

    //上传
    confirmHandle() {
      let _this = this;
      this.$refs["layer"].style.display = "none";
      this.loadingShow = true;
      var fileA = this.cropper
        .getCroppedCanvas({
          imageSmoothingQuality: "high"
        })
        .toDataURL("image/jpeg");
      let blob = _this.dataURLtoFile(fileA, "image/jpeg"); //将base64转换为blob
      let data = _this.submitPic(blob); //再将blob转换为file
      var img = data.get("file");

      _this.tu = img;

      // _this
      //   .$axios({
      //     method: "post",
      //     url: "bigservers/app_insect",
      //     anync: true,
      //     data: form,
      //     headers: {
      //       "Content-Type": "multipart/form-data"
      //     }
      //   })
      //   .then(res => {
      //     if (res.data.code == 200 && res.data.data == null) {
      //       this.$message({
      //         showClose: true,
      //         message: "识别失败",
      //         type: "error",
      //         duration: 1000
      //       });
      //       _this.loading = false;
      //       _this.saveA();
      //     } else {
      //       _this.imageUrl = res.data.data[0].img_urls;
      //       _this.textA = res.data.data[0].name; //名称
      //       _this.loading = false;
      //       this.$notify({
      //         title: "成功",
      //         message: "识别成功",
      //         type: "success",
      //         duration: 1000
      //       });
      //       // 判断传来的数据中文字详情是否有数据
      //       if (res.data.data[0].prevention !== "[防治方法] null") {
      //         _this.check = true;
      //         _this.textB = res.data.data[0].prevention; //详情
      //       } else {
      //         _this.check = false;
      //         _this.textB = "暂无此类害虫资料,努力更新中...";
      //       }
      //       _this.imageUrlA = true;
      //       _this.save();
      //     }
      //   })
      //   .catch(error => {
      //     this.$message({
      //       type: "error",
      //       message: "识别失败!"
      //     });
      //     _this.saveA();
      //     _this.loading = true;
      //   });

      //虫害
      let form = new FormData();
      form.append("imageFile", img);
      form.append("imageType", "1");
      form.append("uniqueKey", "84e6eb40f3a616dd14b1fefc75425006");
      form.append("username", "yunfei");
      form.append("gis", "118.279643#31.221456");
      this.$axios({
        method: "post",
        url: "academysciences/recognizationSys/api/recognization",
        anync: true,
        data: form,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
        .then(res => {
          self.botNav = true; //隐藏底部导航
          if (
            res.data.msg === "识别失败_！" ||
            res.data.msg === "" ||
            res.data.data === null
          ) {
            this.$message({
              type: "error",
              message: "识别失败!"
            });
            _this.loading = false;
            _this.saveA();
          } else {
            _this.imageUrl = res.data.data[0].img_urls;
            _this.textA = res.data.data[0].name; //名称
            _this.loading = false;
            this.$notify({
              title: "成功",
              message: "识别成功",
              type: "success",
              duration: 1000
            });
            // 判断传来的数据中文字详情是否有数据
            if (res.data.data[0].prevention !== "[防治方法] null") {
              _this.check = true;
              _this.textB = res.data.data[0].prevention; //详情
            } else {
              _this.check = false;
              _this.textB = "暂无此类害虫资料,努力更新中...";
            }
            _this.imageUrlA = true;
            _this.save();
          }
        })
        .catch(error => {
          this.$message({
            type: "error",
            message: "识别失败!"
          });
          _this.saveA();
          _this.loading = true;
        });
    },

    //base64转为file类型
    //将base64转换为blob
    dataURLtoFile(dataURI, type) {
      let binary = atob(dataURI.split(",")[1]);
      let array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
    // 图片提交事件。把bold格式转为formData格式进行提交。
    submitPic(fileData) {
      let form = new FormData();
      let fileOfBlob = new File([fileData], new Date() + ".jpg"); // 重命名了
      form.append("file", fileOfBlob);
      return form;
    },

    //关闭查看弹框
    handleClose(done) {
      this.dialogVisible = false;
    },

    //给后端发送识别记录请求成功的情况下
    save() {
      let _this = this;
      //判断并分割科目类
      if (this.textB !== "[防治方法] null") {
        var f = this.textB.split("[科目类]");
        if (f.length === 1) {
          var c = "";
        } else if (f.length !== 1) {
          var c = this.textB.split("[科目类]")[1].split("[")[0];
        }
      } else {
        var c = "";
      }
      let form = new FormData();
      form.append("filte", this.tu);
      form.append("name", this.textA);
      form.append("prevention", this.textB);
      form.append("img_urls", this.imageUrl);
      form.append("lng", localStorage.getItem("shibieJing")); //经度
      form.append("lat", localStorage.getItem("shibieWei")); //纬度
      form.append("addr", localStorage.getItem("location")); //地址
      form.append("course", c);
      _this
        .$axios({
          method: "post",
          url: "bigservers/insect_record",
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {})
        .catch(error => {
          console.log(error);
          const timeA = setInterval(() => {
            location.reload();
          }, 1500);
        });
    },

    //给后端发送识别记录请求失败的情况下
    saveA() {
      let _this = this;
      let form = new FormData();
      form.append("filte", this.tu);
      form.append("name", "");
      form.append("prevention", "");
      form.append("img_urls", "");
      form.append("course", "");
      form.append("lng", localStorage.getItem("shibieJing")); //经度
      form.append("lat", localStorage.getItem("shibieWei")); //纬度
      form.append("addr", localStorage.getItem("location")); //地址
      _this
        .$axios({
          method: "post",
          url: "bigservers/insect_record",
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          const timeA = setInterval(() => {
            location.reload();
          }, 1500);
        })
        .catch(error => {
          console.log(error);
          const timeA = setInterval(() => {
            location.reload();
          }, 1500);
        });
    }
  }
};
</script>

<style lang="scss">
@import "../../assets/style/bus.scss";
@import "../../assets/style/scss/injuriousInsect.scss";
</style>


<style lang="less">
.v-simple-cropper {
  .file {
    display: none;
  }
  .v-cropper-layer {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    z-index: 99999;
    display: none;
    .layer-header {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99999;
      background: #fff;
      width: 100%;
      height: 1.2rem;
      padding: 0 0.2rem;
      box-sizing: border-box;
    }
    .cancel,
    .confirm {
      line-height: 1rem;
      font-size: 0.28rem;
      background: inherit;
      border: 0;
      outline: 0;
      float: left;
      font-size: 20px;
      color: red;
    }
    .confirm {
      float: right;
      font-size: 20px;
      color: blue;
    }
    img {
      position: inherit !important;
      border-radius: inherit !important;
      float: inherit !important;
    }
  }
}
</style> 