<!--  -->
<template>
  <div
    class="touristBox"
    style="'height:' + fullHeight + 'px'"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="tourist">
      <div class="tourist-tltBox">
        <img src="../../../static/touristA.png" alt class="tourist-tlt-img" />
        <div class="tourist-tlt-txt">游客暂只能使用识别功能</div>
        <img @click="outUser()" src="../../../static/out.png" alt class="xiaoxi_img" />
      </div>

      <div class="tourist-imgBox">
        <img src="../../../static/touristB.png" alt class="tourist-img-img" />
        <div class="tourist-img-txt">登录后更多功能等您使用</div>
      </div>

      <div class="tourist-btnBox">
        <button class="tourist-btnA" @click="dialogVisible = true">去识别</button>
        <button class="tourist-btnB" @click="touristlogin()">去登录</button>
      </div>
    </div>

    <!-- 识别功能弹框 -->
    <!-- 点击相机图标弹出选择昆虫或病害窗口 -->
    <el-dialog :modal-append-to-body="false" title="提示" :visible.sync="dialogVisible" width="60%">
      <span>请选择识别类型</span>
      <span slot="footer" class="dialog-footer">
        <!-- 选择昆虫 -->
        <div class="tourist_box_div">
          <!-- 测试 -->
          <el-button @click="dialogVisible = false, upload()" class="kunchongBtn">昆 虫</el-button>
          <img v-show="sHow" src="../../assets/upload.png" alt id="img" />
          <input
            class="hiddenInputA"
            ref="file"
            type="file"
            accept="image/*"
            @change="uploadChange"
          />
        </div>

        <!-- 选择病害 -->
        <div class="tourist_box_div">
          <!-- 测试 -->
          <el-button @click="dialogVisible = false, uploadA()" class="binghaiBtn">病 害</el-button>
          <img v-show="sHow" src="../../assets/upload.png" alt id="img" />
          <input
            class="hiddenInputA"
            ref="file"
            type="file"
            accept="image/*"
            @change="uploadChange"
          />
        </div>
      </span>
    </el-dialog>

    <!-- 上传图片 -->
    <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>

    <!-- loading -->
    <div v-if="loadingShow" class="loading_box" :style="'height:' + fullHeight + 'px'">
      <div class="loading_box_del" @click="loadingDel()">X</div>

      <div class="loading_box_div">
        <img src="../../../static/dongh.gif" alt class="loading_gif" />
        <div class="loading_text">识别中，请稍等...</div>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.min.css";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      loading: true, //页面加载
      sHow: false, //预览对象
      dialogVisible: false, //选择昆虫还是病害识别
      loadingShow: false, //请求等待动画
      fullHeight: document.documentElement.clientHeight,
      //上传
      cropper: null,
      filename: "",
      dialogVisible: false, //选择昆虫还是病害识别
      sHow: false, //预览对象
      fileA: "" //上传图片
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      that.loading = false;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // 测试图片剪裁-昆虫
    change(event) {
      let image = document.getElementById("img"); //预览对象
      this.clip(event, {
        resultObj: image,
        aspectRatio: 1
      });
      this.loadingShow = true;
    },

    // 测试图片剪裁-病害
    changeA(event) {
      let image = document.getElementById("img"); //预览对象
      this.clip(event, {
        resultObj: image,
        aspectRatio: 1
      });
      this.loadingShow = true;
    },

    //等待动画关闭按钮
    loadingDel() {
      this.loadingShow = false;
      location.reload();
    },
    //测试游客登录
    touristlogin() {
      this.$router.replace("/");
      location.reload();
      sessionStorage.removeItem("login");
      localStorage.removeItem("ret");
    },

    outUser() {
      this.$confirm("即将退出程序, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var webview = plus.webview.currentWebview(); //获取当前页面的
          plus.runtime.quit(); //退出应用
        })
        .catch(() => {
          console.log("点击取消");
        });
    },

    // 初始化裁剪插件
    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
      });
    },
    // 点击上传按钮-昆虫
    upload() {
      var _this = this;
      localStorage.setItem("insect", "昆虫"); //添加一个昆虫标识在本地
      localStorage.removeItem("plant"); //删除病害标识
      this.$refs["file"].click();
    },
    // 点击上传按钮-病害
    uploadA() {
      var _this = this;
      localStorage.setItem("plant", "病害"); // 添加一个病害标识在本地
      localStorage.removeItem("insect"); //删除昆虫标识
      this.$refs["file"].click();
    },
    // 取消上传
    cancelHandle() {
      this.cropper.reset();
      this.$refs["layer"].style.display = "none";
      this.$refs["file"].value = "";
    },
    // 选择上传文件
    uploadChange(e) {
      let file = e.target.files[0];
      this.fileA = file; //传递给data中
      this.filename = file["name"];
      let URL = window.URL || window.webkitURL;
      //判断当前识别次数是否有
      let postData = this.$qs.parse({
        name: sessionStorage.getItem("login"), //账号名字
        ret: localStorage.getItem("ret") //账号类型
      });
      this.$axios({
        method: "post",
        url: "bigservers/detect_number",
        data: postData
      })
        .then(res => {
          if (localStorage.getItem("ret") === "tourist") {
            if (res.data === 0) {
              this.$notify({
                title: "提示",
                message:
                  "抱歉，您的体验次数已用完；如果想再次使用，请先注册账号",
                type: "warning",
                duration: 3000
              });
            }
            if (res.data[0].num == "0") {
              this.$notify({
                title: "提示",
                message: "您的识别体验还剩下最后一次机会",
                type: "warning",
                duration: 3000
              });
              this.$refs["layer"].style.display = "block";
              this.cropper.replace(URL.createObjectURL(file));
            } else if (res.data[0].num < "5") {
              this.numData = res.data[0].num;
              this.$notify({
                title: "提示",
                message: "您的识别体验还剩" + this.numData + "次",
                type: "warning",
                duration: 2000
              });
              this.$refs["layer"].style.display = "block";
              this.cropper.replace(URL.createObjectURL(file));
            } else {
              this.$refs["layer"].style.display = "block";
              this.cropper.replace(URL.createObjectURL(file));
            }
          } else if (localStorage.getItem("ret") === "user") {
            if (res.data === 0) {
            } else if (res.data === 1) {
              this.$refs["layer"].style.display = "block";
              this.cropper.replace(URL.createObjectURL(file));
            }
          }
        })
        .catch(error => {
          console.log(error);
        });

      // this.$refs["layer"].style.display = "block";
      // this.cropper.replace(URL.createObjectURL(file));
    },
    //上传
    confirmHandle() {
      let _this = this;
      _this.base();
      //获取图片的ba64编码
      this.cropper.reset();
      this.$refs["layer"].style.display = "none";
      this.loadingShow = true;
      // 判断用户选择的病害还是昆虫;
      if (localStorage.getItem("insect") !== null) {
        //虫害
        let form = new FormData();
        form.append("img_addr", _this.fileA);
        this.$axios({
          method: "post",
          url: "bigservers/app_insect",
          anync: true,
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
          .then(res => {
            self.botNav = true; //隐藏底部导航
            // window.clearInterval(timer);  //销毁计时器
            if (
              res.data.msg === "识别失败_！" ||
              res.data.msg === "" ||
              res.data.data === null
            ) {
              this.$message({
                type: "error",
                message: "识别失败!"
              });

              this.$router.push({
                name: "show",
                params: { data: form.get("img_addr") }
              });
              localStorage.setItem("recordID", "1");
              this.loadingShow = false;
            } else {
              this.$notify({
                title: "成功",
                message: "识别成功",
                type: "success"
              });
              localStorage.setItem(
                "axiosData",
                JSON.stringify(res.data.data[0])
              );
            }
            this.$router.push({
              name: "show",
              params: { data: form.get("img_addr") }
            });
            localStorage.setItem("recordID", "1");
            this.loadingShow = false;
            this.$refs["file"].value = "";
          })
          .catch(error => {
            // window.clearInterval(timer);  //销毁计时器
            this.$message({
              type: "error",
              message: "识别失败!"
            });
            this.$router.push({
              name: "show",
              params: { data: form.get("img_addr") }
            });
            localStorage.setItem("recordID", "1");
            this.loadingShow = false;
            this.$refs["file"].value = "";
          });
      } else if (localStorage.getItem("plant") !== null) {
        //病害
        let form = new FormData();
        form.append("img_addr", _this.fileA);
        this.$axios({
          method: "post",
          url: "bigservers/app_plant",
          anync: true,
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
          .then(res => {
            _this.botNav = true; //隐藏底部导航
            if (
              res.data.msg === "识别失败_! " ||
              res.data.msg === "" ||
              res.data.data === null
            ) {
              this.$message({
                type: "error",
                message: "识别失败!"
              });
              _this.botNav = false; //隐藏底部导航

              this.$router.push({
                name: "show",
                params: { data: form.get("img_addr") }
              });
              localStorage.setItem("recordID", "1");
            } else {
              this.$notify({
                title: "成功",
                message: "识别成功",
                type: "success"
              });
              localStorage.setItem(
                "axiosData",
                JSON.stringify(res.data.data[0])
              );
            }
            this.$router.push({
              name: "show",
              params: { data: form.get("img_addr") }
            });
            localStorage.setItem("recordID", "1");
            this.loadingShow = false;
            this.$refs["file"].value = "";
          })
          .catch(error => {
            this.$message({
              type: "error",
              message: "识别失败aaaaaaa!"
            });
            this.$router.push({
              name: "show",
              params: { data: form.get("img_addr") }
            });
            localStorage.setItem("recordID", "1");
            this.loadingShow = false;
            this.$refs["file"].value = "";
          });
      }
    },
    base() {
      var _this = this;
      var files = _this.fileA;
      if (files) {
        var file = files;
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function() {
          img.src = this.result;
        };
        var img = new Image(),
          width = 1024, //image resize   压缩后的宽
          quality = 0.8, //image quality  压缩质量
          canvas = document.createElement("canvas"),
          drawer = canvas.getContext("2d");
        img.onload = function() {
          canvas.width = width;
          canvas.height = width * (img.height / img.width);
          drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
          var base64 = canvas.toDataURL("image/jpeg", quality); // 这里就拿到了压缩后的base64图片
          console.log(base64);
          localStorage.setItem("ba64dataA", base64);
        };
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init(); //图片剪切
    this.get_boderHeight();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss'>
//@import url(); 引入公共css类
@import "../../assets/scss/bus.scss";
@import "../../assets/scss/tourist.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: 0.8rem;
      padding: 0 0.2rem;
      box-sizing: border-box;
    }
    .cancel,
    .confirm {
      line-height: 0.8rem;
      font-size: 0.28rem;
      background: inherit;
      border: 0;
      outline: 0;
      float: left;
    }
    .confirm {
      float: right;
    }
    img {
      position: inherit !important;
      border-radius: inherit !important;
      float: inherit !important;
    }
  }
}
</style> 