<template>
  <div class="urbanExpressNews">
    <el-button type="primary" class="export" @click="exportfun">
      导出
    </el-button>
    <el-table
      :data="tableData"
      v-if="tableData.length"
      :header-cell-style="{ backgroundColor: '#f4f5f7', color: '#333333' }"
      @expand-change="rowClick"
      @sort-change="sortFun"
      style="width: 100%"
      :default-sort="{ prop: 'stadate', order: 'descending' }"
    >
      <el-table-column type="expand">
        <template #default="props">
          <div :class="'loadare' + props.row.epg_id">
            <el-row v-if="item.programType !== 'simple'">
              <el-col :span="20">
                <div :ref="'huashanChart' + props.row.epg_id"></div>
              </el-col>
              <el-col :span="4">
                <div :ref="'huashanListChart' + props.row.epg_id"></div>
              </el-col>
            </el-row>
            <div v-else :ref="'huashanChart' + props.row.epg_id"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="日期"
        prop="stadate"
        sortable="custom"
      />
      <el-table-column align="center" label="栏目" prop="program_name" />
      <el-table-column
        align="center"
        label="市场占有率"
        prop="occrate"
        sortable="custom"
      >
        <template #default="scope"> {{ scope.row.occrate }}% </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="收视率"
        prop="watchrate"
        sortable="custom"
      >
        <template #default="scope">
          <watchrate-ele
            :watchrate="scope.row.watchrate"
            :zoom="item.maxRate"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
      :page-size="size"
      v-if="total / size > 1"
      v-model:current-page="current"
      @current-change="changePage"
      :total="total"
    >
    </el-pagination> -->
    <el-button
      type="default"
      style="margin: 5px auto; display: block"
      v-if="total > tableData.length"
      :loading="load"
      @click="() => changePage(current)"
      size="mini"
    >
      {{ load ? '加载中...' : '加载更多' }}
    </el-button>
  </div>
</template>

<script>
// @ is an alias to /src
import { epgDetail, epgResult } from '@/api/index';

import watchrateEle from '../components/watchrate.vue';

