<!--  -->
<template>
  <div class="statistics_box" :style="'height:' + fullHeight + 'px'">
    <!-- nav -->
    <div class="dbd">
      <!-- 返回 -->
      <el-page-header v-if="typeShow" title @back="goBack" content="虫害数据统计"></el-page-header>
      <el-page-header v-else title @back="goBack" content="病害数据统计"></el-page-header>

      <!-- 背景渐变 -->
      <div class="bgc"></div>
    </div>

    <div class="statistics_main">
      <!-- 筛选下拉框-虫害 -->
      <el-cascader
        v-if="typeShow"
        :options="optionsA"
        v-model="selectedOptions"
        placeholder="科目筛选"
        @change="result($event)"
        class="content"
        :props="props"
      ></el-cascader>
      <!-- 筛选下拉框-虫害  -->
      <!-- 筛选下拉框-病害 -->
      <el-cascader
        v-else
        :options="optionsA"
        v-model="selectedOptions"
        placeholder="种类筛选"
        @change="result($event)"
        class="content"
        :props="props"
      ></el-cascader>
      <!-- 筛选下拉框-病害  -->

      <!-- 饼状统计图 -->
      <div id="main" style="width: 100%;height: 400px;"></div>
      <!-- 饼状统计图 -->

      <!-- 表格筛选框-时间筛选 -->
      <el-date-picker
        v-model="selectedOptionsB"
        @change="resultA($event)"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
    </div>
    <!-- 表格筛选框-时间筛选 -->

    <!-- 表格 -->
    <mescroll-vue ref="mescroll" :down="mescrollDown" :up="mescrollUp" @init="mescrollInit">
      <div class>
        <!-- <el-table :data="tableData" style="width: 100%">
          <el-table-column label="日期" width="180" prop="data1">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.data1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="分类" width="180" prop="data2">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>分类: {{ scope.row.data2 }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.data2 }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column label="用户名称" width="100" prop="data3">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>用户名称: {{ scope.row.data3 }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.data3 }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column label="采集地点" width="180" prop="data5">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>采集地址: {{ scope.row.data5 }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.data5 | ellipsis }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleDerive(scope.$index, scope.row)">导出</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row, scope)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>-->

        <el-table :data="tableData" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="用户名称:">
                  <span>{{ props.row.data3 }}</span>
                </el-form-item>
                <el-form-item label="采集地址:">
                  <span>{{ props.row.data5 }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="日期" prop="data1"></el-table-column>
          <el-table-column label="分类" prop="data2"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleDerive(scope.$index, scope.row)">导出</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row, scope)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </mescroll-vue>

    <!-- 表格 -->
  </div>
</template>

<script>
import echarts from "echarts";
// 引入mescroll的vue组件
import MescrollVue from "mescroll.js/mescroll.vue";
export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 8) {
        return value.slice(0, 8) + "...";
      }
      return value;
    }
  },
  components: {
    MescrollVue // 注册mescroll组件
  },
  data() {
    //这里存放数据
    return {
      //测试
      tableData: [
        {
          id: "12987122",
          name: "好滋好味鸡蛋仔",
          category: "江浙小吃、小吃零食",
          desc: "荷兰优质淡奶，奶香浓而不腻",
          address: "上海市普陀区真北路",
          shop: "王小虎夫妻店",
          shopId: "10333"
        },
        {
          id: "12987123",
          name: "好滋好味鸡蛋仔",
          category: "江浙小吃、小吃零食",
          desc: "荷兰优质淡奶，奶香浓而不腻",
          address: "上海市普陀区真北路",
          shop: "王小虎夫妻店",
          shopId: "10333"
        },
        {
          id: "12987125",
          name: "好滋好味鸡蛋仔",
          category: "江浙小吃、小吃零食",
          desc: "荷兰优质淡奶，奶香浓而不腻",
          address: "上海市普陀区真北路",
          shop: "王小虎夫妻店",
          shopId: "10333"
        },
        {
          id: "12987126",
          name: "好滋好味鸡蛋仔",
          category: "江浙小吃、小吃零食",
          desc: "荷兰优质淡奶，奶香浓而不腻",
          address: "上海市普陀区真北路",
          shop: "王小虎夫妻店",
          shopId: "10333"
        }
      ],

      fullHeight: document.documentElement.clientHeight,
      //饼状统计图
      charts: "",
      opinion: [],
      //下拉框
      optionsA: [],
      props: {
        value: "name",
        label: "name"
      },
      selectedOptions: "",
      typeShow: true, //判断头部是虫害还是病害
      //表格
      // 表格下拉框
      selectedOptionsB: "",
      propsB: {
        value: "name",
        label: "name"
      },
      tableData: [
        {
          data1: "",
          data2: "",
          data3: "",
          data5: "",
          data6: "",
          data7: ""
        }
      ], //表格数据
      //上拉加载下拉刷新
      //测试
      mescroll: null, // mescroll实例对象
      mescrollDown: {}, //下拉刷新的配置. (如果下拉刷新和上拉加载处理的逻辑是一样的,则mescrollDown可不用写了)
      mescrollUp: {
        // 上拉加载的配置.
        callback: this.upCallback, // 上拉回调,此处简写; 相当于 callback: function(page, mescroll) { }
        //以下是一些常用的配置,当然不写也可以的.
        page: {
          num: 0, //当前页 默认0,回调之前会加1; 即callback(page)会从1开始
          size: 7 //每页数据条数,默认10
        },
        isBounce: true, //根据记录的滚动条高度回弹
        htmlNodata: '<p class="upwarp-nodata">-- 已经到底了! --</p>',
        noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于5才显示无更多数据;
        // 避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
        // 这就是为什么无更多数据有时候不显示的原因
        toTop: {
          //回到顶部按钮
          // src: "../../../static/gotop.png", //图片路径,默认null,支持网络图
          src:
            "http://pic.51yuansu.com/pic3/cover/00/65/23/5896fa4bc81fc_610.jpg", //图片路径,默认null,支持网络图
          offset: 800 //列表滚动1000px才显示回到顶部按钮
        },
        empty: {
          //列表第一页无任何数据时,显示的空提示布局; 需配置warpId才显示
          warpId: "xxid", //父布局的id (1.3.5版本支持传入dom元素)
          icon: "./static/mescroll/mescroll-empty.png", //图标,默认null,支持网络图
          tip: "暂无相关数据~" //提示
        },
        onScroll: function(mescroll, y, isUp) {
          //监听滚动条
          // console.log(y);
        },
        lazyLoad: {
          use: true // 是否开启懒加载,默认false
        }
      },
      aggregate: "" //后端传来数据的总条数
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化

  beforeRouteEnter(to, from, next) {
    // 如果没有配置顶部按钮或isBounce,则beforeRouteEnter不用写
    next(vm => {
      // 滚动到原来的列表位置,恢复顶部按钮和isBounce的配置
      vm.$refs.mescroll && vm.$refs.mescroll.beforeRouteEnter();
    });
  },
  beforeRouteLeave(to, from, next) {
    // 如果没有配置顶部按钮或isBounce,则beforeRouteLeave不用写
    // 记录列表滚动的位置,隐藏顶部按钮和isBounce的配置
    this.$refs.mescroll && this.$refs.mescroll.beforeRouteLeave();
    next();
  },
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    }
  },
  //方法集合
  methods: {
    mescrollInit(mescroll) {
      this.mescroll = mescroll; // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
    },

    // 上拉回调 page = {num:1, size:10}; num:当前页 ,默认从1开始; size:每页数据条数,默认10
    upCallback(page, mescroll) {
      let _this = this;
      _this
        .$axios({
          method: "get",
          url: "/report_forms",
          params: {
            page: this.mescrollUp.page.num,
            ret: localStorage.getItem("examineIndex")
          }
        })
        .then(res => {
          //判断data中的变量是否为空 ，为空的话存后端发来的总条数
          if (this.aggregate === "") {
            //存变量
            this.aggregate = res.data.num;
            var b = "6";
            this.aggregate = this.aggregate / b;
            this.aggregate = Math.ceil(this.aggregate); //将小数点转换为整数
          }

          //删除了默认的每页条数后判断数是否大于页码
          if (this.mescrollUp.page.num <= this.aggregate) {
            this.$axios({
              method: "get",
              url: "/report_forms",
              params: {
                page: this.mescrollUp.page.num,
                ret: localStorage.getItem("examineIndex")
              }
            })
              .then(res => {
                let arr = res.data.dat;
                // 如果是第一页需手动置空列表
                if (page.num === 1) this.redata = [];
                // 把请求到的数据添加到列表
                this.redata = this.redata.concat(arr);
                var data = [];
                for (var k = 0; k < res.data.dat.length; k++) {
                  var obj = {};
                  obj.data1 = res.data.dat[k].time; //日期
                  obj.data2 = res.data.dat[k].insect_sort; //分类
                  obj.data3 = res.data.dat[k].name; //用户名称
                  obj.data5 = res.data.dat[k].user_city; //采集地点
                  obj.data6 = res.data.dat[k].id; //id
                  obj.data7 = res.data.dat[k].del; //id

                  data[k] = obj;
                }
                _this.tableData = data;

                // 数据渲染成功后,隐藏下拉刷新的状态
                this.$nextTick(() => {
                  mescroll.endSuccess(arr.length);
                });
              })
              .catch(error => {
                mescroll.endErr();
              });
          } else if (this.mescrollUp.page.num > this.aggregate) {
            // 数据渲染成功后,隐藏下拉刷新的状态
            this.$nextTick(() => {
              mescroll.endSuccess(this.aggregate);
            });
          }

          if (this.aggregate === 0) {
            this.axiosShow = false;
            this.FenShow = false;
          }
        })
        .catch(error => {
          mescroll.endErr();
          console.log(error);
        });
    },

    //表格删除
    handleDelete(index, row) {
      console.log(index, row.data6, row.data7);
      let _this = this;
      // if (localStorage.getItem("examineIndex") === "0") {
      //   var a = 'insect'
      // } else if (localStorage.getItem("examineIndex") === "1") {
      //   var a = 'plant'
      // }
      var b = row.data6 + "";
      var a = new Array(b);
      let postData = _this.$qs.parse({
        ret: row.data7,
        del: a
      });
      _this
        .$axios({
          method: "post",
          url: "/deleuser",
          data: postData
        })
        .then(res => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          // const timer = setInterval(() => {
          //   location.reload();
          // }, 1500);
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: "删除失败!"
          });
        });
    },

    //表格导出
    handleDerive(index, row) {
      //转换id的类型
      var a = row.data6;
      var b = a.toString();

      let postData = this.$qs.parse({
        id: b,
        ret: ""
      });
      this.$axios({
        method: "post",
        url: "/expores",
        data: postData
      })
        .then(res => {
          window.location.href = "bigservers/" + res.data[0].file;
        })
        .catch(err => {
          this.$notify({
            title: "失败",
            message: "请求失败",
            type: "error",
            duration: 1000
          });
        });
    },

    //返回上一步
    goBack() {
      let _this = this;
      localStorage.removeItem("sortName");
      _this.$router.push("/examine");
    },

    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    //饼状统计图
    drawPie(id) {
      this.charts = echarts.init(document.getElementById(id));
      //判断是虫害还是病害
      if (localStorage.getItem("examineIndex") === "0") {
        //虫害数据
        let postData = this.$qs.parse({
          sort: localStorage.getItem("sortName")
        });
        //判断是默认，还是选择后的数据请求
        if (localStorage.getItem("sortName") !== null) {
          this.$axios({
            method: "post",
            url: "/count_num",
            data: postData
          })
            .then(res => {
              this.charts.setOption({
                tooltip: {
                  trigger: "item"
                },
                legend: {
                  orient: "vertical",
                  x: "left",
                  data: this.opinion
                },
                series: [
                  {
                    name: "类别",
                    type: "pie",
                    radius: ["45%", "70%"],
                    avoidLabelOverlap: false,
                    label: {
                      normal: {
                        show: false,
                        position: "center"
                      },
                      emphasis: {
                        show: true,
                        textStyle: {
                          fontSize: "60",
                          fontWeight: "blod"
                        }
                      }
                    },
                    labelLine: {
                      normal: {
                        show: false
                      }
                    },
                    data: res.data
                  }
                ]
              });
              // this.charts.clear();
            })
            .catch(err => {
              console.log(err);
            });
        } else if (localStorage.getItem("sortName") === null) {
          this.$axios({
            method: "get",
            url: "/count_num"
          })
            .then(res => {
              this.charts.setOption({
                tooltip: {
                  trigger: "item"
                },
                legend: {
                  orient: "vertical",
                  x: "left",
                  data: this.opinion
                },
                series: [
                  {
                    name: "类别",
                    type: "pie",
                    radius: ["45%", "70%"],
                    avoidLabelOverlap: false,
                    label: {
                      normal: {
                        show: false,
                        position: "center"
                      },
                      emphasis: {
                        show: true,
                        textStyle: {
                          fontSize: "60",
                          fontWeight: "blod"
                        }
                      }
                    },
                    labelLine: {
                      normal: {
                        show: false
                      }
                    },
                    data: res.data
                  }
                ]
              });
              // this.charts.clear();
            })
            .catch(err => {
              console.log(err);
            });
        }
      } else if (localStorage.getItem("examineIndex") === "1") {
        let postData = this.$qs.parse({
          sort: localStorage.getItem("sortName")
        });
        //判断是默认，还是选择后的数据请求
        if (localStorage.getItem("sortName") !== null) {
          this.$axios({
            method: "post",
            url: "/count_plant",
            data: postData
          })
            .then(res => {
              this.charts.setOption({
                tooltip: {
                  trigger: "item"
                },
                legend: {
                  orient: "vertical",
                  x: "left",
                  data: this.opinion
                },
                series: [
                  {
                    name: "类别",
                    type: "pie",
                    radius: ["45%", "70%"],
                    avoidLabelOverlap: false,
                    label: {
                      normal: {
                        show: false,
                        position: "center"
                      },
                      emphasis: {
                        show: true,
                        textStyle: {
                          fontSize: "60",
                          fontWeight: "blod"
                        }
                      }
                    },
                    labelLine: {
                      normal: {
                        show: false
                      }
                    },
                    data: res.data
                  }
                ]
              });
              // this.charts.clear();
            })
            .catch(err => {
              console.log(err);
            });
        } else if (localStorage.getItem("sortName") === null) {
          this.$axios({
            method: "get",
            url: "/count_plant"
          })
            .then(res => {
              this.charts.setOption({
                tooltip: {
                  trigger: "item"
                },
                legend: {
                  orient: "vertical",
                  x: "left",
                  data: this.opinion
                },
                series: [
                  {
                    name: "类别",
                    type: "pie",
                    radius: ["45%", "70%"],
                    avoidLabelOverlap: false,
                    label: {
                      normal: {
                        show: false,
                        position: "center"
                      },
                      emphasis: {
                        show: true,
                        textStyle: {
                          fontSize: "60",
                          fontWeight: "blod"
                        }
                      }
                    },
                    labelLine: {
                      normal: {
                        show: false
                      }
                    },
                    data: res.data
                  }
                ]
              });
              // this.charts.clear();
            })
            .catch(err => {
              console.log(err);
            });
        }
      }
    },

    //表格

    //图标-下拉框
    result(e) {
      localStorage.setItem("sortName", e[0]);
      this.drawPie("main");
    },

    //表格-下拉框
    resultA(e) {
      let _this = this;
      //开始时间
      const a = new Date(e[0]);
      const resDate =
        a.getFullYear() +
        "-" +
        this.p(a.getMonth() + 1) +
        "-" +
        this.p(a.getDate());
      const resTime =
        this.p(a.getHours()) +
        ":" +
        this.p(a.getMinutes()) +
        ":" +
        this.p(a.getSeconds());

      //结束时间
      const b = new Date(e[1]);
      const resDateA =
        b.getFullYear() +
        "-" +
        this.p(b.getMonth() + 1) +
        "-" +
        this.p(b.getDate());
      const resTimeA =
        this.p(b.getHours()) +
        ":" +
        this.p(b.getMinutes()) +
        ":" +
        this.p(b.getSeconds());

      let postData = this.$qs.parse({
        ret: localStorage.getItem("examineIndex"),
        start_time: resDate,
        end_time: resDateA,
        page: this.mescrollUp.page.num
      });
      this.$axios({
        method: "post",
        url: "/screen_time",
        data: postData
      })
        .then(res => {
          if (res.data.dat.length === 0) {
            for (var k = 0; k < res.data.dat.length; k++) {
              var obj = {};
              obj.data1 = res.data.dat[k].time; //日期
              obj.data2 = res.data.dat[k].insect_sort; //分类
              obj.data3 = res.data.dat[k].name; //用户名称
              obj.data5 = res.data.dat[k].user_city; //采集地点
              data[k] = obj;
            }
            _this.tableData = data;
            const timer = setInterval(() => {
              location.reload();
            }, 2000);
          } else if (res.data.dat.length !== 0) {
            // this.redata = res.data.dat;
            var data = [];
            for (var k = 0; k < res.data.dat.length; k++) {
              var obj = {};
              obj.data1 = res.data.dat[k].time; //日期
              obj.data2 = res.data.dat[k].insect_sort; //分类
              obj.data3 = res.data.dat[k].name; //用户名称
              obj.data5 = res.data.dat[k].user_city; //采集地点
              data[k] = obj;
            }
            _this.tableData = data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    //转换时间格式
    p(s) {
      return s < 10 ? "0" + s : s;
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let _this = this;
    //请求下拉框中的数据
    if (localStorage.getItem("examineIndex") === "0") {
      this.typeShow = true;
      //请求下拉框中的数据-虫害
      _this
        .$axios({
          method: "get",
          url: "/count_num"
        })
        .then(res => {
          this.optionsA = res.data;
        })
        .catch(err => {
          console.log(err);
        });
    } else if (localStorage.getItem("examineIndex") === "1") {
      this.typeShow = false;
      //请求下拉框中的数据-虫害
      _this
        .$axios({
          method: "get",
          url: "/count_plant"
        })
        .then(res => {
          this.optionsA = res.data;
        })
        .catch(err => {
          console.log(err);
        });
    }

    //请求表格数据
    this.$axios({
      method: "get",
      url: "/report_forms",
      params: {
        page: this.mescrollUp.page.num,
        ret: localStorage.getItem("examineIndex")
      }
    })
      .then(res => {
        // _this.tableData = res.dara.dat[0]
        var data = [];
        for (var k = 0; k < res.data.dat.length; k++) {
          var obj = {};
          obj.data1 = res.data.dat[k].time; //日期
          obj.data2 = res.data.dat[k].insect_sort; //分类
          obj.data3 = res.data.dat[k].name; //用户名称
          obj.data5 = res.data.dat[k].user_city; //采集地点
          obj.data6 = res.data.dat[k].id; //id
          obj.data7 = res.data.dat[k].del; //id
          data[k] = obj;
        }
        _this.tableData = data;
      })
      .catch(err => {
        console.log(erro);
      });
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight();
    // 统计图
    this.$nextTick(function() {
      this.drawPie("main");
    });
  },

  //清除内存中残留的echarts图例
  beforeDestroy() {
    this.charts.clear();
  }
};
</script>
<style lang="scss">
// @import "../../assets/style/bus.scss";
@import "../../assets/style/scss/statistics.scss";
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.el-form--inline .el-form-item__label {
  font-size: 30px;
  width: 2.1rem;
}

.el-table__expand-icon>.el-icon {
  position:absolute;
  top: 20%;
  left: 50%;
}

.el-icon-arrow-right:before {
  font-size: 25px;
}

.el-form-item__content {
  font-size: 25px;
}
</style>

