<template>
  <div style="cursor: default">
    <div class="equipInfo">
      <div class="dateBox">
        <!-- <DateSearch @dateChange="dateChange"></DateSearch> -->
        <div class="viewSwitch">
          <el-button
            type="blueInfo"
            v-if="viewSwitch"
            @click="viewSwitchFun(false)"
            size="mini"
            >手动统计</el-button
          >
          <el-button
            type="blueInfo"
            v-if="!viewSwitch"
            @click="viewSwitchFun(true)"
            size="mini"
            >自动统计</el-button
          >
        </div>
        <div>
          <el-button
            type="orangeInfo"
            @click="lookPestInfo()"
            size="mini"
            >查看害虫信息</el-button
          >
        </div>
      </div>
    </div>
    <!-- 自动统计图 -->
    <div v-if="viewSwitch" >
      <div>
        <el-row :gutter="10">
          <el-col :md="24" :lg="24">
            <div class="box-card">
              <template>
                <div class="chartsSelect">
                  <el-select
                    v-model="viewSwitch2"
                    @change="screenInsect()"
                    size="mini"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in worms"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>
              </template>
              <div class="charts">
                <highcharts
                  class="highcharts"
                  :options="options"
                  v-if="Object.keys(options).length > 0"
                ></highcharts>
                <div class="noDataClass" v-else>暂无数据</div>
              </div>
            </div>
          </el-col>
          <!-- <el-col :md="24" :lg="9">
            <el-card class="box-card">
              <div class="pie">
                <highcharts
                  :options="options2"
                  v-if="Object.keys(options2).length > 0"
                ></highcharts>
                <div class="noDataClass" v-else>暂无数据</div>
              </div>
            </el-card>
          </el-col> -->
        </el-row>
      </div>
    </div>

    <!-- 手动统计 -->
    <div v-if="!viewSwitch">
      <div>
        <el-row :gutter="10">
          <el-col :md="24" :lg="24">
            <div class="box-card">
              <template>
                <div class="chartsSelect">
                  <el-select
                    v-model="viewSwitch23"
                    @change="screenInsectA()"
                    size="mini"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dropDown"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>
              </template>
              <div class="charts">
                <highcharts
                  class="highcharts"
                  :options="options3"
                  v-if="Object.keys(options3).length > 0"
                ></highcharts>
                <div class="noDataClass" v-else>暂无数据</div>
              </div>
            </div>
          </el-col>
          <!-- <el-col :md="24" :lg="9">
            <el-card class="box-card">
              <div class="pie">
                <highcharts
                  :options="options4"
                  v-if="Object.keys(options4).length > 0"
                ></highcharts>
                <div class="noDataClass" v-else>暂无数据</div>
              </div>
            </el-card>
          </el-col> -->
        </el-row>
      </div>
    </div>

  </div>
</template>

<script>
import Vue from "vue";
import DateSearch from "@/components/DateSearch";
import HighCharts, { time } from "highcharts";

