<template>
  <div>
    <el-card shadow="always">
      <div class="charts-box" style=" display: table; width:100%; margin-bottom: 10px;">
        <div
          style="border:1px solid #ebeef5; background-color: #fff; margin-bottom:10px; display: table-cell; border-right:none;"
          v-loading="loading"
        >
          <ve-histogram
            ref="chart-histogram"
            :title="dept_name"
            :xAxis="xAxis"
            :tooltip="tooltip"
            :series="series"
            :grid="{left:10,bottom:15,top:70}"
            :legend="Legend"
            height="250px"
            :settings="chartSettings"
            :colors="colorsintegral"
          ></ve-histogram>
        </div>

        <div
          style="border:1px solid #ebeef5; background-color: #fff; display: table-cell; width:400px;"
          v-loading="loading"
        >
          <ve-pie
            :title="{
        text:'积分构成',
        top:20,
        left:115,
        textStyle:{
        fontSize:14,
        lineHeight:30
        },
    }"
            :legend="pieLegend"
            :series="pieseries"
            :legend-visible="true"
            width="400px"
            height="250px"
          ></ve-pie>
        </div>
      </div>
    </el-card>
    <div style="height: 10px;"></div>
  </div>
</template>
<script>
import Vue from "vue";
import VCharts from "v-charts";

Vue.use(VCharts);
export default {
  props: {
    time_range: {
      type: Array,
      default: []
    },
    dept_id: {
      type: Number,
      default: 0
    },
    dept_name: {
      type: Object,
      default: ""
    }
  },
  data() {
    this.chartSettings = {
      stack: { 日期: ["奖分", "扣分"] }
    };
    return {
      histogramWidth: "200px",
      loading: false,
      Legend: {
        itemWidth: 18,
        itemHeight: 12,
        right: 10,
        top: 20
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow"
        }
      },
      xAxis: {
        type: "category",
        data: []
      },
      series: [
        {
          name: "奖分",
          type: "bar",
          stack: "分数",
          data: [],
          barMinHeight: 1
        },
        {
          name: "扣分",
          type: "bar",
          stack: "分数",
          data: [],
          barMinHeight: 0
        }
      ],
      colorsintegral: ["#5ab1ef", "#fc8675"],

      pieseries: {
        name: "姓名",
        type: "pie",
        radius: 55,
        center: [90, 140],
        label: { show: false },
        data: [],
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      },
      pieLegend: {
        type: "scroll",
        orient: "vertical",
        right: 10,
        top: 80,
        bottom: 20,
        data: []
      },

      comWidth: this.$store.getters.sidebar.opened,

      filter: {
        dept_id: [this.dept_id],
        category_id: [],
        point_type: 0,
        time_range: this.time_range
      },
      instantPickerOptions: {
        shortcuts: [
          {
            text: "本周",
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString());
              const start =
                now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000;
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000;
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "上周",
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString());
              const start =
                now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000;
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000;
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本月",
            onClick(picker) {
              const now = new Date();
              const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
              const endDate = new Date(
                now.getFullYear(),
                now.getMonth() + 1,
                0
              );
              picker.$emit("pick", [startDate.getTime(), endDate.getTime()]);
            }
          },
          {
            text: "上月",
            onClick(picker) {
              const now = new Date();
              const startDate = new Date(
                now.getFullYear() - (now.getMonth() > 0 ? 0 : 1),
                (now.getMonth() + 11) % 12,
                1
              );
              const endDate = new Date(now.getFullYear(), now.getMonth(), 0);
              picker.$emit("pick", [startDate.getTime(), endDate.getTime()]);
            }
          },
          {
            text: "本年",
            onClick(picker) {
              const now = new Date();
              const startDate = new Date(now.getFullYear(), 0, 1);
              const endDate = new Date(now.getFullYear() + 1, 0, 0);
              picker.$emit("pick", [startDate.getTime(), endDate.getTime()]);
            }
          }
        ]
      }
    };
  },
  components: {},
  methods: {
    loadChartData() {
      const params = {
        employee_id: 0
      };
      for (const item in this.filter) {
        const value = this.filter[item];
        if (item == "category_id" || item == "dept_id") {
          if (!value || value.length == 0) {
            continue;
          }
          params[item] = value[value.length - 1];
        } else if (item == "time_range") {
          if (!value || value.length < 2) {
            continue;
          }
          const timeRangeArr = value.map(x => parseInt(x / 1000));
          timeRangeArr[1] += 60 * 60 * 24 - 1;
          params[item] = timeRangeArr.join(",");
        } else {
          params[item] = value;
        }
      }

      var self = this;
      self.loading = true;
      this.$http('get',"/integral.php/point_data/chart_data_by_dept",params)
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data;
            self.loading = false;
            try {
              self.pieseries.data = [];
              const datetime = [];
              const add_point = [];
              const sub_point = [];

              if (typeof jsonData.trend_chart_data != "undefined") {
                for (const item in jsonData.trend_chart_data.labels) {
                  datetime.push(jsonData.trend_chart_data.labels[item]);
                  add_point.push(jsonData.trend_chart_data.p_positive[item]);
                  sub_point.push(
                    jsonData.trend_chart_data.p_negative[item] * -1
                  );
                }

                const pieseries = [];
                const pieLegend = [];
                for (const item in jsonData.structure_positive_chart_data) {
                  pieseries.push({
                    value: jsonData.structure_positive_chart_data[item][1],
                    name:
                      jsonData.structure_positive_chart_data[item][0] +
                      "(" +
                      jsonData.structure_positive_chart_data[item][1] +
                      ")"
                  });
                  pieLegend.push(
                    jsonData.structure_positive_chart_data[item][0] +
                      "(" +
                      jsonData.structure_positive_chart_data[item][1] +
                      ")"
                  );
                }
                self.$set(self.pieseries, "data", pieseries);
                self.$set(self.pieLegend, "data", pieLegend);
              }
              self.$set(self.series[0], "data", add_point);
              self.$set(self.series[1], "data", sub_point);
              self.$set(self.xAxis, "data", datetime);
            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  },
  watch: {
    "$store.getters.sidebar.opened": function(curVal, oldVal) {
      //左边菜单发生变化时，重新设定图表宽度，以适应屏幕
      const self = this;
      setTimeout(() => {
        self.$refs["chart-histogram"].echarts.resize();
      }, 300);
    }
  },
  created() {
    // alert(123)
    const self = this;
    this.$nextTick(() => {
      setTimeout(() => {
        self.$refs["chart-histogram"].echarts.resize();
      }, 300);
    });
    this.loadChartData();
  }
};
</script>