import * as echarts from 'echarts/core';
import { LineChart, BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  ToolboxComponent,
  VisualMapComponent,
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import config from '../../../config/index';
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LineChart,
  BarChart,
  CanvasRenderer,
  ToolboxComponent,
  VisualMapComponent,
  LabelLayout,
  UniversalTransition,
]);
const openList = [];
const openLi = [];
export default {
  name: 'urbanExpressNews',
  props: ['item'],
  data() {
    return {
      tableData: [],
      size: 10,
      load: false,
      current: 0,
      total: 1,
      direction: 'DESC',
      type: 'STADATE',
    };
  },
  mounted() {
    this.changePage(this.current);
  },
  computed: {},
  methods: {
    changePage(num) {
      if (this.load || this.total <= num * this.size) return;
      this.current = ++num;
      this.load = true;
      const p = {
        programId: this.item.id,
        page: this.current,
        pageSize: this.size,
      };
      console.log(this.data)
      this.type && (p.sort = this.type);
      this.direction && (p.order = this.direction);
      epgResult(p).then(programList => {
        this.total = programList.total;
        if (num === 1) {
          this.tableData = programList.data;
        } else this.tableData = [...this.tableData, ...programList.data];
        this.load = false;
      });
    },
    rowClick(row) {
      if (
        openList[row.epg_id] !== undefined ||
        openLi[row.epg_id] !== undefined
      ) {
        if (openList[row.epg_id]) {
          openList[row.epg_id].dispose();
          openList[row.epg_id] = undefined;
        }
        if (openLi[row.epg_id]) {
          openLi[row.epg_id].dispose();
          openLi[row.epg_id] = undefined;
        }
        return;
      }
      this.$nextTick(() => {
        epgDetail({ epgId: row.epg_id, target: '.loadare' + row.epg_id }).then(
          res => {
            let more = this.createChart(
              this.$refs['huashanChart' + row.epg_id],
              res
            );
            openList[row.epg_id] = more.chart;
            openLi[row.epg_id] = this.createBarChart(
              this.$refs['huashanListChart' + row.epg_id],
              more.height
            );
          }
        );
      });
    },
    createChart(ele, list) {
      if (!ele) return;
      const chart = echarts.init(ele);
      const height = (ele.offsetWidth * 6) / 16;
      chart.resize({
        height,
        width: ele.offsetWidth,
      });
      let option = {
        tooltip: {
          confine: true,
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
          formatter: function (data) {
            return data[0].value;
          },
        },
        grid: {
          top: '5%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: list.map(v => v.metric),
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: watchrate => {
              return watchrate;
            },
          },
          axisPointer: {
            snap: true,
          },
        },
        visualMap: {
          show: false,
          dimension: 0,
          pieces: [
            {
              lte: 6,
              color: 'green',
            },
            {
              gt: 6,
              lte: 800,
              color: 'red',
            },
            {
              gt: 8,
              lte: 14,
              color: 'green',
            },
            {
              gt: 14,
              lte: 17,
              color: 'red',
            },
            {
              gt: 17,
              color: 'green',
            },
          ],
        },
        series: [
          {
            type: 'line',
            smooth: true,
            data: list.map(v => v.watchrate),
            itemStyle: {
              opacity: 0,
            },
            lineStyle: {
              width: 1,
            },
            emphasis: {
              scale: false,
              lineStyle: {
                width: 1,
              },
            },
            markArea: {
              itemStyle: {
                color: 'rgba(255, 173, 177, 0.4)',
              },
              data: [
                [
                  {
                    name: 'Morning Peak',
                    xAxis: '07:30',
                  },
                  {
                    xAxis: '10:00',
                  },
                ],
                [
                  {
                    name: 'Evening Peak',
                    xAxis: '17:30',
                  },
                  {
                    xAxis: '21:15',
                  },
                ],
              ],
            },
          },
        ],
      };
      if (this.item.programType === 'simple') {
        delete option.visualMap;
        option.series[0].markArea = undefined;
      }
      option && chart.setOption(option);
      return { chart, height };
    },
    createBarChart(ele, height) {
      if (!ele) return;
      const chart = echarts.init(ele);
      chart.resize({
        height,
        width: ele.offsetWidth,
      });
      let option = {
        title: {},
        tooltip: {
          confine: true,
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          top: 0,
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'value',
          splitNumber: 2,
        },
        yAxis: {
          type: 'category',
          data: ['Brazil', 'Indonesia', 'USA', 'India', 'China', 'World'],
        },
        series: [
          {
            name: '2011',
            type: 'bar',
            data: [1000, 2000, 4000, 50000, 6000, 70000],
          },
        ],
      };
      option && chart.setOption(option);
      return chart;
    },
    sortFun(column) {
      this.direction = column.order ? config.order[column.order] : 'DESC';
      this.type = column.prop ? column.prop.toUpperCase() : 'STADATE';
      this.changePage(0);
    },
    exportfun() {
      let xhttp,
        that = this;
      if (window.XMLHttpRequest) xhttp = new XMLHttpRequest();
      else xhttp = new window.ActiveXObject('Microsoft.XMLHTTP');
      xhttp.responseType = 'blob';
      xhttp.open(
        'GET',
        config.base.url2 + '/epg-export?programId=' + that.item.id,
        true
      );
      xhttp.send();
      xhttp.onreadystatechange = function () {
        if (this.readyState != 4 || this.status != 200) return;
        // 组装a标签
        let elink = document.createElement('a');
        // 设置下载文件名
        let D = new Date(),
          M = D.getMonth() + 1,
          E = D.getDate();
        M > 9 ? '' : (M = ['0', M].join(''));
        E > 9 ? '' : (E = ['0', E].join(''));
        elink.download =
          that.item.programName +
          ' ' +
          [D.getFullYear(), M, E].join('-') +
          '.csv';
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(this.response);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      };
    },
  },

  beforeUnmount: function () {},
  components: {
    watchrateEle,
  },
};
</script>

<style></style>
