<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>测报系统</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/index/cbd' }"
        >虫情测报</el-breadcrumb-item
      >
      <el-breadcrumb-item>害虫分析</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="equipInfo">
      <div>
        <el-button type="success" size="mini" @click="goBackPage()"
          ><i class="el-icon--left el-icon-d-arrow-left"></i>返回</el-button
        >
      </div>
      <div class="dateBox">
        <!-- <DateSearch @dateChange="dateChange"></DateSearch> -->
        <DateSearch
          ref="timeCirculation"
          @dateChange="dateChange"
          @btnSelected="btnSelected"
          @timeScreen="timeScreen"
        ></DateSearch>
      </div>
    </div>
    <el-row :gutter="10">
      <el-col :md="24" :lg="15">
        <el-card class="box-card" v-loading="lineLoading" style="height: 442px">
          <div class="chartsSelect">
            <el-select
              v-model="pestName"
              @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>
          <div class="charts">
            <highcharts
              :options="options"
              v-if="Object.keys(options).length > 0"
            ></highcharts>
            <div class="noDataClass" v-else>暂无数据</div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="24" :lg="9">
        <el-card v-loading="pieLoading" style="height: 442px">
          <div class="chartsSelect">
            <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 class="dataTableSearch">
      <!-- <el-button type="primary" size="mini" @click="deriveData()"
        >导出</el-button
      > -->
      <el-button
        type="primary"
        size="mini"
        v-if="dataSwitchType == 0"
        @click="dataSwitch(1)"
        >详细信息</el-button
      >
      <el-button type="primary" size="mini" v-else @click="dataSwitch(0)"
        >统计信息</el-button
      >
    </div>
    <!-- 统计信息 -->
    <el-card class="box-card" v-if="dataSwitchType == 0">
      <el-table :data="tableDataA" stripe style="width: 100%">
        <el-table-column
          v-for="(item, index) in tableHeadTxt"
          :key="index"
          :prop="item[1]"
          :label="item[0]"
        >
          <template slot-scope="scope">{{
            scope.row[scope.column.property]
          }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              style="background: #f7aa05"
              type="warning"
              size="mini"
              id="viewerDom"
              v-viewer
              @click="insectData(scope.$index, scope.row)"
              >害虫资料</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableDataAllA.length > 0"
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="queryInfo.page"
        @current-change="changePage"
        :page-size="10"
      ></el-pagination>
    </el-card>

    <!-- 详细信息 -->
    <el-card class="box-card" v-else>
      <el-table
        :data="tableDataB"
        stripe
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          v-for="(item, index) in tableHeadTxtAll"
          :key="index"
          :prop="item[1]"
          :label="item[0]"
        >
          <template slot-scope="scope">{{
            scope.row[scope.column.property]
          }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              style="background: #f7aa05"
              type="warning"
              size="mini"
              id="viewerDom"
              v-viewer
              @click="insectData(scope.$index, scope.row)"
              >害虫资料</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableDataAllB.length > 0"
        background
        layout="prev, pager, next"
        :total="totalall"
        :current-page="queryInfo.pageall"
        @current-change="changePageAll"
        :page-size="10"
      ></el-pagination>
    </el-card>
    <!-- 病虫害档案弹框 -->
    <el-dialog
      title="病虫害档案"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
    >
      <ul class="expertDiagnosis_library_main_popUp">
        <li class="expertDiagnosis_library_main_popUp_li">
          <div class="expertDiagnosis_library_main_popUp_li_name">
            害虫名称：
          </div>
          <div class="expertDiagnosis_library_main_popUp_li_nameVal">
            {{ popUpData.name }}
          </div>
        </li>

        <li class="expertDiagnosis_library_main_popUp_li">
          <div class="expertDiagnosis_library_main_popUp_li_img">
            害虫图片：
          </div>
          <div class id="viewerDom" v-viewer>
            <img
              style="cursor: pointer"
              :src="popUpData.img_urls"
              @error="$imghost + errImg"
              alt
              class="expertDiagnosis_library_main_popUp_li_imgVal"
            />
          </div>
        </li>

        <li class="expertDiagnosis_library_main_popUp_li">
          <div class="expertDiagnosis_library_main_popUp_li_details">
            详细信息：
          </div>
          <!-- <div class="expertDiagnosis_library_main_popUp_li_detailsVal">
            {{ popUpData.prevention }}
          </div> -->

          <div>
            <div
              v-for="(item, index) in preventio"
              :key="index"
              class="expertDiagnosis_library_main_popUp_li_detailsVal"
            >
              {{ item }}
            </div>
          </div>
        </li>
      </ul>
    </el-dialog>
    <!-- 导出对话框 -->
    <el-dialog title="导出信息" :visible.sync="dialogVisible" width="30%">
      <!-- <span>这是一段信息</span> -->

      <!-- 下拉框和输入框 -->
      <ul class="iptUl">
        <li class="iptList">
          <div class="iptTxt"><span style="color: red">*</span>文件名称：</div>
          <div class="iptBox">
            <el-input
              placeholder="请输入文件的名称"
              v-model="derivevalue"
              clearable
            >
            </el-input>
          </div>
        </li>
        <li class="iptList">
          <div class="iptTxt">下载类型：</div>
          <div class="iptBox">
            <el-select v-model="derivevalue1" placeholder="请选择">
              <el-option
                v-for="item in optionsA"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </li>
        <!-- <li class="iptList" v-show="timeShow">
          <div class="iptTxt"><span style="color: red">*</span>时间段：</div>
          <div class="iptBox">
            <el-date-picker
              v-model="value2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
        </li> -->
      </ul>
      <!-- 下拉框和输入框 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addData()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导出对话框 -->
  </div>
</template>

<script>
import DateSearch from "@/components/DateSearch";
import HighCharts from "highcharts";
export default {
  data() {
    return {
      queryInfo: {
        begin: "",
        end: "",
        page: 1,
        pageall: 1,
      },
      dataSwitchType: 1, //0代表统计信息，1代表详细信息
      // 自动统计动态表头
      tableHeadTxt: [
        ["害虫名称", "name"],
        ["害虫数量", "sum"],
      ],
      tableHeadTxtAll: [
        ["害虫名称", "name"],
        ["害虫数量", "sum"],
        ["统计时间", "upl_time"],
      ],
      tableDataAllA: [], //统计
      tableDataAllB: [], //详细
      tableDataA: [],
      tableDataB: [],
      worms: [],
      pestName: "",
      peiData: [],
      lineData: [],
      ChartData: [
        {
          name: "温度（°C）",
          dat: [],
        },
        {
          name: "湿度（%）",
          dat: [],
        },
        {
          name: "害虫总数",
          dat: [],
        },
      ],
      allPest: [],
      lineLoading: true,
      pieLoading: true,
      popUpData: {}, //虫害数据
      preventio: [], // 虫害详情数据
      dialogFormVisible: false,
      timeScreenData: null, //保存一个标识，用来区分是点击还是自动获取
      derivevalue: "", //导出文件名
      derivevalue1: "", //导出文件类型
      dialogVisible: false,
      optionsA: [
        {
          value: "选项1",
          label: "全部",
        },
        // {
        //   value: "选项2",
        //   label: "时间段",
        // },
      ],
    };
  },
  created() {
    this.getPests();
  },
  mounted() {
    // this.getPestAllData();
    this.refreshData();
  },
  computed: {
    options() {
      if (this.ChartData[0].dat.length > 0) {
        return {
          chart: {
            zoomType: "x",
            // zoomType: 'y'
          },
          title: {
            text: "害虫变化趋势",
            align: "left",
          },
          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",
            },
          },
          yAxis: {
            title: {
              text: "",
            },
          },
          legend: {
            // layout: 'vertical',
            align: "center",
            verticalAlign: "top",
          },
          plotOptions: {
            series: {
              label: {
                connectorAllowed: false,
              },
              pointStart: 2010,
            },
          },
          series: [
            {
              name: this.ChartData[0].name,
              data: this.ChartData[0].dat,
            },
            {
              name: this.ChartData[1].name,
              data: this.ChartData[1].dat,
            },
            {
              name: this.ChartData[2].name,
              data: this.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 {
        return {};
      }
    },
    options2() {
      let _this = this;
      if (this.peiData.length > 0) {
        return {
          chart: {
            type: "pie",
          },
          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.pestName = e.point.name;
                    _this.screenInsect();
                  },
                },
              },
            },
          },
          series: [
            {
              type: "pie",
              innerSize: "80%",
              name: "害虫比例",
              data: this.peiData,
            },
          ],
        };
      } else {
        return {};
      }
    },
    total() {
      return this.tableDataAllA.length;
    },
    totalall() {
      return this.tableDataAllB.length;
    },
  },
  methods: {
    refreshData() {
      HighCharts.setOptions({
        lang: {
          resetZoom: "刷新",
          resetZoomTitle: "重置缩放比例",
        },
      });
    },

    //子向父传值
    dateChange(data) {
      this.queryInfo.begin = data.begin;
      this.queryInfo.end = data.end;
      this.lineLoading = true;
      this.pieLoading = true;
      this.pestName = "";
      this.getPestAllData();
    },
    btnSelected(data) {
      console.log(data);
    },
    // 当使用日期筛选
    timeScreen(data) {
      this.timeScreenData = data;
    },
    dataSwitch(flag) {
      this.dataSwitchType = flag;
    },
    insectData(index, row) {
      let obj = {
        code: "2", //1病害 2虫害
        name: row.name, //害虫名称
        page: 1,
      };
      this.$axios({
        method: "post",
        url: "/api/api_gateway?method=pest.pests.pests_search",
        data: this.qs.stringify(obj),
      })
        .then((res) => {
          if (res.data.data.nums == 0) {
            //没有数据
            this.$message({
              message: "暂无此虫害的信息",
              type: "warning",
              duration: 1500,
            });
          } else if (res.data.data.data.length !== 0) {
            //有数据
            this.insectAxios(res.data.data.data[0].id);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    insectAxios(id) {
      console.log(id);
      let postData = this.qs.stringify({
        code: "2",
        page: 1,
        pest_id: id,
      });
      this.$axios({
        method: "post",
        url: "api/api_gateway?method=pest.pests.pests_info",
        data: postData,
      })
        .then((res) => {
          var data = res.data.data;
          this.popUpData = data;
          let Adata = data.prevention;
          var a = Adata.replace(/]/g, "：");
          let Bdata = new Array();
          Bdata = a.split("[");
          this.preventio = Bdata;
          this.dialogFormVisible = true;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changePage() {},
    tableRowClassName(row, rowIndex) {},
    //返回上一页
    goBackPage() {
      this.$router.go(-1);
    },
    // 获取折线和饼状图和数据列表
    getPestAllData() {
      // this.lineLoading = true;
      // this.pieLoading = true;
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.pest_statistics_total",
        data: this.qs.stringify({
          start_time: this.queryInfo.begin,
          end_time: this.queryInfo.end,
          pest_name: this.pestName,
        }),
      }).then((res) => {
        // console.log(res.data.data.date);
        // 自动获取数据
        if (res.data.data.date.length == 0 && this.timeScreenData == null) {
          this.$refs.timeCirculation.say();
          console.log("这是自动的");
          // this.lineLoading = false;
          // this.pieLoading = false;
        } else {
          console.log("这是点击的");
        }

        if (res.data.data) {
          let { date, percentage, time_d_sums } = res.data.data;
          if (percentage.length > 0) {
            //害虫种类，下拉框
            this.worms = percentage.map((item) => {
              // 表格统计信息
              this.tableDataAllA.push({
                name: item.name_num,
                sum: item.sum,
              });
              return {
                value: item.name_num,
                label: item.name_num,
              };
            });
            this.tableDataA = this.tableDataAllA.slice(0, 10);
            this.worms.unshift({
              value: "",
              label: "全部",
            });
            // 饼状图
            this.peiData = percentage.map((item) => {
              return { name: item.name_num, y: item.sum };
            });
          }

          // 判断当前害虫名称是否有数据
          if (this.pestName == "") {
            this.ChartData = [
              {
                name: "温度（°C）",
                dat: [],
              },
              {
                name: "湿度（%）",
                dat: [],
              },
              {
                name: "害虫总数",
                dat: [],
              },
            ];
          } else {
            this.ChartData = [
              {
                name: "温度（°C）",
                dat: [],
              },
              {
                name: "湿度（%）",
                dat: [],
              },
              {
                name: this.pestName,
                dat: [],
              },
            ];
          }

          // 折线图
          for (let i of date) {
            this.ChartData[0].dat.push([i.addtime * 1000, Number(i.at)]);
            this.ChartData[1].dat.push([i.addtime * 1000, Number(i.ah)]);
            this.ChartData[2].dat.push([i.addtime * 1000, Number(i._sums)]);
          }
          // console.log(this.ChartData[0].dat)
          console.log(this.ChartData[2]);
          console.log("-------------------------");
          console.log(this.pestName);

          // 表格详细信息
          if (time_d_sums.length > 0) {
            this.tableDataAllB = [];
            time_d_sums.forEach((i) => {
              let arr = i.pest.split("#");
              arr.forEach((j) => {
                let arr2 = j.split(",");
                let obj = {
                  name: this.allPest[arr2[0]],
                  sum: arr2[1],
                  upl_time: this.formatTime(i.addtime * 1000),
                };
                this.tableDataAllB.push(obj);
              });
            });
            this.tableDataB = this.tableDataAllB.slice(0, 10);
          }
        }
        this.lineLoading = false;
        this.pieLoading = false;
      });
    },
    screenInsect() {
      this.lineLoading = true;
      this.getPestAllData();
    },
    //获取害虫种类
    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;
        }
      });
    },
    changePage(e) {
      console.log(111);
      this.tableDataA = this.tableDataAllA.slice((e - 1) * 10, 10 * e);
    },
    changePageAll(e) {
      console.log(222);
      this.tableDataB = this.tableDataAllB.slice((e - 1) * 10, 10 * e);
    },
    deriveData() {
      this.dialogVisible = true;
    },
    addData() {
      var that = this;
      if (that.derivevalue == "") {
        this.$message({
          message: "请将必填项填写完整",
          type: "warning",
          duration: 1500,
        });
      } else if (
        that.derivevalue1 !== ""
      ) {
        var begin = this.queryInfo.begin;
        var end = this.queryInfo.end;
        window.location.href =
          this.$deriveData +
          "/api/cbd_export?device_id=" +
          this.$route.params.d_id +
          "&filename=" +
          that.derivevalue +
          "&start_time=" +
          begin +
          "&end_time=" +
          end +
          "&device_type=7";
      }
    },
  },
  components: {
    DateSearch,
  },
};
</script>

