<!--  -->
<template>
  <div class="questions_box" :style="'height:' + fullHeight + 'px'" v-loading="loading">
    <!-- 头部 -->
    <div class="questions_head">
      <div class="questions_head_returnA" @click="FanHui()">
        <img src="../../assets/image/left.png" alt class="questions_head_returnA_img" />
      </div>

      <!-- 标题 -->
      <div class="head_title">
        <span class="head_title_text">发布交流</span>
      </div>
    </div>
    <!-- 线 -->
    <div class="questions_segment"></div>
    <!-- 线 -->

    <!-- 步骤 -->
    <el-tabs :before-leave="beforeLeave" v-model="activeName" type="card" @tab-click="handleClick">
      <!-- 第一步 -->
      <el-tab-pane label="1 描述问题" name="first">
        <div class="ipt_segmentA"></div>
        <!-- 输入作物或昆虫 -->
        <div class="radio_box">
          <el-radio v-model="radio" label="plant">作物</el-radio>
          <el-radio v-model="radio" label="insect">昆虫</el-radio>
        </div>
        <el-input
          maxlength="20"
          placeholder="请输入提问作物名或昆虫名(字数限制为20，包括特殊字符)"
          v-model="input"
          clearable
        ></el-input>
        <div class="ipt_segmentB"></div>

        <!-- 描述问题 -->
        <div class="question_box">
          <div class="question_text">请描述你的问题</div>
          <el-input
            maxlength="300"
            type="textarea"
            :rows="2"
            :onkeyup="textarea = textarea.replace(/\s+/g,'')"
            placeholder="请详细描述您的问题，以便我们诊断(字数限制为300字，包括特殊字符)"
            v-model="textarea"
          ></el-input>
        </div>
      </el-tab-pane>

      <!-- 第二步 -->
      <el-tab-pane :disabled="this.lianxi == false" label="2 补充照片" name="second">
        <div class="img_text">补充病虫害图片</div>

        <div class="img_box">
          <img src="../../assets/image/jinggao.png" alt class="img_image" />
          <span class="img_describe">建议添加最少两张照片以便专家更准确鉴定,等待图片下方出现删除按钮后再点击下一步</span>

          <!-- 上传 -->
          <div class="uploading_box" v-loading="loadingA">
            <el-upload
              ref="upload"
              :file-list="imgList"
              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>
        </div>
      </el-tab-pane>

      <!-- 第三步 -->
      <el-tab-pane :disabled="this.lianxiA == false" label="3 补充信息" name="third">
        <div class="condition_box">
          <div class="condition_text">近期用肥用药情况</div>
          <el-input
            maxlength="100"
            class="condition_ipt"
            type="textarea"
            :onkeyup="textareaA = textareaA.replace(/\s+/g,'')"
            :rows="2"
            placeholder="请详细描述，以便诊断(字数限制为100字，包括特殊字符)"
            v-model="textareaA"
          ></el-input>
        </div>

        <div class="proportion_box">
          <div class="condition_text">发生面积</div>
          <ul class="proportion_ul">
            <li
              class="proportion_li"
              @click="getItem(index, item)"
              :class="activeClass == index ? 'activeAAAA':''"
              v-for="(item, index) in this.proportion"
              :key="index"
            >{{ item }}</li>
          </ul>
        </div>

        <div class="conditionA_box">
          <div class="condition_text">近期天气情况</div>
          <ul class="condition_ul">
            <li
              class="condition_li"
              :class="activeClassA == index ? 'activeAAAA':''"
              @click="getItemA(index, item)"
              v-for="(item,index) in this.conditionA"
              :key="index"
            >{{ item }}</li>
          </ul>
          <el-input
            maxlength="32"
            v-show="iptShow"
            class="condition_ipt"
            placeholder="请输入具体的天气情况"
            v-model="inputA"
            clearable
          ></el-input>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 步骤 -->

    <!-- 下一步 -->
    <div
      class="botNext"
      v-bind:class="{ 'nav-hide' : hideClass }"
      @click="next()"
      v-if="botNext"
    >下一步</div>
    <div class="botNext" v-bind:class="{ 'nav-hide' : hideClass }" @click="accomplish()" v-else>完成</div>
    <!-- 下一步 -->

    <!-- 测试地图 -->
    <div class="mapbox" v-show="mapShow">
      <baidu-map
        :style="'height:' + fullHeight + 'px'"
        locationIcon
        class="map"
        :double-click-zoom="true"
        @ready="handler"
        :center="center"
        :zoom="150"
        :map-click="false"
        :mapStyle="mapStyle"
      >
        <bm-geolocation
          @locationSuccess="getLoctionSuccess"
          @locationError="getLoctionError"
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="false"
          :autoLocation="true"
        ></bm-geolocation>
      </baidu-map>
    </div>
    <!-- 测试地图 -->
  </div>
