<!--  -->
<template>
  <div
    :style="'height:' + fullHeight + 'px'"
    class="screen_plant-box"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <!-- 页面头部 -->
    <el-header>
      <el-page-header title @back="goBack()" content="作物选择"></el-page-header>
      <button class="screen_plant-box-qued" @click="confirm()">确定</button>
    </el-header>

    <!-- 页面主内容 -->
    <el-main :style="'height:' + fullHeight + 'px'">
      <!-- 粮食作物 -->
      <div class="screen_plant-cerealsbox interval">
        <!-- 标题 -->
        <div class="screen_plant-cerealstlt">
          <div class="screen_plant-cerealstlt-line"></div>
          <div class="screen_plant-cerealstlt-txt">粮食作物</div>

          <el-button type="text" @click="dialogFormVisible = true,kunchong()">
            <img src="../../assets/imageOne/plant_add.png" alt class="screen_plant-cerealstlt-img" />
          </el-button>
        </div>

        <!-- 列表 -->
        <ul class="screen_plant-cerealsUL" v-if="liangshiShow">
          <li
            class="screen_plant-cerealsli"
            v-show="item.crop_sort == '1'"
            v-for="(item, index) in this.redata"
            @click="addShow($event, index), dowm(index)"
            :class="active == index ? 'addclassA' : '' "
            :key="index"
          >
            <!-- <img src="../../assets/plantImg/pitch.png" alt="" class="screen_plant-cerealsli-pitch"> -->
            <div class="screen_plant-cerealsliBox">
              <img src="../../assets/plantImg/cereals.png" alt class="screen_plant-cerealsli-imgA" />
              <div class="screen_plant-cerealsli-text">{{item.pest}}</div>
            </div>
          </li>
        </ul>

        <!-- 暂无数据 -->
        <div class="screen_plant-cereals-nodataBox" v-else>
          <img src="../../assets/plantImg/wu.png" alt class="screen_plant-cereals-nodataImg" />
          <div class="screen_plant-cereals-nodataText">暂无粮食作物数据</div>
        </div>
      </div>

      <!-- 林业 -->
      <div class="screen_plant-cerealsbox">
        <!-- 标题 -->
        <div class="screen_plant-cerealstlt">
          <div class="screen_plant-cerealstlt-line"></div>
          <div class="screen_plant-cerealstlt-txt">林业</div>
          <el-button type="text" @click="dialogFormVisible = true,kunchongA()">
            <img src="../../assets/imageOne/plant_add.png" alt class="screen_plant-cerealstlt-img" />
          </el-button>
          <!-- <img src="../../assets/imageOne/plant_add.png" alt class="screen_plant-cerealstlt-img" /> -->
        </div>

        <!-- 列表 -->
        <ul class="screen_plant-cerealsUL" v-if="linyeShow">
          <li
            class="screen_plant-cerealsli"
            v-show="item.crop_sort == '3'"
            v-for="(item, index) in this.redata"
            @click="addShow($event, index), dowm(index)"
            :class="active == index ? 'addclassA' : '' "
            :key="index"
          >
            <div class="screen_plant-cerealsliBox">
              <img src="../../assets/plantImg/forest.png" alt class="screen_plant-cerealsli-imgA" />
              <div class="screen_plant-cerealsli-text">{{item.pest}}</div>
            </div>
          </li>
        </ul>

        <!-- 暂无数据 -->
        <div class="screen_plant-cereals-nodataBox" v-else>
          <img src="../../assets/plantImg/wu.png" alt class="screen_plant-cereals-nodataImg" />
          <div class="screen_plant-cereals-nodataText">暂无林业数据</div>
        </div>
      </div>

      <!-- 经济作物 -->
      <div class="screen_plant-cerealsbox">
        <!-- 标题 -->
        <div class="screen_plant-cerealstlt">
          <div class="screen_plant-cerealstlt-line"></div>
          <div class="screen_plant-cerealstlt-txt">经济作物</div>
          <el-button type="text" @click="dialogFormVisible = true,kunchongB()">
            <img src="../../assets/imageOne/plant_add.png" alt class="screen_plant-cerealstlt-img" />
          </el-button>
          <!-- <img src="../../assets/imageOne/plant_add.png" alt class="screen_plant-cerealstlt-img" /> -->
        </div>

        <!-- 列表 -->
        <ul class="screen_plant-cerealsUL" v-if="jingjiShow">
          <li
            class="screen_plant-cerealsli"
            v-show="item.crop_sort == '2'"
            v-for="(item, index) in this.redata"
            @click="addShow($event, index), dowm(index)"
            :class="active == index ? 'addclassA' : '' "
            :key="index"
          >
            <div class="screen_plant-cerealsliBox">
              <img
                src="../../assets/plantImg/economics.png"
                alt
                class="screen_plant-cerealsli-imgA"
              />
              <div class="screen_plant-cerealsli-text">{{item.pest}}</div>
            </div>
          </li>
        </ul>

        <!-- 暂无数据 -->
        <div class="screen_plant-cereals-nodataBox" v-else>
          <img src="../../assets/plantImg/wu.png" alt class="screen_plant-cereals-nodataImg" />
          <div class="screen_plant-cereals-nodataText">暂无经济作物数据</div>
        </div>
      </div>
    </el-main>

    <!-- 添加框 -->
    <el-dialog
      :title="this.titleNameA"
      :visible.sync="dialogFormVisible"
      :before-close="handleCloseA"
    >
      <el-form :model="form">
        <el-form-item label :label-width="formLabelWidth">
          <el-input v-model.trim="form.chongmeg" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false,cancel()">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false,add()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加框 -->
  </div>