<style lang='less' scoped>
.equipInfo {
  .equipMsg {
    font-size: 14px;
    color: #3d3d3d;
    span {
      margin-left: 5px;
    }
  }
  .dateBox {
    display: flex;
  }
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 10px;
}
.dataTableSearch {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  .el-input__inner {
    width: 222px;
  }
}
.box-card {
  position: relative;
  .chartsSelect {
    text-align: right;
    position: absolute;
    z-index: 999;
    left: 0;
    right: 21px;
  }
}
// 弹框
.expertDiagnosis_library_main_popUp {
  .expertDiagnosis_library_main_popUp_li {
    display: flex;
    margin: 0 0 30px 0;
    // 害虫名称
    .expertDiagnosis_library_main_popUp_li_name {
      color: #000;
      font-size: 16px;
      font-weight: 550;
    }
    .expertDiagnosis_library_main_popUp_li_nameVal {
      font-weight: 550;
    }
    // 害虫图片
    .expertDiagnosis_library_main_popUp_li_img {
      font-size: 16px;
      font-weight: 550;
      color: #000;
    }
    .expertDiagnosis_library_main_popUp_li_imgVal {
      width: 160px;
      height: 160px;
      border-radius: 10px;
    }
    // 详细信息
    .expertDiagnosis_library_main_popUp_li_details {
      // width: 188px;
      width: 80px;
      font-size: 16px;
      font-weight: 550;
      color: #000;
    }
    .expertDiagnosis_library_main_popUp_li_detailsVal {
      line-height: 30px;
      font-weight: 550;
      width: 800px;
      text-align: left;
    }
  }
}

// 暂无数据
.noDataClass {
  text-align: center;
  line-height: 400px;
  color: #827e7e;
  font-size: 30px;
}

// 表格文字居中
/deep/.el-table th > .cell {
  text-align: center;
}

/deep/.el-table .cell {
  text-align: center;
}
.iptList {
  display: flex;
  margin: 15px 0 15px 0;
  .iptTxt {
    text-align: right;
    width: 20%;
    margin: 0 5% 0 0;
    display: inline-block;
  }
  .iptBox {
    width: 40%;
  }
}
</style>