<template>
  <div class="maincomponents" ref="main">
    <div class="card">
      <div class="cardtit">传播数据</div>
      <el-row style="margin: 10px 10px 0 10px">
        <el-col :span="4">
          <el-card class="box-card" style="text-align: center">
            <div class="numTitle">{{ playT | numform }}</div>
            <div class="numValue">总传播量</div>
          </el-card>
          <br />
          <el-card class="box-card" style="text-align: center">
            <div class="numTitle">{{ publishCount | numform }}</div>
            <div class="numValue">总发稿量</div>
          </el-card>
        </el-col>
        <el-col :span="20" style="padding-left: 10px">
          <el-card class="box-card">
            <div class="pl">
              <div class="platform" v-for="(item, i) in plays" :key="i">
                <div class="line" v-if="i % 4 !== 0"></div>
                <div class="numTitle" :style="'color:' + c[i % c.length]">
                  {{ item.val | numform }}
                </div>
                <div class="numValue">{{ item.p }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-row>
      <el-col :span="15">
        <div class="card">
          <div class="cardtit">传播量趋势</div>
          <canvas id="container" style="width: 100%; height: 100%" class=""></canvas>
        </div>
      </el-col>
      <el-col :span="9" style="padding-left: 5px">
        <div class="card">
          <div class="cardtit">传播平台占比</div>
          <canvas
            id="piechart"
            style="width: 100%; height: 100%"
            class=""
            :height="height + 'px'"
          ></canvas>
        </div>
      </el-col>
    </el-row>

    <div class="card">
      <div class="cardtit">
        部门传播量排行
        <!-- <el-button-group style="float: right; margin-right: 5px">
          <el-button
            :type="type == 'ALL' ? 'primary' : ''"
            size="small"
            @click="type = 'ALL'"
          >
            全部
          </el-button>
          <el-button
            :type="type == 'MONTH' ? 'primary' : ''"
            size="small"
            @click="type = 'MONTH'"
          >
            月
          </el-button>
          <el-button
            :type="type == 'WEEK' ? 'primary' : ''"
            size="small"
            @click="type = 'WEEK'"
          >
            周
          </el-button>
        </el-button-group> -->
      </div>
      <canvas id="barChart" v-if="heightBar > 0" :height="heightBar" style="width: 100%"></canvas>
    </div>

    <div class="card">
      <div class="cardtit">热点报道</div>
      <div style="padding: 10px">
        <el-table :data="platformList" style="width: 100%">
          <el-table-column show-overflow-tooltip prop="host" label="部门"> </el-table-column>
          <el-table-column show-overflow-tooltip prop="subTopic" label="热点话题">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="playCount" label="传播量">
            <template slot-scope="scope">
              <el-popover placement="right" width="400" trigger="hover">
                <el-table :data="scope.row.topicDataList">
                  <el-table-column property="platform" label="平台"></el-table-column>
                  <el-table-column property="address" label="传播量">
                    <template slot-scope="scopeSon">
                      {{ scopeSon.row.playCount | numform }}
                    </template>
                  </el-table-column>
                </el-table>
                <div slot="reference">
                  {{ scope.row.playCount | numform }}
                  <i class="el-icon-warning" style="color: #1890ff"></i>
                </div>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="card">
      <div class="cardtit">
        发稿任务统计
        <el-select
          v-model="dep"
          style="width: 10em; float: right; margin-right: 10px"
          placeholder="请选择部门"
          @change="changeselect"
          size="small"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="T"
          type="daterange"
          @change="change"
          style="float: right; margin-right: 10px"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          size="small"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </div>
      <div style="padding: 20px">
        <el-table v-loading="loading" :data="userlist" style="width: 100%">
          <el-table-column show-overflow-tooltip prop="depName" label="部门"> </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="账号"> </el-table-column>
          <el-table-column show-overflow-tooltip prop="platform" label="平台"> </el-table-column>
          <el-table-column show-overflow-tooltip prop="publishTime" label="发稿时间">
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 5px"
          background
          layout="total, prev, pager, next"
          :total="usertotal"
          :current-page="page"
          @current-change="pagechange"
        >
        </el-pagination>
      </div>
    </div>

    <div class="card">
      <div class="cardtit">TOP30</div>
      <div style="padding: 20px">
        <el-table v-loading="loading" :data="top" style="width: 100%">
          <el-table-column show-overflow-tooltip prop="title" label="标题" width="300">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="platform" label="平台" width="50">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="depName" label="部门"> </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="账号"> </el-table-column>
          <el-table-column show-overflow-tooltip prop="readCount" label="阅读量" width="100">
            <template slot-scope="scope">
              {{ scope.row.readCount | numform }}
            </template>
          </el-table-column>
          <el-table-column width="150" show-overflow-tooltip prop="publishTime" label="发稿时间">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import F2 from '@antv/f2/lib/index-all';
import {
  platformData,
  qushiData,
  bumenData,
  //   pingtaiData,
  baodianList,
  zhanghaoData,
  bumenList,
  getTop
} from '@/api/index.js';
let linechart = null,
  barchart = null,
  piechart = null;

export default {
  name: 'Maincomponents',
  data() {
    return {
      publishCount: 0,
      playT: 0,
      plays: [],
      loading: false,
      platformList: [],
      dep: '全部',
      T: [],
      userlist: [],
      type: localStorage.type || 'ALL',
      page: 1,
      options: [],
      top: [],
      pageSize: 10,
      usertotal: 0,
      height: 0,
      c: ['#FB6161', '#EC72DC', '#F98E53', '#49BED0', '#4BCA8B'],
      heightBar: 0
    };
  },
  filters: {
    numform(text) {
      let num = text;
      if (isNaN(text)) num = '0';
      if (text >= 100000000) num = (text / 100000000).toFixed(2) - 0 + '亿';
      else if (text >= 10000) num = (text / 10000).toFixed(2) - 0 + '万';
      else num = num + '';
      return num;
    }
  },
  props: ['hd', 'topic'],
  watch: {
    type() {
      this.bmGet();
    },
    hd() {
      this.init();
    }
  },
  mounted() {
    this.height = (this.$refs.main.offsetWidth / 24) * 6.9;
  },
  computed: {},
  methods: {
    init() {
      linechart && linechart.destroy();
      barchart && barchart.destroy();
      piechart && piechart.destroy();
      linechart = null;
      barchart = null;
      piechart = null;
      this.page = 1;
      let D = new Date(),
        Year = D.getFullYear(),
        Month = D.getMonth() + 1,
        Day = D.getDate();
      let oD = new Date(Date.now() - 86400000 * 30),
        oYear = oD.getFullYear(),
        oMonth = oD.getMonth() + 1,
        oDay = oD.getDate();
      this.T = [
        [oYear, oMonth, oDay].join('-') + ' 00:00:00',
        [Year, Month, Day].join('-') + ' 23:59:59'
      ];

      baodianList(this.topic).then(r => {
        this.platformList = r || [];
      });
      platformData(this.topic).then(r => {
        let platform = {},
          pli = [];
        for (let i = 0; i < (r || []).length; i++) {
          const v = (r || [])[i];
          if (v.platform === '总传播量') {
            this.playT = v.playCount || 0;
            continue;
          }
          if (!platform[v.platform] && platform[v.platform] !== 0) {
            platform[v.platform] = pli.length;
            pli.push({ p: v.platform, val: v.playCount, a: 1 });
          } else {
            pli[platform[v.platform]] && (pli[platform[v.platform]].val += v.playCount);
          }
        }
        this.plays = pli.sort((a, b) => b.val - a.val);

        if (!pli || !pli.length) {
          document.getElementById('piechart').style.display = 'none';
        } else {
          document.getElementById('piechart').style.display = 'block';
        }
        this.$nextTick(() => {
          this.pie1(pli);
        });
      });
      qushiData(this.topic).then(r => {
        let li = r || [];
        if (!li || !li.length) {
          document.getElementById('container').style.display = 'none';
        } else {
          document.getElementById('container').style.display = 'block';
        }
        this.$nextTick(() => {
          this.line1(li);
        });
      });
      this.bmGet();
      //   pingtaiData({
      //     depRange: "ALL",
      //     title: this.topic,
      //   }).then(r => {
      //       console.log(r)
      //     this.platformList = (r || []).sort((a, b) => b.readTotal - a.readTotal);
      //   });
      this.grtzhData();
      bumenList().then(r => {
        let options = (r || []).map(v => {
          return {
            value: v.depName,
            label: v.depName
          };
        });
        options.unshift({
          value: '全部',
          label: '全部'
        });
        this.options = options;
      });

      getTop(this.topic).then(r => {
        this.top = r || [];
      });
    },
    change() {
      this.grtzhData();
    },
    changeselect() {
      this.grtzhData();
    },
    grtzhData() {
      this.loading = true;
      let t = (this.T || []).length ? this.T : ['', ''];
      const p = {
        page: this.page,
        pageSize: this.pageSize,
        title: this.topic
      };
      this.dep && this.dep !== '全部' && (p.depName = this.dep);
      t[0] && (p.startTime = t[0]);
      t[1] && (p.endTime = t[1]);
      if (p.endTime) p.endTime = p.endTime.replace('00:00:00', '23:59:59');
      zhanghaoData(p).then(r => {
        this.loading = false;
        this.userlist = r.data || [];
        this.usertotal = r.total || 0;
      });
    },
    bmGet() {
      bumenData({
        depRange: this.type,
        title: this.topic
      }).then(r => {
        let li = (r || []).reverse();
        this.heightBar = li.length ? li.length * 35 + 40 : 0;
        localStorage.type = this.type;
        if (this.heightBar === 0) return;
        let n = 0;
        (li || []).map(v => {
          n += v.publishCount;
        });
        this.publishCount = n;
        this.$nextTick(() => {
          this.bar1(li);
        });
      });
    },
    numform(text) {
      let num = text;
      if (isNaN(text)) num = '0';
      if (text >= 100000000) num = (text / 100000000).toFixed(2) - 0 + '亿';
      else if (text >= 10000) num = (text / 10000).toFixed(2) - 0 + '万';
      else num = num + '';
      return num;
    },
    line1(li) {
      if (linechart) {
        linechart.destroy();
        linechart = null;
      }
      const that = this;
      // 传播量趋势
      linechart = new F2.Chart({
        id: 'container',
        pixelRatio: window.devicePixelRatio
      });
      linechart.source(li, {
        dt: {
          tickCount: 5
        },
        playCount: {
          tickCount: 5
        }
      });
      linechart.axis('dt', {
        label: function label(text, index, total) {
          const textCfg = {};
          if (index === 0) {
            textCfg.textAlign = 'left';
          } else if (index === total - 1) {
            textCfg.textAlign = 'right';
          }
          return textCfg;
        }
      });
      linechart.scale('playCount', {
        formatter(text) {
          return that.numform(text);
        }
      });
      linechart.tooltip({
        triggerOn: ['click'],
        onShow: function onShow(ev) {
          const items = ev.items;
          items[0].name = items[0].title;
          items[1].name = null;
          items[1].value = 0;
        }
      });

      linechart.area().position('dt*playCount').color('l(90) 0:#1890FF 1:#f7f7f7').shape('smooth');
      linechart
        .line()
        .position('dt*playCount')
        .color('#1890FF')
        .style({
          lineWidth: 1
        })
        .shape('smooth');
      linechart.render();
    },
    bar1(li) {
      if (barchart) {
        barchart.destroy();
        barchart = null;
      }
      const that = this;
      barchart = new F2.Chart({
        id: 'barChart',
        pixelRatio: window.devicePixelRatio,
        padding: [10, 50, 30, 140],
        height: this.heightBar
      });

      barchart.source(li, {
        readCount: {
          tickCount: 3
        }
      });
      barchart.axis('readCount', {
        label: function label(text) {
          const textCfg = {};
          textCfg.text = that.numform(text);
          textCfg.fontSize = 12;
          return textCfg;
        },
        grid: null
      });
      barchart.axis('depName', {
        label: function label(text) {
          const textCfg = {};
          textCfg.text = text;
          textCfg.fontSize = 14;
          return textCfg;
        },
        grid: null
      });

      barchart.coord({
        transposed: true
      });
      barchart.tooltip(false);

      barchart.interval().position('depName*readCount').color('l(180) 0:#1890ff 1:#70cdd0'); // 定义柱状图渐变色
      barchart.render();
      // 绘制柱状图文本
      const offset = -5;
      const canvas = barchart.get('canvas');
      const group = canvas.addGroup();
      const shapes = {};
      li.forEach(function (obj) {
        const point = barchart.getPosition(obj);
        const text = group.addShape('text', {
          attrs: {
            x: point.x + 30,
            y: point.y + offset + 13,
            text: that.numform(obj.readCount),
            textAlign: 'center',
            textBaseline: 'bottom',
            fill: '#808080'
          }
        });

        shapes[obj.year] = text; // 缓存该 shape, 便于后续查找
      });
    },
    pie1(li) {
      if (piechart) {
        piechart.destroy();
        piechart = null;
      }
      const that = this;
      piechart = new F2.Chart({
        id: 'piechart',
        pixelRatio: window.devicePixelRatio
      });
      let lis = [];
      for (let i = 0; i < li.length; i++) {
        const v = li[i];
        if (!v.val || v.val <= 0) continue;
        lis.push(v);
      }
      piechart.source(lis);
      piechart.tooltip(false);
      piechart.legend(false);
      piechart.coord('polar', {
        transposed: true,
        innerRadius: 0.7,
        radius: 0.85
      });
      // 添加饼图文本
      piechart.pieLabel({
        anchorOffset: -10,
        label1: function label1(data, color) {
          return {
            text: data.p,
            fill: color
          };
        },
        label2: function label2(data) {
          return {
            text: ((data.val / that.playT) * 100).toFixed(2) + '%',
            fill: '#808080',
            fontWeight: 'bold'
          };
        }
      });
      piechart.axis(false);
      piechart
        .interval()
        .position('a*val')
        .color('p', [
          '#1890FF',
          '#13C2C2',
          '#2FC25B',
          '#FACC14',
          '#F04864',
          '#8543E0',
          '#3436C7',
          '#223273'
        ])
        .adjust('stack');

      piechart.render();
    },
    pagechange(p) {
      this.page = p;
      this.$nextTick(() => {
        this.grtzhData();
      });
    }
  },
  beforeDestroy() {
    linechart && linechart.destroy();
    barchart && barchart.destroy();
    piechart && piechart.destroy();
    linechart = null;
    barchart = null;
    piechart = null;
  },
  components: {}
};
</script>

<style>
.maincomponents .card {
  border-radius: 5px;
  background: #fff;
  padding: 8px 0 11px 0;
  margin-bottom: 5px;
}
.maincomponents .cardtit {
  border-left: 3px solid #1a89b3;
  padding-left: 5px;
  height: 25px;
  line-height: 25px;
}
.maincomponents .el-card__body {
  padding: 20px 0;
}
.maincomponents .numTitle {
  font-size: 24px;
  height: 1em;
  line-height: 1em;
  color: #1a89b3;
  font-weight: bold;
}
.maincomponents .numValue {
  margin-top: 8px;
  font-size: 14px;
  color: #919191;
}
.maincomponents .pl {
  width: 100%;
}
.maincomponents .platform {
  display: inline-block;
  text-align: center;
  width: 25%;
  padding-bottom: 0.5em;
  position: relative;
}
.maincomponents .line {
  border-right: 1px solid #eaeaea;
  width: 1px;
  height: 30px;
  top: 15px;
  position: absolute;
}
.maincomponents .el-table {
  color: #3b3b3b;
}
.maincomponents .el-table__header-wrapper {
  border-radius: 5px;
  overflow: hidden;
}
.maincomponents .has-gutter th {
  background: #eceff5;
  color: #3b3b3b;
}
</style>
