<!--  -->
<template>
  <div class="addData_box">
    <!-- 页头 -->
    <!-- <el-header>
      <el-page-header title @back="goBack" content="识别数据添加"></el-page-header>
      <el-button type="text" @click="panduan()">
        <img src="../../assets/imageOne/24.png" alt class="addData_box-img" />
      </el-button>
    </el-header> -->

     <headStyle>
      <img src="../../assets/imageOne/left.png" @click="goBack" class="leftImage" alt="">
       <div class="headerTitle">识别数据添加</div>
      <el-button type="text" @click="panduan()">
        <img src="../../assets/imageOne/24.png" alt class="addData_box-img" />
      </el-button>
    </headStyle>

    <!-- 页面主内容 -->
    <el-main :style="'height:' + fullHeight + 'px'">
      <!-- 病害或虫害name -->
      <div class="addData_box_name">
        <!-- <span class="addData_box_name_title">病害或虫害名：</span> -->
        <span class="addData_box_name_title">{{ this.Name === "0" ? '虫害名称：' : '病害名称：' }}</span>
        <el-input clearable class v-model="inputName" placeholder="请输入内容"></el-input>
      </div>
      <!-- 病害或虫害name -->

      <!-- 科目或种类： -->
      <div class="addData_box_ke">
        <span class="addData_box_ke_title">科目：</span>
        <el-input clearable class v-model="inputKe" placeholder="请输入内容"></el-input>
      </div>
      <!-- 科目或种类： -->

      <!-- 地址： -->
      <div class="addData_box_ke">
        <span class="addData_box_ke_title">地址：</span>
        <el-input @blur="addr()" clearable class v-model="inputAdd" placeholder="请以X省X市X区的格式"></el-input>
      </div>
      <!-- 科目或种类： -->

      <!-- 上传图片 -->
      <div class="addData_box_up">
        <span class="addData_box_up_text">上传图片：</span>
        <el-upload
          ref="upload"
          action="/account_photo"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :http-request="handleHttpRequest"
          :limit="imgLimit"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>

        <!-- 删除 -->
        <el-button @click="delBtn()" type="primary" v-if="btnShow">删除图片</el-button>
      </div>
      <!-- 上传图片 -->

      <!-- 病害或虫害描述详情： -->
      <div class="addData_box_xiang">
        <span class="addData_box_xiang_title">{{ this.Name === "0" ? '虫害描述详情：' : '病害描述详情：' }}</span>
        <el-input
          :autosize="{ minRows: 8, maxRows: 8}"
          type="textarea"
          class
          v-model="inputXiang"
          placeholder="请输入内容"
        ></el-input>
      </div>
      <!-- 病害或虫害描述详情： -->
    </el-main>
  </div>
</template>

