<template>
  <div class="insect-box" :style="'height:' + fullHeight + 'px'">
    <!-- 页头 -->
    <el-header>
      <el-page-header @back="goBack" title content="虫害"></el-page-header>
      <el-button type="primary" class="pathology-btn1" @click="judge()">完成</el-button>
    </el-header>

    <!-- 页面主内容 -->
    <el-main :style="'height:' + fullHeight + 'px'">
      <!-- 主内容列表 -->
      <ul class="insect-ul">
        <!-- 虫害名称 -->
        <li class="insect-li">
          <img src="../../assets/plantImg/addr.png" alt class="insect-li-imgone dandu" />
          <div class="insect-li-div">
            <div>
              <div class="insect-li-divone danoneA">虫害名称</div>
            </div>

            <!-- 测试 -->
            <div class="insect-li-input">
              <el-input
                type="text"
                :rows="10"
                placeholder="输入要添加的虫害名称"
                v-model.trim="inputInsect"
                clearable
                @blur="animateWidthB()"
              ></el-input>
            </div>
          </div>
        </li>
        <!-- 虫害名称 -->

        <!-- 虫害名称 -->
        <li class="insect-li">
          <img src="../../assets/imageOne/insect.png" alt class="insect-li-imgone dandu" />
          <div class="insect-li-div">
            <div class="insect-li-divone danoneA">虫害名称</div>
            <el-cascader
              :options="optionsB"
              v-model="valueA"
              placeholder="请选择虫害种类"
              @change="resultB($event)"
              class="content insectName"
            ></el-cascader>
          </div>
        </li>

        <!-- 生育期 -->
        <li class="insect-li">
          <img src="../../assets/imageOne/raise.png" alt class="insect-li-imgone dandu" />
          <div class="insect-li-div">
            <div>
              <div class="insect-li-divone danoneA">生育期</div>
            </div>

            <!-- 测试 -->
            <div class="insect-li-input">
              <el-input
                @blur="animateWidthC()"
                v-bind:disabled="disabledInput"
                type="text"
                :rows="10"
                placeholder="请输入生育期"
                v-model.trim="inputC"
                clearable
              ></el-input>
            </div>
          </div>
        </li>
        <!-- 生育期 -->

        <!-- 统计方法 -->
        <li class="insect-li">
          <img src="../../assets/imageOne/danwei.png" alt class="insect-li-imgone dandu2" />
          <div class="insect-li-div danxuan">
            <div class="insect-li-divone danxuan2">统计方法</div>
            <!-- 测试 -->
            <el-cascader v-model="value" :options="options" @change="handleChange"></el-cascader>
            <!-- 测试 -->
          </div>
        </li>

        <!-- 作物数量 -->
        <li class="insect-li">
          <img src="../../assets/imageOne/number.png" alt class="insect-li-imgone dandu3" />
          <div class="insect-li-div">
            <div>
              <div class="insect-li-divone shuliang">作物数量</div>
            </div>

            <!-- 测试 -->
            <div class="insect-li-input">
              <el-input
                type="number"
                :rows="10"
                placeholder="只能输入数字"
                v-model.trim="inputA"
                @blur="animateWidthA()"
                @focus="animateWidth()"
                clearable
              ></el-input>
            </div>
            <!-- 测试 -->
          </div>
        </li>

        <!--  -->
        <li class="insect-li ceshi">
          <img src="../../assets/imageOne/dingwei.png" alt class="insect-li-imgone dandu" />
          <div class="insect-li-div">
            <div class="insect-li-divone danone">上传图片</div>

            <!-- 删除 -->
            <el-button @click="delBtn()" type="primary" v-if="btnShow">删除</el-button>
          </div>
          <div class="shangchuan_box">
            <el-upload
              ref="upload"
              action="/account_photo"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :http-request="handleHttpRequest"
              :on-remove="handleRemove"
              :limit="imgLimit"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </div>
        </li>

        <!-- 虫害级别 -->
        <li class="insect-li bgji">
          <img src="../../assets/imageOne/insect.png" alt class="insect-li-img" />
          <div class="insect-li-div">
            <div class="insect-li-text bingji">虫级</div>
            <div class="insect-div-box">
              <div class="insect-text-box">
                <span class="insect-text-box-span">(1)卵:</span>
                <input type="number" placeholder class="insect-inputX" v-model.number="input1" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span">(2)蛹:</span>
                <input type="number" placeholder class="insect-inputX" v-model.number="input2" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-one">(3)幼虫:</span>
                <input type="number" placeholder class="insect-inputE" v-model.number="input3" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-one">(4)落虫:</span>
                <input type="number" placeholder class="insect-inputE" v-model.number="input4" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-two">(5)齡雄虫1:</span>
                <input type="number" placeholder class="insect-inputA" v-model.number="input5" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-two">(6)齡雄虫2:</span>
                <input type="number" placeholder class="insect-inputA" v-model.number="input6" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-two">(7)齡雄虫3:</span>
                <input type="number" placeholder class="insect-inputA" v-model.number="input7" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-two">(8)齡雄虫4:</span>
                <input type="number" placeholder class="insect-inputA" v-model.number="input8" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-two">(9)齡雄虫5:</span>
                <input type="number" placeholder class="insect-inputA" v-model.number="input9" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(10)齡雄虫6:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input10" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(11)齡雌虫1:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input11" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(12)齡雌虫2:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input12" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(13)齡雌虫3:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input13" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(14)齡雌虫4:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input14" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(15)齡雌虫5:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input15" />
              </div>
              <div class="insect-text-box">
                <span class="insect-text-box-span-three">(16)齡雌虫6:</span>
                <input type="number" placeholder class="insect-inputB" v-model.number="input16" />
              </div>
            </div>
          </div>
        </li>
      </ul>
    </el-main>

    <!-- 添加病虫害名称提示框 -->
    <el-dialog
      title="虫害名称添加"
      :visible.sync="dialogVisibleA"
      width="7rem"
      :before-close="handleClose"
    >
      <span>如是否添加{{this.inputInsect}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleA = false, delPlant()">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleA = false, addPlant($event)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "insect",
  data() {
    return {
      disabledInput: true, //生育期input框是否禁用
      valueA: "", //病害名称数据
      inputInsect: "", //添加虫害名称
      dialogVisibleA: false, //虫害名称提示框
      show: true,
      bingType: "", //虫害名称-新建
      newdata: localStorage.newdata, //昆虫种类-新建
      fullHeight: document.documentElement.clientHeight,
      iptlistA: JSON.parse(localStorage.getItem("iptList")), //病虫害值从后端接收的数据
      area: [], //作物数量单位和数字
      crop: [], //作物数量单位和数字
      //统计方法
      value: [],
      options: [
        {
          value: "面积大小",
          label: "面积大小",
          children: [
            {
              value: "平方米",
              label: "平方米"
            },
            {
              value: "亩",
              label: "亩"
            }
          ]
        },
        {
          value: "作物数量",
          label: "作物数量",
          children: [
            {
              value: "株数",
              label: "株数"
            },
            {
              value: "叶数",
              label: "叶数"
            }
          ]
        }
      ],
      inputA: "", //数字
      inputC: "", //昆虫名称
      //虫级
      input1: "0",
      input2: "0",
      input3: "0",
      input4: "0",
      input5: "0",
      input6: "0",
      input7: "0",
      input8: "0",
      input9: "0",
      input10: "0",
      input11: "0",
      input12: "0",
      input13: "0",
      input14: "0",
      input15: "0",
      input16: "0",
      insectName: false, //判断昆虫种类和名称是否显示
      dialogImageUrl: "",
      dialogVisible: false,
      add: [],
      btnShow: false, //删除按钮显示隐藏
      imgLimit: 3, //限制上传图片张数
      //三级联动
      props: {
        value: "sort",
        label: "sort",
        children: "lower"
      },
      optionsA: [],
      selectedOptions: "",
      //昆虫种类
      propsB: {
        value: "insect_type",
        label: "insect_type"
      },
      optionsB: [],
      selectedOptionsB: "",
    };
  },
  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.confirm();
    //作物种类数据
    // this.optionsB = JSON.parse(localStorage.getItem("pestName"));
  },
  computed: {},
  created() {
    let _this = this;
    //请求三级联动的数据
  },
  methods: {
    //三级联动
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        // console.log(data[i].lower.length)
        if (data[i].lower == null || data[i].lower.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].lower = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].lower);
        }
      }
      return data;
    },

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

    goBack() {
      let _this = this;
      localStorage.removeItem("newdata");
      localStorage.removeItem("type");
      localStorage.removeItem("textNumber");
      localStorage.removeItem("tyNumber");
      localStorage.removeItem("iptList");
      localStorage.removeItem("textBNumber");
      localStorage.removeItem("area");
      localStorage.removeItem("tyNumber");
      localStorage.removeItem("add"); //上传图片
      localStorage.removeItem("pestName"); //作物选择返回的病虫害名称

      _this.$router.goBack();
    },

    // 判断必填项是否都以填完
    judge() {
      if (
        localStorage.getItem("classify_palnt") &&
        this.inputC &&
        localStorage.getItem("area") &&
        localStorage.getItem("unit") &&
        localStorage.getItem("plantNumber") &&
        localStorage.getItem("add")
      ) {
        this.binghai();
      } else {
        this.$message.error("必填项没有完成不能保存！！");
      }
    },

    //   给后端传递病虫害值和虫害级别
    binghai() {
      let _this = this;
      // var data = JSON.stringify(_this.inputC)
      _this.chongji(); //调用虫害函数
      let postData = _this.$qs.stringify({
        harm_id: localStorage.getItem("classify_palnt"), //病虫害ID
        // growth_stages: data, //生育期
        growth_stages: _this.inputC, //生育期
        addr_photo: localStorage.getItem("add"), //病虫害照片路径
        area: localStorage.getItem("plantNumber"), //统计面积
        pestname: localStorage.getItem("iptList"), //病害值
        cens_method: localStorage.getItem("area") + localStorage.getItem("unit") //统计方法
      });

      _this
        .$axios({
          method: "POST",
          url: "bigservers/cate",
          data: postData,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        })
        .then(res => {
          if (res.data.code == null) {
            this.$notify.error({
              title: "失败",
              message: "数据保存失败",
              duration: 1000
            });
          } else if (res.data.code == 200) {
            _this.$router.push("home");
            this.$notify({
              title: "成功",
              message: "数据保存成功了",
              type: "success",
              duration: 1000
            });
            //删除存在本地的值
            this.delData();
          }
        })
        .catch(error => {
          alert("保存失败");
          console.log(error);
        });
    },

    //统计方法的值
    handleChange(value) {
      localStorage.setItem("area", value[0]); //作物数量还是面积
      localStorage.setItem("unit", value[1]); //单位
    },

    //监听数字input-失去焦点-作物数量
    animateWidthA() {
      if (this.inputA === "") {
        this.$notify({
          title: "警告",
          message: "这是必填项，不能为空",
          type: "warning",
          duration: 1000
        });
      } else {
        localStorage.setItem("plantNumber", this.inputA); // 存数量
      }
    },

    //监听数字input-获取焦点-作物数量
    animateWidth() {
      if (
        localStorage.getItem("area") === null &&
        localStorage.getItem("unit") === null
      ) {
        this.$notify({
          title: "警告",
          message: "请先选择统计方法之后，再填写数量",
          type: "warning",
          duration: 1000
        });
      }
    },

    //监听数字input-失去焦点-生育期
    animateWidthC(e) {
      let _this = this;
      //判断是否选择病害名称
      if (
        localStorage.getItem("classify_palnt") !== null &&
        _this.inputC === ""
      ) {
        this.$notify({
          title: "警告",
          message: "此项为必填项，请填写完后再填写下一项",
          type: "warning",
          duration: 1000
        });
      }
    },

    //保存虫级值
    chongji() {
      let _this = this;
      //存input框中输入的值
      let list = localStorage.iptList; //原有值
      if (list) {
        var b1 = JSON.parse(list);
        b1.push("卵" + ":" + _this.input1);
        b1.push("蛹" + ":" + _this.input2);
        b1.push("幼虫" + ":" + _this.input3);
        b1.push("落虫" + ":" + _this.input4);
        b1.push("齡雄虫1" + ":" + _this.input5);
        b1.push("齡雄虫2" + ":" + _this.input6);
        b1.push("齡雄虫3" + ":" + _this.input7);
        b1.push("齡雄虫4" + ":" + _this.input8);
        b1.push("齡雄虫5" + ":" + _this.input9);
        b1.push("齡雄虫6" + ":" + _this.input10);
        b1.push("齡雌虫1" + ":" + _this.input11);
        b1.push("齡雌虫2" + ":" + _this.input12);
        b1.push("齡雌虫3" + ":" + _this.input13);
        b1.push("齡雌虫4" + ":" + _this.input14);
        b1.push("齡雌虫5" + ":" + _this.input15);
        b1.push("齡雌虫6" + ":" + _this.input16);

        var b2 = JSON.stringify(b1);
      } else {
        let adlist = [];
        adlist.push("卵" + ":" + _this.input1);
        adlist.push("蛹" + ":" + _this.input2);
        adlist.push("幼虫" + ":" + _this.input3);
        adlist.push("落虫" + ":" + _this.input4);
        adlist.push("齡雄虫1" + ":" + _this.input5);
        adlist.push("齡雄虫2" + ":" + _this.input6);
        adlist.push("齡雄虫3" + ":" + _this.input7);
        adlist.push("齡雄虫4" + ":" + _this.input8);
        adlist.push("齡雄虫5" + ":" + _this.input9);
        adlist.push("齡雄虫6" + ":" + _this.input10);
        adlist.push("齡雌虫1" + ":" + _this.input11);
        adlist.push("齡雌虫2" + ":" + _this.input12);
        adlist.push("齡雌虫3" + ":" + _this.input13);
        adlist.push("齡雌虫4" + ":" + _this.input14);
        adlist.push("齡雌虫5" + ":" + _this.input15);
        adlist.push("齡雌虫6" + ":" + _this.input16);
        var b2 = JSON.stringify(adlist);
      }
      localStorage.setItem("iptList", b2);
    },

    //保存完成后删除本地数据
    delData() {
      //第二步页面的数据
      localStorage.removeItem("iptList"); //病虫害值
      localStorage.removeItem("area"); //作物数量
      localStorage.removeItem("add"); //上传图片
      localStorage.removeItem("classify_palnt"); //病害名称
      localStorage.removeItem("unit"); //统计方法
      localStorage.removeItem("plantNumber"); //作物数量

      //第一步页面数据
      localStorage.removeItem("regionID"); //地区ID
      localStorage.removeItem("regionName"); //地区名称
      localStorage.removeItem("regionData"); //地区
      localStorage.removeItem("monthID"); //月份ID
      localStorage.removeItem("month"); //月份
      localStorage.removeItem("screebIndex");
      localStorage.removeItem("plantType");
      localStorage.removeItem("plantName");
      localStorage.removeItem("pestName");
      localStorage.removeItem("radioData");
      localStorage.removeItem("screenIndex");
    },

    handleRemove(file, fileList) {
      // console.log(file, fileList);
      // console.log(this.add)
      // let postData = this.$qs.parse({
      //   pic_list: localStorage.getItem("add")
      // });
      // this.$axios({
      //   method: "post",
      //   url: "/del_account_photo",
      //   data: postData,
      //   headers: {
      //     "Content-Type": "application/json"
      //   }
      // })
      //   .then(res => {
      //     console.log(res.data);
      //   })
      //   .catch(error => {
      //     console.log(error);
      //   });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleHttpRequest(file) {
      let _this = this;
      // console.log(file.file)
      // console.log(file)
      let form = new FormData();
      form.append("file", file.file);
      _this
        .$axios({
          method: "post",
          url: "bigservers/account_photo",
          anync: true,
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          _this.add.push(res.data.src);
          _this.btnShow = true;
          localStorage.setItem("add", _this.add);
        })
        .catch(error => {
          console.log(err);
        });
    },

    //删除上传的图片
    delBtn() {
      let _this = this;
      let postData = _this.$qs.stringify({
        pic_list: localStorage.getItem("add")
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/del_account_photo",
          data: postData,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        })
        .then(res => {
          localStorage.removeItem("add");
          this.$notify({
            title: "成功",
            message: "图片删除成功",
            type: "success"
          });
          this.$refs.upload.clearFiles();
          localStorage.removeItem("add");
        })
        .catch(error => {
          console.log(error);
          this.$notify.error({
            title: "失败",
            message: "图片删除失败"
          });
        });
    },

    //监听虫害名称添加input-失去焦点-虫害名称
    animateWidthB() {
      let _this = this;
      //判断是否为空
      if (_this.inputInsect !== "") {
        _this.dialogVisibleA = true;
      }
    },
    handleClose(done) {
      let _this = this;
      _this.dialogVisibleA = false;
    },
    //添加病虫害名称弹框确定事件
    addPlant() {
      let _this = this;
      let postData = _this.$qs.stringify({
        ret: "add_harm",
        // ret: "none",
        harm: localStorage.getItem("plantName"), //分类id
        pest_sort: localStorage.getItem("radioData"), //病虫害区分
        pest_name: _this.inputInsect, //病虫害名称
        month_id: localStorage.getItem("monthID") //月份ID
      });
      _this
        .$axios({
          url: "bigservers/city",
          method: "post",
          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.confirm();
          } else if (res.data.code == 201) {
            this.$message({
              showClose: true,
              message: "该虫害名称已经存在了！",
              type: "warning"
            });
          } else if (res.data.code == null) {
            this.$message({
              type: "warning",
              message: "该虫害名称新建失败！",
              duration: 1500
            });
          }
          _this.inputInsect = "";
        })
        .catch(err => {
          console.log(err);
        });
    },
    //添加病虫害名称弹框取消事件
    delPlant() {
      let _this = this;
      _this.inputInsect = "";
    },

    //下拉框选中虫害名称
    resultB(e) {
      console.log(e);
      localStorage.setItem("classify_palnt", e);
      this.disabledInput = false; //生育期
    },

    //请求病虫害名
    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: _this.redata.pest_name, //作物名称
            pest_sort: _this.redata.crop_sort, //作物类型
            month_id: _this.redata.month //月份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
        });
      }
      _this
        .$axios({
          url: "bigservers/city",
          method: "post",
          data: postData,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          }
        })
        .then(res => {
          this.optionsB = res.data;
          // this.optionsB = JSON.parse(localStorage.getItem("pestName"));
        })
        .catch(err => {});
    }
  }
};
</script>

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