export default {
  props: ["equipId", "equipType","d_id"],
  data() {
    return {
      btnSelected: "2",
      allPest: [],
      options: {},
      options2: {},
      options3: {},
      options4: {},
      equip_name: "",
      worms: [],
      // 状态信息
      equipStatus: {},
      queryInfo: {
        begin: "",
        end: "",
        page: 1,
        pageall: 1,
        pest_name: "",
        manualpage: 1,
      },
      viewSwitch: 1,
      viewSwitch2: "",
      viewSwitch23: "",
      dropDown:[],
    };
  },
  watch: {
    viewSwitch(val) {
      this.btnSelected = "2";
    },
    value1(val) {
      if (val == "选项2") {
        this.timeShow = true;
      }
      if (val == "选项1") {
        this.timeShow = false;
      }
    },
    dialogVisible(val) {
      if (val == false) {
        this.value = "";
        this.value1 = "";
        this.value2 = "";
        this.timeShow = false;
      }
    },
    discernVisible(val) {
      if (val == false) {
        var swiper = new Swiper(".swiper-container", {
          initialSlide: 0,
          observer: true, //修改swiper自己或子元素时，自动初始化swiper
          observeParents: true, //修改swiper的父元素时，自动初始化swiper
          prevButton: ".swiper-button-prev",
          nextButton: ".swiper-button-next",
        });
        swiper.destroy(true, true);
      }
    },
    discernVisibleA(val) {
      if (val == false) {
        this.tagName = "";
        this.setdataNum = {};
        this.$refs["aiPanel-editor"].getMarker().clearData();
      }
    },
  },
  created() {
    this.getPests();
  },
  mounted() {
    this.refreshData(); //设置hightcharts配置
    // 判断是自动统计还是手动统计
    if (this.viewSwitch == true) {
      //自动统计
      this.getPestAllData();
    } else if (this.viewSwitch == false) {
      //手动统计
      this.manualStatistics(); //手动统计折线图请求
    }
  },
  methods: {
    // 设置hightcharts配置
    refreshData() {
      HighCharts.setOptions({
        // 所有语言文字相关配置都设置在 lang 里
        lang: {
          resetZoom: "刷新",
          resetZoomTitle: "重置缩放比例",
        },
      });
    },

    //子向父传值
    dateChange(data) {
      this.queryInfo.begin = data.begin;
      this.queryInfo.end = data.end;
      this.queryInfo.pest_name = "";
      // 判断是自动统计还是手动统计
      if (this.viewSwitch == true) {
        //自动统计
        this.getPestAllData();
      } else if (this.viewSwitch == false) {
        //手动统计
        this.manualStatistics(); //手动统计折线图请求
      }
    },
    //获取害虫种类
    getPests() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.worm_list",
      }).then((res) => {
        if (res.data.message == "") {
          this.allPest = res.data.data;
        }
      });
    },
    // 获取折线和饼状图和数据列表
     getPestAllData(list) {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.pest_statistics",
        data: this.qs.stringify({
          d_id: this.d_id,
          start_time: this.queryInfo.begin,
          end_time: this.queryInfo.end,
          pest_name: this.queryInfo.pest_name,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.equipStatus = {
            address: res.data.data.address,
            device_name: res.data.data.device_name,
          };
          // 折线
          var ChartData = [
            {
              name: "温度（°C）",
              dat: [],
            },
            {
              name: "湿度（%）",
              dat: [],
            },
            {
              name: "害虫总数",
              dat: [],
            },
          ];
          var data = res.data.data.date;
          if (data.length > 0) {
            this.viewSwitch2 = data[0]._sname;
            for (let item of data) {
              ChartData[0].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.temperature),
              ]);
              ChartData[1].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item.humidity),
              ]);
              ChartData[2].dat.unshift([
                item.addtime * 1000 + 8 * 3600000,
                Number(item._sums),
              ]);
            }
            // console.log(ChartData)
            this.options = {
              chart: {
                zoomType: "x",
                backgroundColor: 'rgba(0,0,0,0)'
              },
              title: {
                text: "害虫变化趋势",
                align: "left",
                style: {
                  color: '#fff',
                }
              },
              subtitle: {
                text: "",
              },
              xAxis: {
                crosshair: true, //十字基准线
                type: "datetime",
                dateTimeLabelFormats: {
                  //根据时间间距X轴自动显示哪种格式
                  millisecond: "%H:%M:%S.%L",
                  second: "%H:%M:%S",
                  minute: "%H:%M",
                  hour: "%H:%M",
                  day: "%m-%d",
                  week: "%m-%d",
                  month: "%Y-%m",
                  year: "%Y",
                },
                lineColor:'#fff',
                labels: {
                  style: {
                    color: '#fff',
                  }
                },
              },
              yAxis: {
                title: {
                  text: "",
                },
                labels: {
                  style: {
                    color: '#fff',
                  }
                },
              },
              legend: {
                // layout: 'vertical',
                align: "center",
                verticalAlign: "top",
                itemStyle:{
                  color:'#fff',
                }
              },
              plotOptions: {
                series: {
                  label: {
                    connectorAllowed: false,
                  },
                  pointStart: 2010,
                },
              },
              series: [
                {
                  type: 'column',
                  name: ChartData[0].name,
                  data: ChartData[0].dat,
                },
                {
                  type: 'column',
                  name: ChartData[1].name,
                  data: ChartData[1].dat,
                },
                {
                  type: 'spline',
                  name: ChartData[2].name,
                  data: ChartData[2].dat,
                },
              ],
              colors: ["#00e29d", "#6cbbff", "#ff3f3f"],
              credits: {
                //去掉默认的highcharts.com
                enabled: false,
              },
              tooltip: {
                // crosshairs: true,
                shared: true, //折线共享
                headerFormat: "<b>{point.x:%Y-%m-%e %H:%M:%S}</b><br>",
              },
              responsive: {
                rules: [
                  {
                    condition: {
                      maxWidth: 500,
                    },
                    chartOptions: {
                      legend: {
                        layout: "horizontal",
                        align: "center",
                        verticalAlign: "bottom",
                      },
                    },
                  },
                ],
              },
            };
          } else {
            this.options = {};
            this.viewSwitch2 = "";
            this.gainInsect([]); //获取下拉框害虫种类
          }
          // 饼状和列表
          if (list != 1) {
            var percentage = res.data.data.percentage;
            if (percentage.length > 0) {
              var arr = [];
              for (let i in percentage) {
                let o = {
                  value: percentage[i].name_num,
                  label: percentage[i].name_num,
                };
                arr.push(o);
              }
              this.gainInsect(arr); //获取下拉框害虫种类

            } else {
              this.options2 = {};
            }
            
          }
        }
      });
    },


    // 手动自动切换
    viewSwitchFun(params) {
      this.viewSwitch = params;
      this.queryInfo.page = 1;
      this.queryInfo.pest_name = "";
      this.queryInfo.manualpage = 1;
      if (params == true) {
        //自动统计
        this.getPestAllData();
      } else if (params == false) {
        // console.log('手动统计')
        this.manualStatistics(); //手动统计折线图请求
      }
    },
    // 查看害虫信息
    lookPestInfo(){
      this.$store.commit('setData',{
        name:'cbd_pest_id',
        val:this.equipId
      })
      this.$store.commit('setData',{
        name:'cbd_pest_did',
        val:this.d_id
      })
      this.$router.push('cbdPestStats')
    },
   

    // 获取下拉框害虫种类-自动统计
    gainInsect(data) {
      this.worms = data;
    },

    // 下拉框筛选害虫名称
    screenInsect() {
      this.queryInfo.pest_name = this.viewSwitch2;
      this.getPestAllData(1);
    },
  

    // 手动统计-折线图数据请求
    manualStatistics(flag) {
      let that = this;
      let postData = that.qs.stringify({
        device_id: this.d_id, //设备id
        start_time: this.queryInfo.begin, //开始时间
        end_time: this.queryInfo.end, //结束时间
        pest_name: this.queryInfo.pest_name, //害虫名
        page: this.queryInfo.manualpage,
      });
      that
        .$axios({
          method: "post",
          url:
            "/api/api_gateway?method=forecast.worm_lamp.pest_manual_statistics",
          data: postData,
        })
        .then((res) => {
          if (res.data.message == "") {
            this.total = res.data.data.nums;
            var ChartData = [
              {
                name: "害虫总数(头)",
                dat: [],
              },
            ];
            if (flag != 1) {
              var data = res.data.data.dat;
              this.viewSwitch23 = res.data.data.pests.pest_name;
              if (data.length > 0) {
                var newArr = [];
                for (let item of data) {
                  var newObj = {};
                  newObj["value"] = item.pest_name;
                  newObj["label"] = item.pest_name;
                  newArr.push(newObj);
                }
                this.dropDown = newArr; //害虫名称下拉框数据
              } else {
                this.dropDown = []; //害虫名称下拉框数据
              }
              that.manualStatisticsPie(res.data); //请求手动统计饼状图数据
              that.manualStatisticsTab(res.data); //请求手动统计表格数据
            }

            var pest_list = res.data.data.pests.pest_list || [];
            if (pest_list.length > 0) {
              this.chartsLineShow = true;
              for (let ite of pest_list) {
                ChartData[0].dat.unshift([
                  ite.add_time * 1000 + 8 * 3600000,
                  Number(ite.pest_num),
                ]);
              }
              this.options3 = {
                chart: {
                  zoomType: "x",
                  backgroundColor: 'rgba(0,0,0,0)'
                },
                title: {
                  text: "害虫变化趋势",
                  align: "left",
                  style: {
                    color: '#FF00FF',
                    fontWeight: 'bold'
                  }
                },
                subtitle: {
                  text: "",
                },
                xAxis: {
                  crosshair: true, //十字基准线
                  type: "datetime",
                  dateTimeLabelFormats: {
                    //根据时间间距X轴自动显示哪种格式
                    millisecond: "%H:%M:%S.%L",
                    second: "%H:%M:%S",
                    minute: "%H:%M",
                    hour: "%H:%M",
                    day: "%m-%d",
                    week: "%m-%d",
                    month: "%Y-%m",
                    year: "%Y",
                  },
                  lineColor:'#fff',
                  labels: {
                    style: {
                      color: '#fff',
                    }
                  },
                },
                yAxis: {
                  title: {
                    text: "",
                  },
                  labels: {
                    style: {
                      color: '#fff',
                    }
                  },
                },
                legend: {
                  // layout: 'vertical',
                  align: "center",
                  verticalAlign: "top",
                  itemStyle:{
                    color:'#fff',
                  }
                },
                plotOptions: {
                  series: {
                    label: {
                      connectorAllowed: false,
                    },
                    pointStart: 2010,
                  },
                },
                series: [
                  {
                    name: ChartData[0].name,
                    data: ChartData[0].dat,
                  },
                ],
                colors: ["#00e29d", "#6cbbff", "#ff3f3f"],
                credits: {
                  //去掉默认的highcharts.com
                  enabled: false,
                },
                tooltip: {
                  // crosshairs: true,
                  shared: true, //折线共享
                  headerFormat: "<b>{point.x:%Y-%m-%e %H:%M:%S}</b><br>",
                },
                responsive: {
                  rules: [
                    {
                      condition: {
                        maxWidth: 500,
                      },
                      chartOptions: {
                        legend: {
                          layout: "horizontal",
                          align: "center",
                          verticalAlign: "bottom",
                        },
                      },
                    },
                  ],
                },
              };
            } else if (res.data.data.nums == 0) {
              this.chartsLineShow = false;
              this.options3 = {};
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 手动统计分页
    manualStatisticspage() {
      let that = this;
      let postData = that.qs.stringify({
        device_id: this.d_id, //设备id
        start_time: this.queryInfo.begin, //开始时间
        end_time: this.queryInfo.end, //结束时间
        pest_name: this.queryInfo.pest_name, //害虫名
        page: this.queryInfo.manualpage,
      });
      that
        .$axios({
          method: "post",
          url:
            "/api/api_gateway?method=forecast.worm_lamp.pest_manual_statistics",
          data: postData,
        })
        .then((res) => {
          if (res.data.message == "") {
            this.total = res.data.data.nums;
            this.manualStatisticsTab(res.data); //请求手动统计表格数据
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 手动统计-点击下拉框就切换折线图数据
    screenInsectA() {
      this.queryInfo.pest_name = this.viewSwitch23;
      this.manualStatistics(1);
    },

    //手动统计-饼状图数据
    manualStatisticsPie(data) {
      var dat = data.data.dat;
      var arr = [];
      for (var i = 0; i < dat.length; i++) {
        var a = [];
        a.push(dat[i].pest_name);
        a.push(parseInt(dat[i].pest_num));
        arr.push(a);
      }
      //判断当前是否有数据
      if (data.data.nums !== 0) {
        this.chartsPieShow = true;
        // console.log('有数据')
        var _this = this;
        this.options4 = {
          chart: {
            type: "pie",
            options3d: {
              enabled: true,
              alpha: 60,
              beta: 0,
            },
          },
          credits: {
            enabled: false,
          },
          title: {
            text: "害虫比例",
            align: "left",
          },
          tooltip: {
            headerFormat: "{series.name}<br>",
            pointFormat: "{point.name}: <b>{point.y}头</b>",
          },
          colors: ["#00e29d", "#6cbbff", "#ff3f3f"],
          plotOptions: {
            pie: {
              allowPointSelect: true,
              cursor: "pointer",
              dataLabels: {
                enabled: true,
                format: "<b>{point.name}</b>: {point.percentage:.1f} %",
              },
              point: {
                events: {
                  mouseOver: function (e) {
                    // 鼠标滑过时动态更新标题
                    // console.log(e)
                    // console.log(this.setTitle())
                    // 标题更新函数，API 地址：https://api.hcharts.cn/highcharts#Chart.setTitle
                    // VueHighcharts.setTitle({
                    //    text: e.target.name+ '\t'+ e.target.y + ' %'
                    // });
                  },
                  click(e) {
                    // 同样的可以在点击事件里处理
                    _this.viewSwitch23 = e.point.name;
                    _this.screenInsectA();
                  },
                },
              },
            },
          },
          series: [
            {
              type: "pie",
              innerSize: "80%",
              name: "害虫比例",
              data: arr,
            },
          ],
        };
      } else if (data.data.nums == 0) {
        this.chartsPieShow = false;
        this.options4 = {};
      }
    },




    // 列表图片加载失败
    errImg(e) {
      e.target.src = "/images/expertDiagnosis/ku/noData.jpg";
    },


  },
  components: {
    DateSearch,
  },
};
</script>

<style lang='less' scoped>
.box-card {
  position: relative;
}
.equipInfo {
  .equipMsg {
    font-size: 14px;
    color: #3d3d3d;
    span {
      margin-left: 5px;
    }
  }
  .dateBox {
    width: 100%;
    display: flex;
    justify-content: space-between;
    .viewSwitch {
      margin-left: 10px;
    }
  }
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.time-check {
  display: flex;
  justify-content: space-between;
  .el-input__inner {
    margin-left: 10px;
    width: 222px;
  }
  .viewSwitch {
    margin-left: 10px;
  }
}

.chartsSelect {
  text-align: right;
  position: absolute;
  z-index: 999;
  left: 0;
  right: 21px;
}
// 暂无数据
.noDataClass {
  text-align: center;
  font-size: 25px;
  line-height: 350px;
  color: rgb(122, 115, 115);
}
.highcharts{
  height: 350px;
}
</style>