<template>
  <div>
    <el-col :span="24">
      <el-row>
        <el-col :span="6" class="overview_block_item">
          <el-card class="overview_block_item_card" style="background-color: #a66dd4">
            <el-row>
              <el-col :span="18">
                <h1 class="card_title">采集节点</h1>
              </el-col>
              <el-col :span="6" class="card_number">
                <i class="el-icon-cpu"></i>
              </el-col>
            </el-row>
            <el-row style="margin-top: 25px">
              <el-progress :stroke-width="10" :percentage="numberStats.server.positive/numberStats.server.all*100"
                           :show-text="false" color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col :span="12">
                  <span class="card_subtitle" @click="jumpTo('/oscm/server')">服务器在线</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">{{ numberStats.server.positive }} 台
                </el-col>
              </el-row>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-progress :stroke-width="10" :percentage="numberStats.project.positive/numberStats.project.all*100"
                           :show-text="false" color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col :span="12">
                  <span class="card_subtitle" @click="jumpTo('/oscm/project')">采集引擎启用</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">{{ numberStats.project.positive }} 个
                </el-col>
              </el-row>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="6" class="overview_block_item">
          <el-card class="overview_block_item_card" style="background-color: #6dd4b1">
            <el-row>
              <el-col :span="18">
                <h1 class="card_title">监控目标</h1>
              </el-col>
              <el-col :span="6" class="card_number">
                <i class="el-icon-aim"></i>
              </el-col>
            </el-row>
            <el-row style="margin-top: 25px">
              <el-progress :stroke-width="10"
                           :percentage="numberStats.targetWebsite.positive/numberStats.targetWebsite.all*100"
                           :show-text="false"
                           color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col :span="12">
                  <span class="card_subtitle" @click="jumpTo('/oscm/target/website')">网站目标</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">{{ numberStats.targetWebsite.positive }}
                  个
                </el-col>
              </el-row>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-progress :stroke-width="10"
                           :percentage="numberStats.targetSocial.positive/numberStats.targetSocial.all*100"
                           :show-text="false"
                           color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col :span="12">
                  <span class="card_subtitle" @click="jumpTo('/oscm/target/social')">社交帐号</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">{{ numberStats.targetSocial.positive }} 个
                </el-col>
              </el-row>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="6" class="overview_block_item">
          <el-card class="overview_block_item_card" style="background-color: #34caca">
            <el-row>
              <el-col :span="18">
                <h1 class="card_title">采集任务</h1>
              </el-col>
              <el-col :span="6" class="card_number">
                <i class="el-icon-document"></i>
              </el-col>
            </el-row>
            <el-row style="margin-top: 25px">
              <el-progress :stroke-width="10"
                           :percentage="numberStats.taskCommon.positive/numberStats.taskCommon.all*100"
                           :show-text="false"
                           color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col :span="12"><span class="card_subtitle" @click="jumpTo('/oscm/task/common')">普通任务</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">{{ numberStats.taskCommon.positive }} 个
                </el-col>
              </el-row>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-progress :stroke-width="10" :percentage="100" :show-text="false"
                           color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col :span="12">
                  <span class="card_subtitle" @click="jumpTo('/oscm/task/single')">单站点任务</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">{{ numberStats.taskSingle.all }} 个
                </el-col>
              </el-row>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="6" class="overview_block_item">
          <el-card class="overview_block_item_card" style="background-color: #63c7ff">
            <el-row>
              <el-col :span="18">
                <h1 class="card_title">运行日志</h1>
              </el-col>
              <el-col :span="6" class="card_number">
                <i class="el-icon-date"></i>
              </el-col>
            </el-row>
            <el-row style="margin-top: 25px">
              <el-progress :stroke-width="10" :percentage="numberStats.log.positive / numberStats.log.all*100"
                           :show-text="false"
                           color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col class="card_text" :span="12">采集成功率</el-col>
                <el-col class="card_text" :span="12" style="text-align: right">
                  {{ Math.floor(numberStats.log.positive / numberStats.log.all * 100) + '%' }}
                </el-col>
              </el-row>
            </el-row>
            <el-row style="margin-top: 10px">
              <el-progress :stroke-width="10" :percentage="100" :show-text="false"
                           color="#e83e8c"></el-progress>
              <el-row style="margin-top: 10px">
                <el-col class="card_text" :span="12">
                  <span class="card_subtitle" @click="jumpTo('/oscm/log')">所有日志</span>
                </el-col>
                <el-col class="card_text" :span="12" style="text-align: right">
                  {{ numberStats.log.all }} 条
                </el-col>
              </el-row>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <el-row style="margin-top: 3vh">
        <el-col :span="12" class="overview_block_item">
          <el-row class="chart_card" v-loading="lineChartLoading">
            <el-row class="stats_selector">
              <el-col :span="6" :offset="18">
                <el-select v-model="lineChartProject" size="small" placeholder="请选择"
                           @change="lineChartProjectChange()">
                  <el-option
                      v-for="item in this.projectOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
            <div id="lineReport" class="chart_area"></div>
          </el-row>
        </el-col>
        <el-col :span="12" class="overview_block_item">
          <el-row class="chart_card" v-loading="pieChartLoading">
            <el-row class="stats_selector">
              <el-col :span="12" :offset="12">
                <el-date-picker
                    v-model="pieChartTimeRange"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始时刻"
                    end-placeholder="结束时刻"
                    size="small"
                    @change="pieChartTimeRangeChange()"
                >
                </el-date-picker>
              </el-col>
            </el-row>
            <div id="pieReport" class="chart_area"></div>
          </el-row>
        </el-col>
      </el-row>
    </el-col>
  </div>