</template>

<script>
export default {
  name: "screen_plant",
  components: {},
  data() {
    //这里存放数据
    return {
      isClick: true,
      //添加弹框
      dialogFormVisible: false,
      titleNameA: "",
      form: {
        chongmeg: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        userList: ""
      },
      type: "", //作物类型
      formLabelWidth: "120px",
      //数据数组
      redata: [],
      //粮食作物
      liangshiShow: false,
      current: "",
      active: localStorage.getItem("screenIndex"),
      //林业判断
      linyeShow: false,
      //经济作物
      jingjiShow: false,
      fullHeight: document.documentElement.clientHeight,
      loading: 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);
      }
    }
  },
  //方法集合
  methods: {
    // 返回
    goBack() {
      let _this = this;
      if (localStorage.getItem("defaultID") !== null) {
        // _this.$router.push("/acquiescent");
        _this.$router.replace("/acquiescent");
      } else {
        // _this.$router.push("/newmessage");
        _this.$router.replace("/newmessage");
      }
    },

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

    //请求当前页面数据
    listData() {
      let _this = this;
      //判断当前是新建还是默认、
      if (localStorage.getItem("monthID") !== null) {
        //新建
        var postData = _this.$qs.stringify({
          ret: "harm",
          month_id: localStorage.getItem("monthID"),
          pest_sort: localStorage.getItem("radioData")
        });
      } else if (localStorage.getItem("yfenID") !== null) {
        if (localStorage.getItem("yuefenID") !== null) {
          var postData = _this.$qs.stringify({
            ret: "harm",
            month_id: localStorage.getItem("yuefenID"),
            pest_sort: localStorage.getItem("defaultType")
          });
        } else {
          var postData = _this.$qs.stringify({
            ret: "harm",
            month_id: localStorage.getItem("yfenID"),
            pest_sort: localStorage.getItem("defaultType")
          });
        }
      }
      _this
        .$axios({
          method: "post",
          url: "bigservers/city",
          data: postData,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        })
        .then(res => {
          _this.loading = false;
          for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].crop_sort === "1") {
              //粮食作物
              _this.liangshiShow = true;
            } else if (res.data[i].crop_sort === "2") {
              //经济作物
              _this.jingjiShow = true;
            } else if (res.data[i].crop_sort === "3") {
              //林业
              _this.linyeShow = true;
            }
          }

          _this.redata = res.data;
        })
        .catch(err => {
          console.log(err);
        });
    },

    //作物选择事件委托
    addShow(e, index) {
      let _this = this;
      if (
        e.target.className === "screen_plant-cerealsliBox" ||
        e.target.className === "screen_plant-cerealsli-imgA" ||
        e.target.className === "screen_plant-cerealsli-text"
      ) {
        _this.current = index;
        localStorage.setItem("screenIndex", this.current); //存index数据
        //获取点击对象
        let el = e.currentTarget;
        let listType = _this.redata[index].crop_sort; //作物选择类型
        let listPest = _this.redata[index].pest; //作物
        console.log(listType);
        console.log(listPest);
        localStorage.setItem("plantType", listType);
        localStorage.setItem("plantName", listPest);
      }
    },
    //作物作物选择
    dowm(index) {
      //将点击的元素的索引赋值给变量
      this.active = index;
      console.log(this.active);
    },

    //弹出框右上角关闭按钮回调
    handleCloseA() {
      let _this = this;
      _this.dialogFormVisible = false;
      _this.cancel();
    },
    //取消按钮
    cancel() {
      let _this = this;
      _this.form.chongmeg = "";
    },
    //粮食作物
    kunchong() {
      let _this = this;
      _this.dialogFormVisible = true;
      _this.dialogVisible = false;
      _this.titleNameA = "粮食作物添加";
    },
    //林业
    kunchongA() {
      let _this = this;
      _this.dialogFormVisible = true;
      _this.dialogVisible = false;
      _this.titleNameA = "林业作物添加";
    },
    //经济作物
    kunchongB() {
      let _this = this;
      _this.dialogFormVisible = true;
      _this.dialogVisible = false;
      _this.titleNameA = "经济作物添加";
    },

    //添加向后端上传数据
    add() {
      let _this = this;
      //判断是新建还是默认
      if (localStorage.getItem("monthID") !== null) {
        var month = localStorage.getItem("monthID");
      } else if (localStorage.getItem("yfenID") !== null) {
        if (localStorage.getItem("yuefenID") !== null) {
          var month = localStorage.getItem("yuefenID");
        } else {
          var month = localStorage.getItem("yfenID");
        }
      }

      var isClick = _this.isClick;
      if (isClick === true) {
        _this.isClick = false;
        // 判断是添加到昆虫种类还是昆虫名称;
        if (_this.form.chongmeg !== "" && _this.titleNameA === "粮食作物添加") {
          let postData = _this.$qs.stringify({
            pest: _this.form.chongmeg, //添加的作物名字
            crop_sort: "1", //作物类型
            ret: "crea",
            month_id: month, //月份
            pest_sort: localStorage.getItem("radioData")
          });
          _this
            .$axios({
              method: "post",
              url: "bigservers/city",
              data: postData,
              headers: {
                "Content-Type": "application/x-www-form-urlencoded"
              }
            })
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "添加成功!",
                  duration: 1500
                });
                _this.listData(); //重新请求数据
                // const timer = setInterval(() => {
                //   location.reload();
                // }, 1000);
              } else if (res.data.code == null) {
                this.$message({
                  type: "warning",
                  message: "数据已存在!",
                  duration: 1500
                });
              }
              _this.cancel();
            })
            .catch(error => {
              this.$message({
                showClose: true,
                message: "失败",
                type: "error",
                duration: 1500
              });
            });
        } else if (
          _this.form.chongmeg !== "" &&
          _this.titleNameA === "林业作物添加"
        ) {
          let postData = _this.$qs.stringify({
            pest: _this.form.chongmeg, //添加的作物名字
            crop_sort: "3", //作物类型
            ret: "crea",
            month_id: month, //月份
            pest_sort: localStorage.getItem("radioData")
          });
          _this
            .$axios({
              method: "post",
              url: "bigservers/city",
              data: postData,
              headers: {
                "Content-Type": "application/x-www-form-urlencoded"
              }
            })
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "添加成功!",
                  duration: 1500
                });
                _this.listData(); //重新请求数据
              } else if (res.data.code == null) {
                this.$message({
                  type: "warning",
                  message: "数据已存在!",
                  duration: 1500
                });
              }
              _this.cancel();
            })
            .catch(error => {
              this.$message({
                showClose: true,
                message: "失败",
                type: "error",
                duration: 1500
              });
            });
        } else if (
          _this.form.chongmeg !== "" &&
          _this.titleNameA === "经济作物添加"
        ) {
          let postData = _this.$qs.stringify({
            pest: _this.form.chongmeg, //添加的作物名字
            crop_sort: "2", //作物类型
            ret: "crea",
            month_id: month, //月份
            pest_sort: localStorage.getItem("radioData")
          });
          _this
            .$axios({
              method: "post",
              url: "bigservers/city",
              data: postData,
              headers: {
                "Content-Type": "application/x-www-form-urlencoded"
              }
            })
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "添加成功!",
                  duration: 1500
                });
                _this.listData(); //重新请求数据
              } else if (res.data.code == null) {
                this.$message({
                  type: "warning",
                  message: "数据已存在!",
                  duration: 1500
                });
              }
              _this.cancel();
            })
            .catch(error => {
              this.$message({
                showClose: true,
                message: "失败",
                type: "error",
                duration: 1500
              });
            });
        } else if (_this.form.chongmeg === "") {
          this.$message({
            type: "warning",
            message: "不能为空!",
            duration: 1500
          });
        }

        setTimeout(function() {
          _this.isClick = true;
        }, 1500);
      }
    },

    //选择作物确定
    confirm() {
      let _this = this;
      //判断当前数据是新建还是默认编辑
      if (localStorage.getItem("defaultID") !== null) {
        if (localStorage.getItem("yfenID") !== null) {
          //默认编辑
          var postData = _this.$qs.stringify({
            ret: "details",
            harm_name: localStorage.getItem("plantName"), //作物名称
            pest_sort: localStorage.getItem("defaultType"), //作物类型
            month_id: localStorage.getItem("yfenID") //月份ID
          });
        } else if (localStorage.getItem("yuefenID") !== null) {
          //默认编辑
          var postData = _this.$qs.stringify({
            ret: "details",
            harm_name: localStorage.getItem("plantName"), //作物名称
            pest_sort: localStorage.getItem("defaultType"), //作物类型
            month_id: localStorage.getItem("yuefenID") //月份ID
          });
        }
      } else {
        //新建
        var postData = _this.$qs.stringify({
          ret: "details",
          harm_name: localStorage.getItem("plantName"), //作物名称
          pest_sort: localStorage.getItem("radioData"), //作物类型
          month_id: localStorage.getItem("monthID") //月份ID
        });
      }
      var isClick = _this.isClick;
      if (isClick === true) {
        _this.isClick = false;
        //判断当前是否选择了作物
        if (
          localStorage.getItem("screenIndex") !== null &&
          localStorage.getItem("plantName") !== null
        ) {
          _this
            .$axios({
              url: "bigservers/city",
              method: "post",
              data: postData,
              headers: {
                "Content-Type": "application/x-www-form-urlencoded"
              }
            })
            .then(res => {
              // if (res.data.code !== null) {
              this.$message({
                type: "success",
                message: "选择成功!",
                duration: 1500
              });

              //判断当前是默认编辑还是新建
              if (localStorage.getItem("defaultID") !== null) {
                var aa = JSON.stringify(res.data);
                localStorage.setItem("pestName", aa);
                //默认编辑
                // _this.$router.push("/acquiescent");
                _this.$router.replace("/acquiescent");
              } else {
                var aa = JSON.stringify(res.data);
                localStorage.setItem("pestName", aa);
                //新建
                //判断是跳转到病害还是虫害
                if (localStorage.getItem("radioData") == "1") {
                  //病害
                  // _this.$router.push("/secondstep");
                  // _this.$router.push("/newmessage");
                  _this.$router.replace("/newmessage");
                  location.reload();
                } else if (localStorage.getItem("radioData") == "2") {
                  //虫害
                  // _this.$router.push("/insect");
                  // _this.$router.push("/newmessage");
                  _this.$router.replace("/newmessage");
                  location.reload();
                }
              }
            })
            .catch(err => {});
        } else {
          this.$notify.error({
            title: "错误",
            message: "请先选择作物再进行下一步",
            duration: 1500
          });
        }

        setTimeout(function() {
          _this.isClick = true;
        }, 1500);
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    //判断当前是否有存index数据
    if (localStorage.getItem("screenIndex") === null) {
      localStorage.setItem("screenIndex", -1);
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight();
    this.listData(); //请求当前数据
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss'>
@import "../../assets/style/bus.scss";
@import "../../assets/style/scss/screen_plant.scss";
</style>