<!--  -->
<template>
  <div class="addData_box" :style="'height:' + fullHeight + 'px'">
    <!-- 头部 -->
    <div class="addData_head">
      <div class="addData_head_returnA" @click="FanHui()">
        <img src="../../assets/image/left.png" alt class="addData_head_returnA_img" />
      </div>

      <!-- 标题 -->
      <div class="head_title">
        <span class="head_title_text">采集</span>
      </div>
    </div>

    <!-- 线 -->
    <div class="addData_segment"></div>
    <!-- 线 -->

    <!-- 主内容 -->
    <div class="addData_main">
      <!-- 输入作物或昆虫 -->
      <div class="radio_box" v-show="typeShow">
        <el-radio v-model="radio" label="plant">作物</el-radio>
        <el-radio v-model="radio" label="insect">昆虫</el-radio>
      </div>

      <!-- 科目 -->
      <div class="course_box">
        <el-input maxlength="25" v-model="course" placeholder="请输入您要填写的病虫害科目"></el-input>
        <div class="course_num">{{ this.course.length }} / 25</div>
      </div>
      <!-- 科目 -->

      <!-- 病虫害名称 -->
      <div class="insectName_box">
        <el-input maxlength="20" v-model="insectName" placeholder="请输入您要填写的病虫害名称"></el-input>
        <div class="insectName_num">{{ this.insectName.length }} / 20</div>
      </div>
      <!-- 病虫害名称 -->

      <!-- 内容input -->
      <div class="addData_IptBox">
        <el-input
          maxlength="200"
          type="textarea"
          :rows="10"
          placeholder="请输入该病虫害的详细描述"
          :onkeyup="textarea = textarea.replace(/\s+/g,'')"
          v-model="textarea"
        ></el-input>
        <div class="addData_IptNum">{{ this.textarea.length }} / 200</div>
      </div>
      <!-- 内容input -->

      <!-- 定位地址 -->
      <div class="orientationAddr_box">
        <img src="../../assets/image/ding.png" alt class="orientationAddr_img" />
        <div class="orientationAddr_text">{{ this.addr }}</div>
      </div>
      <!-- 定位地址 -->

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

      <!-- 删除按钮 -->
      <button @click="handleRemove" class="delBtn" v-show="delImage">删除图片</button>
      <!-- 上传图片 -->

      <!-- 发布 -->
      <button v-bind:class="{ 'nav-hide' : hideClass }" @click="bomNextBtn()" class="bomNextBtn">采集</button>
      <!-- 发布 -->
    </div>
    <!-- 主内容 -->
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  name: "addData",
  components: {},
  data() {
    //这里存放数据
    return {
      isClick: true, //点赞开关
      hideClass: false, //按钮被顶上去
      loading: false,
      fullHeight: document.documentElement.clientHeight,
      showHeight: document.documentElement.clientHeight, //按钮被顶上去
      textarea: "", //内容
      addImage: [], //图片
      delImage: false, //删除按钮
      imgLimit: "", //限制上传图片张数
      dialogVisible: false,
      dialogImageUrl: "",
      addr: localStorage.getItem("dizhi"), //地址
      radio: "plant", //作物或昆虫单选框
      course: "", //科目
      insectName: "", //病虫害名称
      typeShow: false, //判断是识别失败还是手动输入的进行隐藏、显示数据类型
      isClick: true //开关
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },
    //描述
    textarea(val) {
      // console.log(val);
    },
    //科目
    course(val) {
      this.course = this.course.replace(/[^A-Za-z0-9\u4e00-\u9fa5]/g, "");
    },
    //病虫害名称
    insectName(val) {
      this.insectName = this.insectName.replace(
        /[^A-Za-z0-9\u4e00-\u9fa5]/g,
        ""
      );
    },
    addImage(val) {
      if (val !== null) {
        this.delImage = true;
        this.loading = false;
      } else {
        this.delImage = false;
        this.loading = false;
      }
    },
    //按钮被顶上去
    showHeight: "inputType"
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    //返回主页
    FanHui() {
      //判断是识别失败进来的还是直接点击的手动输入
      if (localStorage.getItem("memoryCompileID") !== null) {
        //识别失败
        // this.$router.push("/memory");
        this.$router.replace("/memory");
        localStorage.removeItem("memoryCompileID");
        localStorage.removeItem("memoryDistinction");
      } else {
        //手动输入
        // this.$router.push("/person");
        this.$router.replace("/person");
      }
      localStorage.removeItem("add");
    },

    //上传图片-删除
    handleRemove() {
      //判断是识别失败进来的还是直接点击的手动输入
      if (localStorage.getItem("memoryCompileID") !== null) {
        let postData = this.$qs.parse({
          img_list: localStorage.getItem("add"),
          ret: this.radio
        });
        //识别失败
        return this.$confirm("确定要删除图片吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios({
              method: "post",
              url: "http://120.27.222.26:5555/del_insect_photo",
              data: postData
            })
              .then(res => {
                if (res.data === 0) {
                  this.$notify({
                    title: "成功",
                    message: "删除成功",
                    type: "success",
                    duration: 1500
                  });
                  this.$refs.upload.clearFiles();
                  localStorage.removeItem("add");
                } else if (res.data === 1) {
                  this.$notify.error({
                    title: "错误",
                    message: "删除失败",
                    duration: 1500
                  });
                }
              })
              .catch(error => {
                console.log(error);
              });
          })
          .catch(() => {
            throw new Error("取消成功！");
          });
      } else {
        let postData = this.$qs.parse({
          pic_list: localStorage.getItem("add"),
          ret: this.radio
        });
        //手动输入
        return this.$confirm("确定要删除图片吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios({
              method: "post",
              url: "http://120.27.222.26:5555/del_person_img",
              data: postData
            })
              .then(res => {
                if (res.data === 0) {
                  this.$notify({
                    title: "成功",
                    message: "删除成功",
                    type: "success",
                    duration: 1500
                  });
                  this.$refs.upload.clearFiles();
                  localStorage.removeItem("add");
                } else if (res.data === 1) {
                  this.$notify.error({
                    title: "错误",
                    message: "删除失败",
                    duration: 1500
                  });
                }
              })
              .catch(error => {
                console.log(error);
              });
          })
          .catch(() => {
            throw new Error("取消成功！");
          });
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传
    handleHttpRequest(file) {
      let _this = this;
      _this.loading = true;
      let form = new FormData();
      form.append("file", file.file);
      form.append("ret", _this.radio);

      //判断是识别失败进来的还是直接点击的手动输入
      if (localStorage.getItem("memoryCompileID") !== null) {
        _this.imgLimit = 1; //限制上传图片张数
        //识别失败
        _this
          .$axios({
            method: "post",
            url: "http://120.27.222.26:5555/upload_photos",
            anync: true,
            data: form,
            headers: {
              "Content-Type": "multipart/form-data"
            }
          })
          .then(res => {
            _this.addImage.push(res.data.news_photo);
            _this.btnShow = true;
            localStorage.setItem("add", _this.addImage);
          })
          .catch(error => {
            // console.log("222");
          });
      } else {
        _this.imgLimit = 3; //限制上传图片张数
        //手动输入
        _this
          .$axios({
            method: "post",
            url: "http://120.27.222.26:5555/person_harm_img",
            anync: true,
            data: form,
            headers: {
              "Content-Type": "multipart/form-data"
            }
          })
          .then(res => {
            _this.addImage.push(res.data.src);
            _this.btnShow = true;
            localStorage.setItem("add", _this.addImage);
          })
          .catch(error => {
            // console.log("222");
          });
      }
    },
    clearFiles() {
      // console.log("删除");
    },

    //发布
    bomNextBtn() {
      let _this = this;
      var isClick = _this.isClick;
      if (isClick === true) {
        _this.isClick = false;
        //判断input是否为空
        if (_this.textarea === "") {
          this.$notify({
            title: "警告",
            message: "请填写您分享的文字",
            type: "warning",
            duration: 1500
          });
        } else if (_this.course === "") {
          this.$notify({
            title: "警告",
            message: "请填写病虫害的科目",
            type: "warning",
            duration: 1500
          });
        } else if (_this.insectName === "") {
          this.$notify({
            title: "警告",
            message: "请填写病虫害名称",
            type: "warning",
            duration: 1500
          });
        } else if (localStorage.getItem("add") === null) {
          this.$notify({
            title: "警告",
            message: "请上传您分享的照片",
            type: "warning",
            duration: 1500
          });
        } else if (
          _this.textarea !== "" &&
          localStorage.getItem("add") !== null
        ) {
          //判断是识别失败进来的还是直接点击的手动输入
          if (localStorage.getItem("memoryCompileID") !== null) {
            //识别失败
            let postData = _this.$qs.parse({
              addr: localStorage.getItem("dizhi"), //地址
              lng: localStorage.getItem("jingdu"), //经度
              lat: localStorage.getItem("weidu"), //纬度
              img_urls: localStorage.getItem("add"), //
              content: _this.textarea, //描述信息
              name: _this.insectName, //病虫害名称
              ret: localStorage.getItem("memoryDistinction"), //病虫害区别
              course: _this.course, //科目
              id: localStorage.getItem("memoryCompileID") //id
            });
            _this
              .$axios({
                method: "post",
                url: "http://120.27.222.26:5555/make_data",
                data: postData
              })
              .then(res => {
                if (res.data === 0) {
                  this.$notify({
                    title: "成功",
                    message: "发布成功",
                    type: "success",
                    duration: 1500
                  });
                  //判断是识别失败进来的还是直接点击的手动输入
                  if (localStorage.getItem("memoryCompileID") !== null) {
                    //识别失败
                    this.$router.replace("/memory");
                    localStorage.removeItem("memoryCompileID");
                    localStorage.removeItem("commandIndex");
                    localStorage.setItem("commandLuru", "全部");
                  } else {
                    //手动输入
                    // this.$router.push("/home");
                    localStorage.setItem("commandIndex", "all");
                    localStorage.setItem("commandLuru", "全部");
                    this.$router.replace("/home");
                  }
                  const timeA = setInterval(() => {
                    location.reload();
                  }, 1500);
                } else if (res.data === 1) {
                  this.$notify.error({
                    title: "错误",
                    message: "发布失败，请重试",
                    duration: 1500
                  });
                }
              })
              .catch(err => {
                console.log(err);
              });
          } else {
            //手动输入
            let postData = _this.$qs.parse({
              addr: localStorage.getItem("dizhi"), //地址
              lng: localStorage.getItem("jingdu"), //经度
              lat: localStorage.getItem("weidu"), //纬度
              img_list: localStorage.getItem("add"), //
              problem: _this.textarea, //描述信息
              name: _this.insectName, //病虫害名称
              ret: _this.radio, //病虫害区别
              sort: _this.course //科目
            });
            _this
              .$axios({
                method: "post",
                url: "http://120.27.222.26:5555/save_disease",
                data: postData
              })
              .then(res => {
                if (res.data === 0) {
                  this.$notify({
                    title: "成功",
                    message: "发布成功",
                    type: "success",
                    duration: 1500
                  });
                  //判断是识别失败进来的还是直接点击的手动输入
                  if (localStorage.getItem("memoryCompileID") !== null) {
                    //识别失败
                    // this.$router.push("/memory");
                    this.$router.replace("/memory");
                    localStorage.removeItem("memoryCompileID");
                    localStorage.setItem("commandIndex", "all");
                    localStorage.setItem("commandLuru", "全部");
                  } else {
                    //手动输入
                    // this.$router.push("/home");
                    localStorage.setItem("commandIndex", "all");
                    localStorage.setItem("commandLuru", "全部");
                    this.$router.replace("/home");
                  }
                  const timeA = setInterval(() => {
                    location.reload();
                  }, 1500);
                } else if (res.data === 1) {
                  this.$notify.error({
                    title: "错误",
                    message: "发布失败，请重试",
                    duration: 1500
                  });
                }
              })
              .catch(err => {
                console.log(err);
              });
          }
        }
        setTimeout(function() {
          _this.isClick = true;
        }, 1500);
      }
    },

    //按钮被顶上去
    inputType() {
      if (!this.timer) {
        this.timer = true;
        let that = this;
        setTimeout(() => {
          if (that.fullHeight > that.showHeight) {
            //显示class
            this.hideClass = true;
          } else if (that.fullHeight <= that.showHeight) {
            //显示隐藏
            this.hideClass = false;
          }
          that.timer = false;
        }, 20);
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    var _this = this;
    //判断是识别失败进来的还是直接点击的手动输入
    if (localStorage.getItem("memoryCompileID") !== null) {
      //识别失败
      _this.typeShow = false;
    } else {
      //手动输入
      _this.typeShow = true;
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight();

    // window.onresize监听页面高度的变化
    window.onresize = () => {
      return (() => {
        window.screenHeight = document.body.clientHeight;
        this.showHeight = window.screenHeight;
      })();
    };
  }
};
</script>
<style lang='scss'>
@import "../../assets/scss/bus.scss";
@import "../../assets/scss/addData.scss";
</style>