<!--  -->
<template>
  <div
    class="pestbox"
    v-loading="pestboxloading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <!-- <div
      :style="{ height: '100%', width: '100%' }"
      id="mychart"
      ref="mychart"
    ></div> -->
    <div class="amap-demo" id="mapContainer2"></div>
    <div class="searchbox">
      <el-select
        v-model="wornvalue"
        placeholder="请选择害虫名称"
        size="mini"
        @change="search"
      >
        <el-option
          v-for="item in wornoptions"
          :key="item.point_id"
          :label="item.point_name"
          :value="item.point_id"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="inoffvalue"
        placeholder="请选择所在监测点"
        size="mini"
        @change="search"
      >
        <el-option
          v-for="item in inoffoptions"
          :key="item.point_name"
          :label="item.point_name"
          :value="item.point_name"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="versionsvalue2"
        placeholder="请选择隶属组织"
        size="mini"
        @change="search"
      >
        <el-option
          v-for="item in versionsoptions2"
          :key="item.org_name"
          :label="item.org_name"
          :value="item.org_name"
        >
        </el-option>
      </el-select>
      <el-date-picker
        v-model="timevalue"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="oickchange"
        size="mini"
        :editable="false"
      >
      </el-date-picker>
      <el-button type="info" @click="search" size="mini">搜索</el-button>
      <el-button @click="reset" size="mini">重置</el-button>
      <el-button type="warning" @click="dialogVisible = true" size="mini"
        >设置</el-button
      >
    </div>
    <div class="piebox">
      <p
        :class="
          pietf ? 'iconbox el-icon-arrow-right' : 'iconbox el-icon-arrow-left'
        "
        @click="pietf = !pietf"
        style="cursor: pointer"
      ></p>
      <div
        :style="{
          height: '500px',
          width: width,
          transition: 'all 1s ease',
          borderRadius: '10px',
        }"
        id="mychartpie"
        ref="mychartpie"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      ></div>
    </div>
    <div class="measurebox">
      <div
        :class="
          measure_index == 1 ? 'measurebox_item selmea' : 'measurebox_item'
        "
        @click="measure_distance"
      >
        <i class="iconfont icon-ceju"></i>
        <p>测距</p>
      </div>
      <p class="measurebox_line"></p>
      <div
        :class="
          measure_index == 2 ? 'measurebox_item selmea' : 'measurebox_item'
        "
        @click="measure_area"
      >
        <i class="iconfont icon-mianji"></i>
        <p>侧面</p>
      </div>
    </div>
    <el-dialog
      title="设置"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="shezhibox">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          class="demo-ruleForm"
        >
          <el-form-item label="最大害虫数量设置可标红" prop="threshold">
            <el-input v-model="ruleForm.threshold" size="mini"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import * as echarts from "echarts";