</template>
<script>
import Vue from "vue";
import echarts from "echarts";
import 'echarts/theme/macarons'
import {mapActions} from "vuex";
import {
  Row,
  Col, Progress
} from "element-ui";
import overViewApi from '../../js/api/overviewApi'
import metaDictApi from "../../js/api/metaDictApi";

Vue.use(Row);
Vue.use(Col);
Vue.use(Progress);
Vue.prototype.$echarts = echarts;
export default {
  name: "OverView",
  data() {
    return {
      numberStats: {
        server: {positive: 0, all: 0},
        project: {positive: 0, all: 0},
        targetWebsite: {positive: 0, all: 0},
        targetSocial: {positive: 0, all: 1},
        taskCommon: {positive: 0, all: 1},
        taskSingle: {positive: 0, all: 1},
        log: {positive: 0, all: 1}
      },
      lineChartLoading: false,
      pieChartLoading: false,
      lineCharData: {
        categories: [],
        data: []
      },
      pieChartData: {
        opinion: [],
        data: []
      },
      lineCharts: {},
      pieCharts: {},
      metaDict: {},
      projectOptions: [],
      lineChartProject: "",
      // currentTime: new Date(),
      pieChartTimeRange: [new Date(new Date().getTime() - 24 * 3600 * 1000), new Date()],
      pieChartTimeText: "",
      pickerOptions: {
        shortcuts: [{
          text: '最近1小时',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000);
            picker.$emit('pick', [start, end]);
            // this.setPieChartSubText("1小时内");
          }
        }, {
          text: '最近12小时',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 12);
            picker.$emit('pick', [start, end]);
            // this.setPieChartSubText("12小时内");
          }
        }, {
          text: '最近24小时',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
            // this.setPieChartSubText("24小时内");
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
            // this.setPieChartSubText("7天内");
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
            // this.setPieChartSubText("30天内");
          }
        }]
      },
    };
  },
  computed: {
    lineChartOptions: function () {
      let seriesData = [];
      let categories = [];
      let legends = [];
      for (let i = 0; i < this.lineChartData.data.length; ++i) {
        let currentSeries = {}
        currentSeries.counts = undefined;
        currentSeries = this.lineChartData.data[i];
        if (i === 0) {
          for (let j = 0; j < currentSeries.counts.length; ++j) {
            categories.push(currentSeries.counts[j][0]);
          }
          if (i + 1 < this.lineChartData.data.length) continue;
        }
        let currentName = '';
        if (currentSeries.systemFlag !== undefined)
          currentName = this.metaDict[currentSeries.systemFlag];
        else if (currentSeries.project !== undefined)
          currentName = this.metaDict[this.lineChartProject];
        else
          currentName = '全部数据';
        legends.push(currentName);

        let currentData = []
        let resultData = {}
        for (let j = 0; j < currentSeries.counts.length; ++j) {
          resultData[currentSeries.counts[j][0]] = currentSeries.counts[j][1]
        }
        for (let j = 1; j < categories.length; ++j) {
          if (resultData[categories[j]] !== undefined) {
            currentData.push(resultData[categories[j]]);
          } else {
            currentData.push(0);
          }
        }
        seriesData.push({
          data: currentData,
          name: currentName,
          type: "line",
          smooth: true,
        })
      }
      return {
        title: {
          text: '流量监测',
          textStyle: {
            color: '#303133',
            fontSize: 20
          },

        },
        xAxis: {
          name: '日期',
          type: "category",
          data: categories.slice(1),
          boundaryGap: false,
          axisLabel: {
            interval: '0',
            rotate: 45
          }
        },
        yAxis: {
          name: '采集数量',
          type: "value",
        },
        series: seriesData,
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: legends,
          orient: "verticle",
          x: 'right'
        },
      }
    },
    pieChartOptions: function () {
      console.log(this.pieChartTimeText);
      return {
        title: {
          text: '数据类型占比',
          subtext: this.pieChartTimeText,
          textStyle: {
            color: '#303133',
            fontSize: 20
          },
          itemGap: 30,
        },
        tooltip: {
          trigger: "item",
          formatter: "{b}</br> {c} ({d}%)",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        legend: {
          type: 'scroll',
          data: this.pieChartData.opinion,
          itemWidth: 20,
          itemHeight: 15,
          orient: 'vertical',
          x: 'right',
          y: 'center'
        },
        series: [
          {
            name: "引擎采集量",
            type: "pie",
            minAngle: 0,
            radius: ['0%', '45%'],
            center: ["40%", "50%"],
            selectedMode: 'single',
            avoidLabelOverlap: true,
            data: this.pieChartData.opinionData[0],
            labelLine: {
              normal: {
                show: false
              }
            },
            label: {
              normal: {
                position: 'inner',
                formatter: '{b}'
              }
            },
          },
          {
            name: "任务采集量",
            type: "pie",
            minAngle: 0,
            radius: ['60%', '85%'],
            center: ["40%", "50%"],
            selectedMode: 'single',
            avoidLabelOverlap: true,
            data: this.pieChartData.opinionData[1],
            labelLine: {
              normal: {
                show: true
              }
            },
            label: {
              normal: {
                position: 'outer',
                formatter: '{b}'
              }
            },
          },
        ],
      }
    }
  }
  ,
  mounted: function () {
    this.lineChartLoading = true;
    this.pieChartLoading = true;
    metaDictApi.queryByTableName('crawl_rules', (response) => {
      if (response.data.code === 200) {
        let tempDict = this.buildDictTree(response.data.content, 'systemFlag');
        for (let i = 0; i < tempDict.length; ++i) {
          this.metaDict[tempDict[i].value] = tempDict[i].label;
        }
      }
    })
    metaDictApi.queryByTableName('project', (response) => {
      if (response.data.code === 200) {
        this.projectOptions = this.buildDictTree(response.data.content, 'projectName');
        for (let i = 0; i < this.projectOptions.length; ++i) {
          this.metaDict[this.projectOptions[i].value] = this.projectOptions[i].label;
        }
      }
    })
    overViewApi.getCountStats((response) => {
      if (response.data.code === 200) {
        this.numberStats = response.data.content;
      }
    })
    overViewApi.getItemCountGroupByDate((response) => {
      if (response.data.code === 200) {
        let categories = [];
        let data = response.data.content;
        this.lineChartData = {
          categories: categories,
          data: data,
        }
        this.lineChartProject = "WebsiteSpider";
        this.drawLine("lineReport");
        this.lineChartLoading = false;
      } else {
        this.lineChartLoading = false;
      }
    })
    overViewApi.getItemCountGroupByTask((response) => {
      if (response.data.code === 200) {
        let opinion = [];
        let opinionData = [];
        for (let i = 0; i < response.data.content.length; ++i) {
          let localOpinionData = [];
          response.data.content[i].forEach(element => {
            if (element[1] !== 0) {
              let opinionLabel = this.metaDict[element[0]] === undefined ? element[0] : this.metaDict[element[0]]
              opinion.push(opinionLabel);
              localOpinionData.push({value: (Math.log(element[1]) / Math.log(10)).toFixed(2), name: opinionLabel});
            }
          });
          opinionData.push(localOpinionData);
        }
        this.pieChartData = {opinion: opinion, opinionData: opinionData};
        this.pieChartTimeRange[1] = new Date();
        this.pieChartTimeRange[0] = new Date(new Date().getTime() - 3600 * 1000 * 24);
        this.drawPie("pieReport");
        this.pieChartLoading = false;
      } else {
        this.pieChartLoading = false;
      }
    })
  },
  methods: {
    ...
        mapActions({
          queryAllNodesPageable: "node/queryAllNodesPageable",
        }),
    jumpTo(uri) {
      this.$router.push(uri);
    },
    drawLine(id) {
      this.lineCharts = this.$echarts.init(document.getElementById(id), 'vintage');
      this.lineCharts.clear();
      this.lineCharts.setOption(this.lineChartOptions);
    }
    ,
    drawPie(id) {
      this.pieCharts = this.$echarts.init(document.getElementById(id), 'vintage');
      this.pieCharts.clear();
      this.pieCharts.setOption(this.pieChartOptions);
    },
    pieChartTimeRangeChange() {
      let params = {
        startTime: this.pieChartTimeRange[0].getTime(),
        endTime: this.pieChartTimeRange[1].getTime()
      }
      overViewApi.postItemCountGroupByTask(params, (response) => {
        if (response.data.code === 200) {
          let opinion = [];
          let opinionData = [];
          for (let i = 0; i < response.data.content.length; ++i) {
            let localOpinionData = [];
            response.data.content[i].forEach(element => {
              if (element[1] !== 0) {
                let opinionLabel = this.metaDict[element[0]] === undefined ? element[0] : this.metaDict[element[0]]
                opinion.push(opinionLabel);
                localOpinionData.push({value: (Math.log(element[1]) / Math.log(10)).toFixed(2), name: opinionLabel});
              }
            });
            opinionData.push(localOpinionData);
          }
          this.pieChartData = {opinion: opinion, opinionData: opinionData};
          this.drawPie("pieReport");
        }
      })
    },
    lineChartProjectChange() {
      let params = {
        project: this.lineChartProject
      }
      overViewApi.postItemCountGroupByDate(params, (response) => {
        if (response.data.code === 200) {
          let categories = [];
          let data = response.data.content;
          this.lineChartData = {
            categories: categories,
            data: data,
          }
          this.lineChartProject = response.data.content[0].project;
          this.drawLine("lineReport");
        }
      })
    },
    format_number(n) {
      let b = parseInt(n).toString();
      let len = b.length;
      if (len <= 3) {
        return b;
      }
      let r = len % 3;
      return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
    },
    buildDictTree(data, columnString) {
      let siteOptions = [];
      let nodeList = [];
      data.forEach(e => {
        if (e.columnName === columnString)
          nodeList.push({
            value: e.dictCode,
            label: e.dictValue,
            children: undefined,
            parentDictCode: e.parentDictCode
          });
      })
      nodeList.forEach(e1 => {
        if (e1.parentDictCode !== undefined) {
          nodeList.forEach(e2 => {
            if (e1.parentDictCode === e2.value) {
              if (e2.children === undefined) {
                e2.children = []
              }
              e2.children.push(e1);
            }
          })
        } else {
          siteOptions.push(e1);
        }
      })
      return siteOptions;
    },
  }
}
;
</script>

<style scoped>
.overview_block_item {
  padding: 10px;
  min-height: 20vh;
}

.overview_block_item_card {
  height: 20vh;
}


.chart_card {
  height: 60vh;
}

.card_title {
  color: white;
  font-size: 24px;
}

.card_subtitle {
  color: white;
  font-size: 14px;
  margin-top: 5px;
}

.card_subtitle:hover {
  cursor: pointer;
}

.card_number {
  font-size: 24px;
  font-weight: 550;
  color: white;
  text-align: right;
}

.card_text {
  font-size: 14px;
  color: white;
}

/*.chart_card:hover {*/
/*  background: rgb(244, 244, 245);*/
/*}*/

.chart_area {
  width: 100%;
  height: 55vh;
  padding-top: 2vh;
}

.stats_selector {
  padding-top: 0;
}


</style>