</template>

<script>
import BmMarker from "vue-baidu-map/components/overlays/Marker";
import { BmGeolocation } from "vue-baidu-map";
const markers = [];
const carList = [{}];
export default {
  name: "questions",
  //限时数据文本的字数限时
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 5) {
        return value.slice(0, 5) + "...";
      }
      return value;
    }
  },

  components: {
    BmMarker,
    // 手动定位控件
    BmGeolocation,
    // marker控件
    BmMarker
  },
  data() {
    return {
      isClick: true, //点赞开关
      loadingA: false, //加载
      loading: true, //加载
      imgList: [],
      inputA: "", //天气情况
      oldActiveName: false,
      mapShow: false, //地图
      radio: "plant", //作物或昆虫单选框
      input: "", //第一步填写提问作物
      botNext: true, //下一步按钮
      activeName: "first", //步骤
      fullHeight: document.documentElement.clientHeight, //一开始的屏幕高度
      showHeight: document.documentElement.clientHeight, //按钮被顶上去
      hideClass: false, //按钮被顶上去
      questionsA: localStorage.getItem("seek_name"),
      show2: false, //筛选按钮
      reData: [], //后端传来的列表数据
      image: "", //后端传来的图片
      axiosShow: true, //暂空判断
      shows: localStorage.getItem("shows"), //active
      textarea: "", //问题描述
      //上传图片
      dialogImageUrl: "",
      dialogVisible: false,
      imgLimit: 3, //限制上传图片张数
      textareaA: "", //第三步用肥用药情况
      iptShow: false, //第三步input框
      center: null,
      BMap: "",
      map: "",
      markers,
      carList,
      show: false,
      redata: [], //后端传来的数据
      active: false,
      latA: "",
      lngA: "",
      nameShow: false,
      mapStyle: {
        styleJson: [
          {
            featureType: "all",
            elementType: "geometry",
            stylers: {
              // hue: "#007fff",
              hue: "#eb8f16",
              saturation: 89
            }
          },
          {
            featureType: "water",
            elementType: "all",
            stylers: {
              color: "#ffffff"
            }
          }
        ]
      },
      //设置地图详细信息
      address: "", //位置详细信息
      jgNameDialog: false,
      show: false,
      postionMap: {
        //地图坐标
        lng: 120.211486,
        lat: 30.256576
      },
      location: "",
      keyword: "", //搜索框关键词
      // zoom: 12.8, //放大比例
      address: "", //位置详细信息
      add: {
        siteName: "",
        site: "",
        jd: "",
        wd: "",
        desce: "",
        type: "",
        jgName: "",
        jgNum: ""
      },
      organizationData: [],
      jgName: "",
      jgNum: "",
      weatherdata: [],
      activeClass: -1, // 0为默认选择第一个，-1为不选择
      activeClassA: -1,
      proportion: ["一两株", "小范围", "成片或整田"],
      conditionA: [
        "无异常",
        "高温",
        "低温",
        "高湿",
        "干旱",
        "连续雨",
        "霜冻",
        "台风",
        "其他"
      ],
      addImage: [], //图片
      delImage: false, //删除按钮
      //测试返回的布尔值
      lianxi: true,
      lianxiA: false
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },
    activeName(val) {
      if (this.activeName === "first") {
        if (this.input !== "" && this.textarea !== "") {
          this.activeName = "second";
          this.lianxi = true;
        } else if (this.input === "") {
          this.$notify({
            title: "警告",
            message: "作物或昆虫名称不能为空",
            type: "warning",
            duration: 1500
          });
          this.lianxi = false;
        } else if (this.textarea === "") {
          this.$notify({
            title: "警告",
            message: "作物或昆虫描述不能为空",
            type: "warning",
            duration: 1500
          });
          this.lianxi = false;
        }
      } else if (this.activeName === "second") {
        // if (localStorage.getItem("add") !== null) {
        //   this.activeName = "third";
        //   this.lianxi = true;
        // } else if (localStorage.getItem("add") === null) {
        //   this.$notify({
        //     title: "警告",
        //     message: "请先上传图片,再进行下一步",
        //     type: "warning",
        //     duration: 1500
        //   });
        //   this.lianxi = false;
        // }
      } else if (this.activeName === "third") {
        if (localStorage.getItem("add") !== null) {
          this.activeName = "third";
          this.lianxi = true;
          this.botNext = false;
        } else if (localStorage.getItem("add") === null) {
          this.$notify({
            title: "警告",
            message: "请先上传图片,再进行下一步",
            type: "warning",
            duration: 1500
          });
          this.lianxi = false;
        }
      }
    },
    radio(val) {},
    addImage(val) {
      if (val !== null) {
        this.delImage = true;
        this.loadingA = false;
      } else {
        this.delImage = false;
        this.loadingA = false;
      }
    },

    botNext(val) {
      console.log(val);
    },

    //输入作物昆虫名
    input: function() {
      this.input = this.input.replace(/[^A-Za-z0-9\u4e00-\u9fa5]/g, "");
    },
    //天气具体情况
    inputA: function() {
      this.inputA = this.inputA.textarea(/[^A-Za-z0-9\u4e00-\u9fa5]/g, "");
    },

    //按钮被顶上去
    showHeight: "inputType"
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // 返回home页面
    FanHui() {
      let _this = this;
      //   localStorage.removeItem("memoryBiaoshi");
      //   localStorage.removeItem("questionsPage");
      //   localStorage.removeItem("shows");
      localStorage.removeItem("add");
      // _this.$router.push("/home");
      _this.$router.replace("/home");
    },

    //百度地图事件
    //地图初始化
    handler({ BMap, map }) {
      const _this = this;
      // 获取自动定位方法
      var geolocation = new BMap.Geolocation();
      // 获取逆解析方法实例
      this.myGeo = new BMap.Geocoder();
      // 获取自动定位获取的坐标信息
      geolocation.getCurrentPosition(
        function(r) {
          _this.center = {
            lng: r.point.lng,
            lat: r.point.lat
          };
          _this.point = {
            lng: r.point.lng,
            lat: r.point.lat
          };
          localStorage.setItem("jingdu", _this.point.lng); //存经纬度
          localStorage.setItem("weidu", _this.point.lat);
          _this.ceshi(r);
        },

        { enableHighAccuracy: true }
      );
      map.enableScrollWheelZoom(true);
      _this.BMap = BMap;
      _this.map = map;
    },
    //手动定位成功回调
    getLoctionSuccess(e) {
      this.lngA = e.point.lng;
      this.latA = e.point.lat;
      localStorage.setItem("jingdu", this.lngA); //存经纬度
      localStorage.setItem("weidu", this.latA);

      this.show = true;
      this.postionMap.lng = e.point.lng; //通过  e.point.lng获取经度
      this.postionMap.lat = e.point.lat; //通过  e.point.lat获取纬度
      this.add.jd = e.point.lng;
      this.add.wd = e.point.lat;

      let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
      geocoder.getLocation(e.point, rs => {
        this.add.site = rs.address;
        //地址描述(string)=
        // console.log(rs.address);    //这里打印可以看到里面的详细地址信息，可以根据需求选择想要的
        // console.log(rs.addressComponents);//结构化的地址描述(object)
        // console.log(rs.addressComponents.province); //省
        // console.log(rs.addressComponents.city); //城市
        // console.log(rs.addressComponents.district); //区县
        // console.log(rs.addressComponents.street); //街道
        // console.log(rs.addressComponents.streetNumber); //门牌号
        // console.log(rs.surroundingPois); //附近的POI点(array)
        // console.log(rs.business); //商圈字段，代表此点所属的商圈(string)

        let a = rs.addressComponents.province;
        let b = rs.addressComponents.city;
        let c = rs.addressComponents.district;
        let d = rs.addressComponents.street;
        let e = rs.addressComponents.streetNumber;
        localStorage.setItem("dizhi", a + b + c + d + e); //存地址
      });
      this.loadinAShow = false; //关闭地图加载动画
    },
    //手动定位失败回调
    getLoctionError() {
      alert("定位失败");
    },

    //自动定位
    ceshi(r) {
      let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
      geocoder.getLocation(r.point, rs => {
        this.add.site = rs.address;
        let a = rs.addressComponents.province;
        let b = rs.addressComponents.city;
        let c = rs.addressComponents.district;
        let d = rs.addressComponents.street;
        let e = rs.addressComponents.streetNumber;
        localStorage.setItem("dizhi", a + b + c + d + e); //存地址
      });
      this.loadinAShow = false; //关闭地图加载动画
      this.loading = false;
    },

    //交流，个人秀
    handleClick(e) {},

    //步骤
    handleClick(tab, event) {},

    clearFiles() {},

    //上传图片
    handleRemove() {
      let postData = this.$qs.parse({
        pic_list: localStorage.getItem("add"),
        ret: this.radio,
        req: "prob"
      });
      return this.$confirm("确定要删除图片吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios({
            method: "post",
            url: "bigservers/del_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.loadingA = true;
      let form = new FormData();
      form.append("file", file.file);
      form.append("ret", this.radio);
      form.append("req", "prob");
      _this
        .$axios({
          method: "post",
          url: "bigservers/send_answer_img",
          anync: true,
          data: form,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          _this.addImage.push(res.data.src);
          _this.btnShow = true;
          this.lianxi = true;
          _this.loadingA = false;
          localStorage.setItem("add", _this.addImage);
        })
        .catch(error => {});
    },

    //点击选中其他显示input
    elseIpt() {
      this.iptShow = true;
    },

    //点击下一步
    next() {
      if (this.activeName === "first") {
        if (this.input !== "" && this.textarea !== "") {
          this.activeName = "second";
          this.lianxi = true;
        } else if (this.input === "") {
          this.$notify({
            title: "警告",
            message: "作物或昆虫名称不能为空",
            type: "warning",
            duration: 1500
          });
          this.lianxi = false;
        } else if (this.textarea === "") {
          this.$notify({
            title: "警告",
            message: "作物或昆虫描述不能为空",
            type: "warning",
            duration: 1500
          });
          this.lianxi = false;
        }
      } else if (this.activeName === "second") {
        if (localStorage.getItem("add") !== null) {
          this.activeName = "third";

          this.lianxi = true;
          this.lianxiA = true;
        } else if (localStorage.getItem("add") === null) {
          this.$notify({
            title: "警告",
            message: "请先上传图片,再进行下一步",
            type: "warning",
            duration: 1500
          });
          this.lianxiA = false;
          this.lianxi = true;
        }
      }
    },

    beforeLeave(item) {},

    //新建完成
    accomplish() {
      let _this = this;
      if (localStorage.getItem("tianqi") === "其他") {
        var a = this.inputA;
      } else {
        var a = localStorage.getItem("tianqi");
      }

      var isClick = _this.isClick;
      if (isClick === true) {
        _this.isClick = false;
        //判断是否填写完整
        if (
          _this.textareaA !== "" &&
          localStorage.getItem("area") !== null &&
          (a !== null || a !== "")
        ) {
          let postData = _this.$qs.parse({
            name: this.input, //病虫害名字
            problem: this.textarea, //描述信息
            addr: localStorage.getItem("dizhi"), //地址
            ret: this.radio, //病虫害类型
            img_list: localStorage.getItem("add"), //图片
            drug: this.textareaA, //肥料和用药情况
            area: localStorage.getItem("area"), //面积
            weather: a, //天气
            lat: localStorage.getItem("jingdu"), //经度
            lng: localStorage.getItem("weidu") //纬度
          });

          _this
            .$axios({
              method: "post",
              url: "bigservers/save_answer",
              data: postData
            })
            .then(res => {
              if (res.data === 0) {
                this.$notify({
                  title: "成功",
                  message: "新建交流成功",
                  type: "success",
                  duration: 1500
                });
                this.delData();
                _this.$router.push("/home");
                const timer = setInterval(() => {
                  location.reload();
                }, 1000);
              } else if (res.data === 1) {
                this.$notify.error({
                  title: "错误",
                  message: "新建交流失败，请重试",
                  duration: 1500
                });
              }
            })
            .catch(error => {
              this.$notify.error({
                title: "错误",
                message: "新建交流失败，请重试",
                duration: 1500
              });
            });
        } else {
          this.$notify({
            title: "警告",
            message: "请将信息填写完整",
            type: "warning",
            duration: 1500
          });
        }
        setTimeout(function() {
          _this.isClick = true;
        }, 2500);
      }
    },

    //切换active-面积
    getItem(index, item) {
      this.activeClass = index;
      localStorage.setItem("area", item);
    },

    //切换active-天气
    getItemA(index, item) {
      this.activeClassA = index;
      localStorage.setItem("tianqi", item);
      if (item === "其他") {
        this.elseIpt();
      } else {
        this.iptShow = false;
      }
    },

    //新建成功删除本地数据
    delData() {
      localStorage.removeItem("tianqi"); //天气其他
      localStorage.removeItem("area"); //面积
      localStorage.removeItem("dizhi"); //地址
      localStorage.removeItem("weidu"); //纬度
      localStorage.removeItem("jingdu"); //经度
      localStorage.removeItem("add"); //图片
      this.$router.replace("/home");
    },

    //按钮被顶上去
    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() {
    //将tab切换设置为不可操作
    this.lianxi = false;
  },
  //生命周期 - 挂载完成（可以访问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/questions.scss";
</style>