<script>  
function filterInputA(val) {
  // 这里过滤的是空格
  return val.replace(/\s+/g,'');
}
import headStyle from "../headStyle/headStyle"; //头部插件
export default {
  components: {
    headStyle
  },
  data() {
    //这里存放数据
    return {
      fullHeight: document.documentElement.clientHeight,
      inputName: "", //病害或虫害名
      inputKe: "", //科目或种类
      inputAdd: "", //地址
      inputXiang: "", //病害或虫害描述详情
      imgLimit: 1, //限制上传图片张数
      dialogVisible: false,
      dialogImageUrl: "",
      btnShow: false, //删除按钮显示隐藏
      Name: localStorage.getItem("biaoshi")
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },

    //病虫害名称
    inputName(val) {
       this.$nextTick(() => {
        this.inputName = filterInputA(val);
      });
    },
    //科目或种类
    inputKe(val) {
       this.$nextTick(() => {
        this.inputKe = filterInputA(val);
      });
    },
    //地址
    inputAdd(val) {
       this.$nextTick(() => {
        this.inputAdd = filterInputA(val);
      });
    },
     //病害或虫害描述详情
    inputXiang(val) {
       this.$nextTick(() => {
        this.inputXiang = filterInputA(val);
      });
    },
  },
  //方法集合
  methods: {
    //点击返回系统设置页面
    goBack() {
      let _this = this;
      // _this.$router.push("/record");
      _this.$router.replace("/record");
      localStorage.removeItem("addUrl");
      localStorage.removeItem("recordID");
      localStorage.removeItem("addDatalng");
      localStorage.removeItem("addDatalat");
      location.reload();
    },

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

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleHttpRequest(file) {
      //判断是虫害还是病害
      if (localStorage.getItem("biaoshi") === "1") {
        var a = "plant";
      } else if (localStorage.getItem("biaoshi") === "0") {
        var a = "insect";
      }
      let _this = this;
      let form = new FormData();
      form.append("filter", file.file);
      form.append("ret", a); //测试写为死数据
      _this
        .$axios({
          method: "post",
          url: "bigservers/upload_photos",
          anync: true,
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          localStorage.setItem("addUrl", res.data.news_photo);
          _this.btnShow = true;
        })
        .catch(error => {
          console.log(error);
        });
    },

    //判断必选项是否填写
    panduan() {
      let _this = this;
      if (_this.inputName === "") {
        this.$notify({
          title: "警告",
          message: "病害或虫害名不能为空",
          type: "warning",
          duration: 1000
        });
      } else if (_this.inputKe === "") {
        this.$notify({
          title: "警告",
          message: "科目或种类不能为空",
          type: "warning",
          duration: 1000
        });
      } else if (_this.inputXiang === "") {
        this.$notify({
          title: "警告",
          message: "病害或虫害描述不能为空",
          type: "warning",
          duration: 1000
        });
      } else if (_this.inputAdd === "") {
        this.$notify({
          title: "警告",
          message: "地址还未填写",
          type: "warning",
          duration: 1000
        });
      } else if (
        _this.inputXiang !== "" &&
        _this.inputKe !== "" &&
        _this.inputName !== ""
      ) {
        _this.Add();
        // _this.dizhi(); //发送地址给后端
      }
    },

    //保存数据
    Add() {
      let _this = this;
      //判断是虫害还是病害
      if (localStorage.getItem("biaoshi") === "1") {
        var a = "plant";
      } else if (localStorage.getItem("biaoshi") === "0") {
        var a = "insect";
      }

      //判断如果存入的经纬度为空
      if (
        localStorage.getItem("addDatalng") === null &&
        localStorage.getItem("addDatalat") === null
      ) {
        var b = "";
        var c = "";
      } else if (
        localStorage.getItem("addDatalng") !== null &&
        localStorage.getItem("addDatalat") !== null
      ) {
        var b = localStorage.getItem("addDatalng");
        var c = localStorage.getItem("addDatalat");
      }

      let postData = _this.$qs.parse({
        name: _this.inputName, //虫害还是病害名
        prevention: _this.inputXiang, //病害还是虫害描述详情
        course: _this.inputKe, //科目还是种类
        ret: a, //区分病害还是虫害
        photo: localStorage.getItem("addUrl"), //上传图片路径
        id: localStorage.getItem("recordID"),
        addr: _this.inputAdd, //地址
        lng: b, //经度
        lat: c, //纬度
        addr: _this.inputAdd //地址
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/make_data",
          data: postData
        })
        .then(res => {
          if (res.data === 1) {
            this.$notify({
              title: "成功",
              message: "保存成功",
              type: "success",
              duration: 1000
            });
            const timer = setInterval(() => {
              _this.goBack();
            }, 1500);
          } else if (res.data === 0) {
            this.$notify.error({
              title: "错误",
              message: "保存失败",
              duration: 1000
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    //删除图片
    delBtn() {
      let _this = this;
      //判断是虫害还是病害
      if (localStorage.getItem("biaoshi") === "1") {
        var a = "plant";
      } else if (localStorage.getItem("biaoshi") === "0") {
        var a = "insect";
      }

      let postData = _this.$qs.parse({
        photos: localStorage.getItem("addUrl"),
        ret: a
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/del_insect_photo",
          data: postData
        })
        .then(res => {
          if (res.data === 0) {
            this.$notify.error({
              title: "错误",
              message: "删除失败",
              duration: 1000
            });
          } else if (res.data === 1) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 1000
            });
            this.$refs.upload.clearFiles();
            _this.btnShow = false
            localStorage.removeItem("addUrl");
            // const timer = setInterval(() => {
            //   location.reload();
            // }, 1500);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    //地址input框失去焦点将地址转换为经纬度
    addr() {
      this.$axios({
        method: "get",
        url: "https://restapi.amap.com/v3/geocode/geo",
        params: {
          key: "e6c027a25208208ad19770f2b95580a1",
          address: this.inputAdd,
          output: JSON
        }
      })
        .then(res => {
          let aa = res.data.geocodes[0].location;
          let bb = new Array();
          bb = aa.split(",");
          localStorage.setItem("addDatalng", bb[0]); //经度
          localStorage.setItem("addDatalat", bb[1]); //纬度
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight();
  }
};
</script>
<style lang='scss'>
@import "../../assets/style/bus.scss";
@import "../../assets/style/scss/addData.scss";
</style>