<template>
  <div class="RealOnline">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>新媒体</el-breadcrumb-item>
      <el-breadcrumb-item>用户分析</el-breadcrumb-item>
      <el-breadcrumb-item>实时访客</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-form
        ref="form"
        :model="form"
        size="small"
        :inline="true"
        label-width="120px"
        class="demo-form-inline"
      >
        <el-form-item label="应用">
          <el-select v-model="form.app" placeholder="请选择时段">
            <el-option
              v-for="item in cycle"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="粒度">
          <el-select v-model="form.lidu" placeholder="请选择粒度">
            <el-option
              v-for="item in lidu"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="regularData">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br />
    <el-card>
      <div class="totalText" style="display: flex; text-align: center">
        <div
          class="totalItem"
          v-for="(item, i) in total"
          :key="i + item"
          :style="{ color: item.color }"
        >
          <countTo
            :startVal="0"
            :endVal="item.value"
            :duration="1500"
          ></countTo>
          <p v-text="item.name" style="font-size: 16px;color: #000;"></p>
        </div>
      </div>
    </el-card>
    <br />
    <el-card class="box-card">
      <div class="realLineChart" ref="realLineChart"></div>
    </el-card>
  </div>
</template>

<script>
// @ is an alias to /src
import countTo from "@/components/counto/vue-countTo.vue";
import {
  getRealAppOnline,
  getRule,
  getAppList,
  getSearchData,
} from "@/api/index";

import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  ToolboxComponent,
  LegendComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LineChart,
  CanvasRenderer,
  ToolboxComponent,
  LegendComponent,
]);

// import config from "@/config/index";
let chart = undefined,
  time = undefined;
export default {
  name: "RealOnline",
  data() {
    return {
      form: {
        app: "",
        lidu: "",
      },
      total: {},
      tableData: [],
      cycle: [],
      lidu: [],
      realForm: {},
    };
  },
  mounted() {
    this.init();
  },
  computed: {},
  methods: {
    async init() {
      if (chart && chart.dispose) chart.dispose();
      const { source, appli, lidu } = await this.getAppListFunc();
      appli.map(v => {
        if ((length.length && source[v.mcode]) || source.length === 0)
          this.cycle.push({
            value: v.mname,
            label: v.mname,
          });
      });
      this.lidu = lidu.map(v => {
        return {
          value: v.mcode,
          label: v.mname,
        };
      });
      this.form = {
        // app: (this.cycle[0] || { value: "" }).value,
        app: '起点新闻',
        lidu: '60',
      };
      this.regularData();
    },
    regularData() {
      if (time) clearInterval(time);
      this.realForm = {
        appName: this.form.app,
        minute: this.form.lidu,
      };
      this.onSubmit();
      time = setInterval(this.onSubmit, 5000);
    },
    onSubmit() {
      getRealAppOnline(this.realForm)
        .then(r => {
          if (!this.$refs.realLineChart) return;
          const li = r.list || [],
            T = r.total || {},
            keys = Object.keys(T),
            total = [],
            color = ["rgb(244, 127, 146)", "rgb(17, 160, 248)"];
          const keyList = [],
            valueList_active = [],
            valueList_newUser = [];
          for (let i = 0; i < keys.length; i++) {
            const v = keys[i];
            if (typeof T[v].value !== "number") continue;
            let p = {
              name: T[v].name,
              value: T[v].value,
              color: color[i % 2],
            };
            total.push(p);
          }
          this.total = total;
          li.map(v => {
            const key = v.recMinute.split(" ")[1] || "";
            keyList.push(key);
            valueList_active.push(v.active);
            valueList_newUser.push(v.newUser);
          });
          this.createImage(keyList, valueList_active, valueList_newUser);
        })
        .catch(() => {
          if (!chart) return;
          chart.clear();
        });
    },
    createImage(keyList, valueList_active, valueList_newUser) {
      !chart && (chart = echarts.init(this.$refs.realLineChart));
      chart.resize({
        height: (this.$refs.realLineChart.offsetWidth * 4) / 16,
      });
      chart.setOption({
        tooltip: {
          confine: true,
          trigger: "axis",
        },
        toolbox: {
          feature: {
            saveAsImage: {
              type: "jpg",
              name: "实时",
            },
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        legend: {
          data: ["活跃用户", "新增用户"],
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
          data: keyList,
        },
        yAxis: {
          type: "value",
          minInterval: 1,
          axisLabel: {
            formatter(v) {
              let val = v;
              if (val >= 100000000) {
                val = (val / 100000000).toFixed(2) + "亿";
              } else if (val >= 10000) {
                val = (val / 10000).toFixed(2) + "万";
              }
              return val;
            },
          },
        },
        color: [ "rgb(17, 160, 248)","rgb(244, 127, 146)"],
        series: [
          {
            name: "活跃用户",
            data: valueList_active,
            symbolSize: 0,
            lineStyle: {
              width: 1,
            },
            type: "line",
            smooth: true,
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(17, 160, 248, 0.8)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(17, 160, 248, 0.1)", // 100% 处的颜色
                  },
                ],
                global: false, // 缺省为 false
              },
            },
          },
          {
            name: "新增用户",
            data: valueList_newUser,
            symbolSize: 0,
            lineStyle: {
              width: 1,
            },
            type: "line",
            smooth: true,
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgba(244, 127, 146, 0.8)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgba(244, 127, 146, 0.1)", // 100% 处的颜色
                  },
                ],
                global: false, // 缺省为 false
              },
            },
          },
        ],
      });
    },
    async getAppListFunc() {
      const { r, li, lidu } = await this.getAppListOri();
      let source = {
          length: 0,
        },
        appli = [];
      let prvList = r.output.data.prvRolectrl || [];
      for (let i = 0; i < prvList.length; i++) {
        const v = prvList[i];
        if (v.controlid == "RMT_SOURCE")
          (source[v.detid] = true), (source.length = source.length + 1);
      }
      if (li.status === "0") appli = li.output.data || [];
      return {
        source,
        appli,
        lidu,
      };
    },
    async getAppListOri() {
      const roleid = JSON.parse(
        window.parent.localStorage.userinfo || "{}"
      ).roleid;
      const r = await getRule({
        db: "authplat",
        exportMark: "0",
        menuid: 400,
        roleid,
      });
      const li = await getAppList({
        exportMark: "0",
        gcode: "SOURCE",
        pageid: 1,
        pagesize: 1000,
      });

      const defaultAppName = li.status == "0" ? li.output.data[0].mname : "";
      const lidu = await getSearchData({
        gcode: "TIME_MINUTE",
        source: defaultAppName,
      });
      return { r, li, lidu };
    },
  },
  components: { countTo },
};
</script>

<style>
.RealOnline {
  margin: 10px 15px;
}
.RealOnline .has-seconds .el-time-spinner__wrapper:last-child {
  display: none;
}
.totalText {
  display: flex;
}
.totalText .totalItem {
  flex: 1;
  position: relative;
  font-size: 42px;
  font-weight: 700;
  font-family: sans-serif;
}
.totalText .totalItem:not(:last-child)::after {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  content: "";
  display: block;
  width: 1px;
  background: #e7eef0;
}
</style>
