<!--  -->
<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="searchbox">
      <el-select v-model="wornvalue" placeholder="请选择害虫名称" size="mini">
        <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"
      >
        <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"
      >
        <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"
      >
      </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"
      ></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>
    <el-dialog title="设置" :visible.sync="dialogVisible" width="450px">
      <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 } 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,
    };
  },
  //监听属性 类似于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: {
    init(trap_data_arr) {
      var that = this;
      let myChart = echarts.init(document.getElementById("mychart"));
      var arr = [];
      const mapData = require("./json/shenzhen.json");
      //   const name = "深圳";
      arr.push(mapData.features);
      //   echarts.registerMap(name, mapData);
      const mapData2 = require("./json/shanwei.json");
      console.log(mapData2);
      arr.push(mapData2.features);
      //   const name2 = "汕尾";
      //   echarts.registerMap(name2, mapData2);
      const mapData3 = require("./json/huizhou.json");
      arr.push(mapData3.features);
      //   const name3 = "惠州";
      //   echarts.registerMap(name3, mapData3);

      var arr2 = arr.reduce(function (a, b) {
        return a.concat(b);
      });
      // console.log(arr2);
      var xbMap = {
        type: "FeatureCollection",
        features: arr2,
      };

      echarts.registerMap("深圳", xbMap);
      // let myChart = echarts.init(document.getElementById("mychart"));
      window.addEventListener("resize", function () {
        // undefined;
        myChart.resize();
      });
      myChart.setOption({
        backgroundColor: "#252b45",
        title: {
          left: "center",
          textStyle: {
            color: "#000",
          },
        },
        visualMap: {
          min: 0,
          max: Number(that.ruleForm.threshold),
          calculable: true,
          inRange: {
            color: ["#50a3ba", "#eac736", "#d94e5d"],
          },
          textStyle: {
            color: "#fff",
          },
        },
        geo:
          // [
          {
            map: "深圳",
            label: {
              normal: {
                show: true,
                color: "#fff",
              },
              emphasis: {
                show: true,
              },
            },
            roam: true, //是否允许缩放
            layoutCenter: ["50%", "110%"], //地图位置
            layoutSize: "200%",
            itemStyle: {
              normal: {
                color: "#031525", //地图背景色
                borderColor: "rgba(100,149,237,1)", //省市边界线
              },
              emphasis: {
                color: "rgba(37, 43, 61, .5)", //悬浮背景
              },
            },
            scaleLimit: {
              //所属组件的z分层，z值小的图形会被z值大的图形覆盖
              min: 0.5, //最小的缩放值
              max: 50,
            },
          },
        tooltip: {
          show: true,
          // formatter: "{a}{b}{c}{d}",
          formatter: function (e) {
            // console.log(e);
            if (e.seriesType == "scatter") {
              var str = ``;
              for (var i = 0; i < e.data.pest_data.length; i++) {
                str +=
                  `<p>` +
                  e.data.pest_data[i].pest_name +
                  ` ：` +
                  e.data.pest_data[i].sum +
                  ` 只</p>`;
              }
              return (
                `<div><p>设备id ：` + e.data.device_id + `</p>` + str + `</div>`
              );
            } else {
              return e.name;
            }
            // var name = e.seriesName
          },
        },
        series: [
          {
            type: "map",
            map: "深圳",
            geoIndex: 0,
            aspectScale: 0.75, //长宽比
            showLegendSymbol: false, // 存在legend时显示
            label: {
              normal: {
                show: false,
              },
              emphasis: {
                show: false,
                textStyle: {
                  color: "#fff",
                },
              },
            },
            roam: true,
            itemStyle: {
              normal: {
                areaColor: "#031525",
                borderColor: "#3B5077",
              },
              emphasis: {
                areaColor: "#2B91B7",
              },
            },
            animation: false,
            data: [],
          },
          {
            name: "害虫",
            type: "scatter",
            coordinateSystem: "geo",
            // geoIndex: 2,
            data: trap_data_arr,
            label: {
              normal: {
                formatter: "{b}",
                position: "right",
                show: true,
              },
              emphasis: {
                show: true,
              },
            },
            itemStyle: {
              normal: {
                color: "#05C3F9",
              },
            },
          },
        ],
      });
      this.pestboxloading = false;
    },
    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: "#fff",
          },
          top: "5%",
        },
        backgroundColor: "#04243E",
        tooltip: {
          title: "详情",
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "horizontal",
          bottom: "5%",
          itemWidth: 10,
          itemHeight: 10,
          x: "center",
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
          show: true,
          data: data,
        },
        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: "{d}%",
              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}：}{b|{c}}",
              rich: {
                a: {
                  padding: [0, 0, 0, 10],
                  color: "#aebfe8",
                  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",
        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) => {
        this.loading = false;
        console.log(res.data.data.pest_count);
        var trap_data = res.data.data.trap_data;
        var num = 0;
        var trap_data_arr = [];
        for (var i = 0; i < trap_data.length; i++) {
          if (trap_data[i].pest_total > num) {
            num = trap_data[i].pest_total;
          }
          var obj = {
            value: [
              trap_data[i].lng,
              trap_data[i].lat,
              trap_data[i].pest_total,
            ],
            device_id: trap_data[i].device_id,
            pest_data: trap_data[i].pest_data,
          };
          trap_data_arr.push(obj);
        }
        if (res.data.data.threshold == 0) {
          this.ruleForm.threshold = num;
        } else {
          this.ruleForm.threshold = res.data.data.threshold;
        }
        this.init(trap_data_arr);
        var pest_count = res.data.data.pest_count;
        var arr = [];
        this.wornoptions = [];
        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 obj2 = {
            point_id: pest_count[i].pest_name,
            point_name: pest_count[i].pest_name,
          };
          this.wornoptions.push(obj2);
        }
        this.initpie(arr);
      });
    },
    tabtime(times) {
      //时间转换
      var years = times.getFullYear();
      var month = times.getMonth() + 1;
      var date = times.getDate();
      return years + "-" + month + "-" + date;
    },
    oickchange(e) {
      this.start_time = this.tabtime(e[0]);
      this.end_time = this.tabtime(e[1]);
    },
    search() {
      this.getwornlist();
    },
    reset() {
      this.wornvalue = "";
      this.inoffvalue = "";
      this.versionsvalue2 = "";
      this.timevalue = "";
    },
    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 = res.data.data.org_list;
        this.inoffoptions = res.data.data.point_data;
      });
    },
    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;
              this.$message({
                showClose: true,
                message: "设置成功",
                type: "success",
              });
            } else {
              this.$message({
                showClose: true,
                message: "设置失败",
                type: "success",
              });
            }
          });
        } else {
          this.$message({
            showClose: true,
            message: "设置失败" + res.data.message,
            type: "warning",
          });
          // return false;
        }
      });
    },
    resetForm(formName) {
      this.dialogVisible = false;
      this.$refs[formName].resetFields();
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    setTimeout(() => {
      this.init();
    }, 500);
    this.getwornlist();
    // this.getmon();
    this.getmon2();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.pestbox {
  width: 100%;
  height: 97%;
  position: relative;
  overflow: hidden;
  .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;
      border-radius: 10px;
    }
  }
}
/deep/.el-dialog__body {
  padding-bottom: 0;
}
.shezhibox {
  /deep/.el-input {
    width: 50%;
  }
}
</style>