import { map, time } from "highcharts";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    var checklnglat = (rule, value, callback) => {
      if (isNaN(value)) {
        callback(new Error("请输入数字"));
      } else {
        callback();
      }
    };
    return {
      pietf: true,
      width: "500px",
      wornvalue: "", //有害生物名称 选择
      wornoptions: [], //有害生物列表
      inoffvalue: "", //监测点 选择
      inoffoptions: [], //监测点列表
      versionsvalue2: "", //隶属组织选择
      versionsoptions2: [], //隶属组织列表
      timevalue: "",
      start_time: "",
      end_time: "",
      loading: false,
      dialogVisible: false,
      ruleForm: {
        threshold: "100", //阈值
      },
      rules: {
        name: [
          { required: true, message: "请输入值", trigger: "blur" },
          { validator: checklnglat, trigger: "blur" },
        ],
      },
      pestboxloading: true,
      center: [114.052758, 22.545817],
      measure_index:0,
      mouseTool:null
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    pietf: function (val) {
      // console.log(this.width)
      if (val) {
        this.width = "500px";
      } else {
        this.width = "0";
      }
      // console.log(this.width)
    },
  },
  //方法集合
  methods: {
    ToDigital(lnglat) {
      // console.log(lnglat);
      if (!isNaN(lnglat)) {
        return lnglat;
      }
      lnglat = lnglat.toString();
      var strDu, strFen, strMiao;
      var duindex = lnglat.indexOf("°"); //字符度的下标
      var fenindex = lnglat.indexOf("′"); //字符分的下标
      var miaoindex = lnglat.indexOf("″"); //字符秒的下标
      strDu = lnglat.slice(0, duindex);
      strFen = lnglat.slice(duindex + 1, fenindex);
      strMiao = lnglat.slice(fenindex + 1, miaoindex);
      // len = len > 6 || typeof len == "undefined" ? 6 : len; //精确到小数点后最多六位
      strDu =
        typeof strDu == "undefined" || strDu == "" ? 0 : parseFloat(strDu);
      strFen =
        typeof strFen == "undefined" || strFen == ""
          ? 0
          : parseFloat(strFen) / 60;
      strMiao =
        typeof strMiao == "undefined" || strMiao == ""
          ? 0
          : parseFloat(strMiao) / 3600;
      var digital = strDu + strFen + strMiao;
      if (digital == 0) {
        return "";
      } else {
        return digital.toFixed(6);
      }
    },
    initmap() {
      var map = new AMap.Map(document.getElementById("mapContainer2"), {
        center: this.center,
        resizeEnable: true,
        zoom: 11,
        lang: "en",
        mapStyle: "amap://styles/fresh",
        layers: [],
      });
      //new AMap.TileLayer.Satellite(),new AMap.TileLayer.RoadNet()
      AMap.plugin(["AMap.ToolBar", "AMap.Geocoder"], () => {
        map.addControl(new AMap.ToolBar());
        this.geocoder = new AMap.Geocoder({
          city: "全国",
          radius: 1000,
        });
      });
      AMap.plugin(["AMap.MouseTool"], () => {
        this.mouseTool = new AMap.MouseTool(map);
      });
      this.map = map;
      this.getwornlist();
    },
    initpie(data) {
      var data = data;
      var placeHolderStyle = {
        normal: {
          label: {
            show: false,
          },
          labelLine: {
            show: false,
          },
          color: "rgba(0, 0, 0, 0)",
          borderColor: "rgba(0, 0, 0, 0)",
          borderWidth: 0,
        },
      };
      var data1 = [];
      var data2 = [];
      var colorIn = [
        "rgb(33, 166, 161)",
        "rgb(102,113,209)",
        "rgb(230,144,78)",
        "rgb(38,185,211)",
        "rgb(82,125,12)",
        "rgb(35,70,209)",
      ];
      var colorOut = [
        "rgba(33, 166, 161, 0.5)",
        "rgba(102,113,209, 0.5)",
        "rgba(230,144,78, 0.5)",
        "rgba(38,185,211, 0.5)",
        "rgb(82,125,12,0.5)",
        "rgb(35,70,209,0.5)",
      ];
      for (var i = 0; i < data.length; i++) {
        data1.push({
          data: data[i].value,
          value: data[i].value,
          name: data[i].name,
          itemStyle: {
            normal: {
              color: colorOut[i],
            },
          },
        });
        data2.push({
          data: data[i].value,
          value: data[i].value,
          name: data[i].name,
          itemStyle: {
            normal: {
              color: colorIn[i],
            },
          },
        });
      }
      var dataArr = [];
      for (var i = 0; i < 100; i++) {
        if (i % 2 === 0) {
          dataArr.push({
            name: (i + 1).toString(),
            value: 25,
            itemStyle: {
              normal: {
                color: "#2ac9e1",
                borderWidth: 0,
                borderColor: "rgba(0,0,0,0)",
              },
            },
          });
        } else {
          dataArr.push({
            name: (i + 1).toString(),
            value: 20,
            itemStyle: {
              normal: {
                color: "rgba(0,0,0,0)",
                borderWidth: 0,
                borderColor: "rgba(0,0,0,0)",
              },
            },
          });
        }
      }
      var option = {
        title: {
          text: "有害生物占比",
          subtext: "",
          sublink: "",
          left: "center",
          textStyle: {
            color: "#222222",
          },
          top: "5%",
        },
        backgroundColor: "#ffffff",
        tooltip: {
          title: "详情",
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "horizontal",
          top: "90%",
          itemWidth: 10,
          itemHeight: 10,
          x: "center",
          textStyle: {
            color: "#222222",
            fontSize: 12,
          },
          show: true,
          // data: data,
          type: "scroll", //分页类型
          data: (function () {
            var list = [];
            for (var i = 0; i < data.length; i++) {
              list.push(data[i]);
            }
            return list;
          })(),
          pageIconColor: "#ff781f", //翻页箭头颜色
          pageTextStyle: {
            color: "#999", //翻页数字颜色
          }, //翻页数字设置
          pageIconSize: 13,
          itemHeight: 10,
          itemWidth: 15,
        },
        series: [
          {
            type: "pie",
            zlevel: 3,
            silent: true,
            // center: ['50%', '40%'],
            radius: ["43%", "45%"],
            label: {
              normal: {
                show: false,
              },
            },
            labelLine: {
              normal: {
                show: false,
              },
            },
            data: dataArr,
          },
          {
            name: "详情",
            type: "pie",
            selectedMode: "single",
            radius: [0, "40%"],
            label: {
              formatter: "",
              position: "inner",
            },
            data: data2,
          },
          {
            name: "详情",
            type: "pie",
            radius: ["48%", "50%"],
            labelLine: {
              normal: {
                length: 10,
                length2: 14,
              },
            },
            label: {
              show: true,
              position: "outer",
              alignTo: "labelLine",
              // ·圆点
              backgroundColor: "auto",
              height: 0,
              width: 0,
              lineHeight: 0,
              distanceToLabelLine: 0,
              borderRadius: 2.5,
              padding: [2.5, -2.5, 2.5, -2.5],
              formatter: "{a|{b} }",
              rich: {
                a: {
                  padding: [0, 0, 0, 10],
                  color: "#151515",
                  fontSize: 14,
                },
                b: {
                  padding: [0, 10, 0, 0],
                  fontSize: 14,
                },
              },
            },
            data: data1,
          },
        ],
      };
      echarts.init(document.getElementById("mychartpie")).setOption(option);
    },
    getwornlist() {
      this.loading = true;
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.home_map.pest_distribute_new",
        data: this.qs.stringify({
          pest_name: this.wornvalue, //                非必传(string)               有害生物名称 搜索项
          point_name: this.inoffvalue, //               非必传(string)               设备所属监测点 搜索项
          org_name: this.versionsvalue2, //                 非必传(string)               设备所属组织   搜索项
          start_time: this.start_time, //               非必传(string)               开始时间  搜索项 2022-01-20
          end_time: this.end_time, //                 非必传(string)               结束时间  搜索项 2022-01-23
        }),
      }).then((res) => {
        // console.log(res.data.data);
        this.map.clearMap();
        var resdata = res.data.data;
        this.loading = false;
        var pest_count = res.data.data.pest_count;
        var arr = [];
        for (var i = 0; i < pest_count.length; i++) {
          var obj = {
            value: pest_count[i].sum,
            name: pest_count[i].pest_name,
          };
          arr.push(obj);
        }
        var capitals = [];
        if (resdata.huizhou) {
          for (var i = 0; i < resdata.huizhou.length; i++) {
            var obj = {
              device_id: resdata.huizhou[i].device_id,
              pest_data: resdata.huizhou[i].pest_data,
              pest_total: resdata.huizhou[i].pest_total,
              name: "北京",
              center: [
                this.ToDigital(resdata.huizhou[i].lng),
                this.ToDigital(resdata.huizhou[i].lat),
              ],
            };
            capitals.push(obj);
          }
        }
        if (resdata.shenzhen) {
          for (var i = 0; i < resdata.shenzhen.length; i++) {
            var obj = {
              device_id: resdata.shenzhen[i].device_id,
              pest_data: resdata.shenzhen[i].pest_data,
              pest_total: resdata.shenzhen[i].pest_total,
              center: [
                this.ToDigital(resdata.shenzhen[i].lng),
                this.ToDigital(resdata.shenzhen[i].lat),
              ],
            };
            capitals.push(obj);
          }
        }
        if (resdata.shanwei) {
          for (var i = 0; i < resdata.shanwei.length; i++) {
            var obj = {
              device_id: resdata.shanwei[i].device_id,
              pest_data: resdata.shanwei[i].pest_data,
              pest_total: resdata.shanwei[i].pest_total,
              center: [
                this.ToDigital(resdata.shanwei[i].lng),
                this.ToDigital(resdata.shanwei[i].lat),
              ],
            };
            capitals.push(obj);
          }
        }
        var maxnum = 0;
        for (var i = 0; i < capitals.length; i += 1) {
          if (capitals[i].pest_total > maxnum) {
            console.log();
            maxnum = capitals[i].pest_total;
          }
        }
        for (var i = 0; i < capitals.length; i += 1) {
          var color = "";
          if (capitals[i].pest_total > Math.floor(maxnum * 0.8)) {
            color = "#ff0202";
          } else if (capitals[i].pest_total > Math.floor(maxnum * 0.6)) {
            color = "#ff4902";
          } else if (capitals[i].pest_total > Math.floor(maxnum * 0.4)) {
            color = "#ffe402";
          } else if (capitals[i].pest_total > Math.floor(maxnum * 0.2)) {
            color = "#ff00ba";
          } else {
            color = "#0cff00";
          }
          var center = capitals[i].center;
          var device_id = capitals[i].device_id;
          var pest_data = capitals[i].pest_data;
          var pest_total = capitals[i].pest_total;
          var circleMarker = new AMap.CircleMarker({
            center: center,
            device_id: device_id,
            pest_data: pest_data,
            pest_total: pest_total,
            radius: 8, //3D视图下，CircleMarker半径不要超过64px
            strokeColor: "white",
            strokeWeight: 2,
            strokeOpacity: 0.5,
            fillColor: color,
            fillOpacity: 0.8,
            zIndex: 10,
            bubble: true,
            cursor: "pointer",
            clickable: true,
          });
          circleMarker.setMap(this.map);
          circleMarker.on("click", (e) => {
            // console.log(e.target);
            this.openInfo(e.target._opts);
          });
        }
        this.initpie(arr);
        this.pestboxloading = false;
      });
    },
    openInfo(info) {
      //构建信息窗体中显示的内容
      var str = ``;
      for (var i = 0; i < info.pest_data.length; i++) {
        str +=
          `<p>` +
          info.pest_data[i].pest_name +
          ` ：` +
          info.pest_data[i].sum +
          ` 只</p>`;
      }
      var infoWindow = new AMap.InfoWindow({
        content:
          `<div style="height:100px;overflow-y: auto;"><p>设备id ：` +
          info.device_id +
          `</p>` +
          str +
          `</div>`, //使用默认信息窗体框样式，显示信息内容
      });

      infoWindow.open(this.map, [info.center.lng, info.center.lat]);
    },
    getwornlistflex() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.home_map.pest_name_list",
      }).then((res) => {
        // console.log(res.data.data);
        this.wornoptions = [];
        var pest_list = res.data.data;
        for (var i = 0; i < pest_list.length; i++) {
          var obj2 = {
            point_id: pest_list[i].pest_name,
            point_name: pest_list[i].pest_name,
          };
          this.wornoptions.push(obj2);
        }
      });
    },
    tabtime(times) {
      //时间转换
      var years = times.getFullYear();
      var month = times.getMonth() + 1;
      var date = times.getDate();
      return years + "-" + month + "-" + date;
    },
    oickchange(e) {
      if (e) {
        this.start_time = this.tabtime(e[0]);
        this.end_time = this.tabtime(e[1]);
      } else {
        this.start_time = "";
        this.end_time = "";
      }
    },
    search() {
      this.getwornlist();
    },
    reset() {
      this.wornvalue = "";
      this.inoffvalue = "";
      this.versionsvalue2 = "";
      this.timevalue = "";
      this.getwornlist();
    },
    getmon2() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=monitor_manage.trap_manage.pest_trap_org",
      }).then((res) => {
        // console.log(res.data.data);
        this.versionsoptions2 = [];
        var org_list = res.data.data.org_list;
        for (var i = 0; i < org_list.length; i++) {
          if (org_list[i].org_name != "") {
            this.versionsoptions2.push(org_list[i]);
          }
        }
        // this.versionsoptions2 = res.data.data.org_list;
        this.inoffoptions = res.data.data.point_data;
        this.initmap();
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=monitor_manage.home_map.pest_distribute_threshold",
            data: this.qs.stringify({
              threshold: this.ruleForm.threshold,
            }),
          }).then((res) => {
            if (res.data.data) {
              this.dialogVisible = false;
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  showClose: true,
                  message: "设置成功",
                  type: "success",
                });
              }
              this.getwornlist();
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  showClose: true,
                  message: "设置失败",
                  type: "success",
                });
              }
            }
          });
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message({
              showClose: true,
              message: "设置失败" + res.data.message,
              type: "warning",
            });
          }
          // return false;
        }
      });
    },
    resetForm(formName) {
      this.dialogVisible = false;
      this.$refs[formName].resetFields();
    },
    //距离测量
    measure_distance() {
      this.measure_index = 1;
      this.draw("rule");
      window.addEventListener("dblclick", () => {
        this.measure_index = 0;
        this.mouseTool.close();
      });
      window.addEventListener("contextmenu", () => {
        this.measure_index = 0;
        this.mouseTool.close();
      });
    },
    //面积测量
    measure_area() {
      this.measure_index = 2;
      this.draw("measureArea");
      window.addEventListener("dblclick", () => {
        this.measure_index = 0;
        this.mouseTool.close();
      });
      window.addEventListener("contextmenu", () => {
        this.measure_index = 0;
        this.mouseTool.close();
      });
    },
    measure_close() {
      this.measure_index = 0;
      this.mouseTool.close(true);
    },
    draw(type) {
      console.log(type);
      // this.mouseTool.close(true);
      var mouseTool = this.mouseTool;
      switch (type) {
        case "rule": {
          mouseTool.rule({
            startMarkerOptions: {
              //可缺省
              icon: new AMap.Icon({
                size: new AMap.Size(19, 31), //图标大小
                imageSize: new AMap.Size(19, 31),
                image: "//webapi.amap.com/theme/v1.3/markers/b/start.png",
              }),
              offset: new AMap.Pixel(-9, -31),
            },
            endMarkerOptions: {
              //可缺省
              icon: new AMap.Icon({
                size: new AMap.Size(19, 31), //图标大小
                imageSize: new AMap.Size(19, 31),
                image: "//webapi.amap.com/theme/v1.3/markers/b/end.png",
              }),
              offset: new AMap.Pixel(-9, -31),
            },
            midMarkerOptions: {
              //可缺省
              icon: new AMap.Icon({
                size: new AMap.Size(19, 31), //图标大小
                imageSize: new AMap.Size(19, 31),
                image: "//webapi.amap.com/theme/v1.3/markers/b/mid.png",
              }),
              offset: new AMap.Pixel(-9, -31),
            },
            lineOptions: {
              //可缺省
              strokeStyle: "solid",
              strokeColor: "#FF33FF",
              strokeOpacity: 1,
              strokeWeight: 2,
            },
            //同 RangingTool 的 自定义 设置，缺省为默认样式
          });
          break;
        }
        case "measureArea": {
          mouseTool.measureArea({
            strokeColor: "#80d8ff",
            fillColor: "#80d8ff",
            fillOpacity: 0.3,
            //同 Polygon 的 Option 设置
          });
          break;
        }
      }
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getmon2();
    this.getwornlistflex();
    // this.getmon();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.pestbox {
  width: 100%;
  height: 97%;
  position: relative;
  overflow: hidden;
  #mapContainer2 {
    width: 100%;
    height: 100%;
    /deep/.amap-logo {
      display: none !important;
    }
    /deep/.amap-copyright {
      display: none !important;
    }
  }
  .searchbox {
    position: absolute;
    top: 10px;
    left: 15px;
    /deep/.el-select {
      margin-right: 10px;
    }
    /deep/.el-date-editor {
      margin-right: 10px;
    }
    /deep/.el-button--info {
      background-color: #409eff;
      border-color: #409eff;
    }
  }
  .piebox {
    position: absolute;
    top: 0;
    right: 0;
    display: flex;
    height: 100%;
    transition: width 1s ease;
    .iconbox {
      width: 30px;
      height: 50px;
      background-color: chocolate;
      color: #fff;
      line-height: 50px;
      text-align: center;
      font-size: 25px;
    }
    /deep/canvas {
      border-radius: 10px;
    }
    #mychartpie {
      // background-color: #04243e;
      background-color: #fff;
      border-radius: 10px;
    }
  }
  .measurebox {
    position: absolute;
    right: 20px;
    bottom: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 0 3px rgb(0 0 0 / 50%);
    padding: 10px 5px;
    .measurebox_item {
      text-align: center;
      font-size: 14px;
    }
    .measurebox_line {
      margin: 10px 0;
      border-bottom: 1px solid;
    }
    .selmea {
      color: #409eff;
    }
  }
}
/deep/.el-dialog__body {
  padding-bottom: 0;
}
.shezhibox {
  /deep/.el-input {
    width: 50%;
  }
}
/deep/.el-date-editor {
  cursor: pointer;
  .el-range-input {
    cursor: pointer;
  }
}
/deep/.amap-controls {
  display: none !important;
}
</style>