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

      <!-- 标题 -->
      <div class="head_title">
        <span class="head_title_text">发布个人秀</span>
      </div>
    </div>

    <!-- 主内容 -->
    <div class="fieldsShow_main">
      <!-- 内容input -->
      <div class="fieldsShow_IptBox">
        <el-input
          maxlength="50"
          type="textarea"
          :rows="10"
          placeholder="分享你播种的快乐"
          v-model="textarea"
          :onkeyup="textarea = textarea.replace(/\s+/g,'')"
        ></el-input>
        <div class="fieldsShow_IptNum">{{ this.textarea.length }} / 50</div>
      </div>
      <!-- 内容input -->

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

      <!-- 上传图片 -->
      <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>
      <!-- 上传图片 -->

      <!-- 发布 -->
      <button v-bind:class="{ 'nav-hide' : hideClass }" @click="bomNextBtn()" class="bomNextBtn">发布</button>
      <!-- 发布 -->
    </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>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import BmMarker from "vue-baidu-map/components/overlays/Marker";
import { BmGeolocation } from "vue-baidu-map";
const markers = [];
const carList = [{}];
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
     BmMarker,
    // 手动定位控件
    BmGeolocation,
    // marker控件
    BmMarker
  },
  data() {
    //这里存放数据
    return {
      loadingA: false, //加载
      isClick: true, //点赞开关
      loading: true, //加载
      fullHeight: document.documentElement.clientHeight,
      textarea: "", //内容
      addImage: [], //图片
      delImage: false, //删除按钮
      imgLimit: 3, //限制上传图片张数
      dialogVisible: false,
      dialogImageUrl: "",
      dizhi: '', //地址
      imgList: [], //上传图片列表
      showHeight: document.documentElement.clientHeight, //按钮被顶上去
      hideClass: false, //按钮被顶上去
      isClick: true, //开关

      //地图
      //自动定位
      mapShow: false, //地图
      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: ""
    };
  },
  //监听属性 类似于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);
    },
    addImage(val) {
      if (val !== null) {
        this.delImage = true;
        this.loadingA = false;
      } else {
        this.delImage = false;
        this.loadingA = false;
      }
    },
    //按钮被顶上去
    showHeight: "inputType"
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    //返回主页
    FanHui() {
      // this.$router.push("/home");
      localStorage.removeItem("add");
      this.$router.replace("/home");
    },

    //上传图片-删除
    handleRemove() {
      let postData = this.$qs.parse({
        pic_list: localStorage.getItem("add"),
        ret: "",
        req: "farm"
      });
      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("req", "farm");
      _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.loadingA = false;
          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 (localStorage.getItem("add") === null) {
          this.$notify({
            title: "警告",
            message: "请上传您分享的照片",
            type: "warning",
            duration: 1500
          });
        } else if (
          _this.textarea !== "" &&
          localStorage.getItem("add") !== null
        ) {
          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 //描述信息
          });
            _this
              .$axios({
                method: "post",
                url: "bigservers/save_farm_show",
                data: postData
              })
              .then(res => {
                if (res.data === 0) {
                  this.$notify({
                    title: "成功",
                    message: "发布成功",
                    type: "success",
                    duration: 1500
                  });
                  this.$router.push("/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);
        }

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

    //按钮被顶上去
    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);
      }
    },


    //地图定位
    //百度地图事件
    //地图初始化
    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 _this = this;
      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("addrData", b); //存下地址
        //判断本地存储中是否存有值
        if (localStorage.getItem("tianqiData") !== null) {
          //有值
          var data = localStorage.getItem("tianqiData");
          var data = JSON.parse(data); //获取到存在本地的值
        } else if (localStorage.getItem("tianqiData") === null) {
          //没有值
          // this.tianqiAxios(b);
        }
        //测试自定义天气插件
        localStorage.setItem("dizhi", a + b + c + d + e); //存地址
        _this.dizhi =  a + b + c + d + e
        _this.loading = false;
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问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/fieldsShow.scss";
//@import url(); 引入公共css类
</style>