<template>
  <br />
  <el-card style="margin: 0 1em;">
    <div class="title_card" v-text="title"></div>
    <br />
    <el-button-group style="margin-left: 1.5em">
      <el-button
        size="small"
        type="primary"
        v-for="(item, i) in hard_list"
        :key="'launch' + i"
        :plain="hard_act !== i"
        @click="() => hard_change(i)"
      >
        {{ item.text }}
      </el-button>
    </el-button-group>
    <br />
    <div ref="launch" id="launch"></div>
    <br />
    <div style="border-top: 1px dashed #eee"></div>
    <br />
    <el-button-group style="margin-left: 1.5em">
      <el-button
        size="small"
        type="primary"
        v-for="(item, i) in soft_list"
        :key="'trend' + i"
        :plain="soft_act !== i"
        @click="() => soft_change(i)"
      >
        {{ item.text }}
      </el-button>
    </el-button-group>
    <br />
    <div ref="trend"></div>
  </el-card>
</template>

<script>
// @ is an alias to /src
import { byIndustryTrendHard, byIndustryTrendSoft } from "@/api/index.js";
// import config from "@/config/index";
import * as echarts from "echarts";
let hard_chart = undefined;
let soft_chart = undefined;
export default {
  name: "AdvertisingEye_trend",
  data() {
    return {
      hard_act: 0,
      soft_act: 0,
      hard_list: [
        {
          text: "时长",
          proportionType: "timeSize",
          unit: "分",
          type: 2,
        },
        {
          text: "频次",
          proportionType: "pinci",
          unit: "次",
          type: 1,
        },
        {
          text: "费用",
          proportionType: "feiyong",
          unit: "万元",
          type: 3,
        },
      ],
      soft_list: [
        {
          text: "时长",
          proportionType: "timeSize",
          unit: "分",
          type: 2,
        },
        {
          text: "频次",
          proportionType: "pinci",
          unit: "次",
          type: 1,
        },
      ],
    };
  },
  props: {
    title: String,
    industry: Number,
    industryRang: Number,
    industryAct: Number,
  },
  watch: {
    industryRang() {
      this.init();
    },
    industry() {
      this.init();
    },
  },
  mounted() {
    this.init();
  },
  computed: {},
  filter: {},
  methods: {
    init() {
      byIndustryTrendHard({
        industryId: this.industry,
        dataType: this.industryRang + 1,
        type: this.hard_list[this.hard_act].type,
      }).then(r => {
        let org = r || [],
          returnObj = {
            before: org.harddatabase || [],
            now: org.harddatacompare || [],
          };
        if (!org.harddatabase || !org.harddatacompare) return;
        this.industryChart(returnObj);
      });
      byIndustryTrendSoft({
        industryId: this.industry,
        dataType: this.industryRang + 1,
        type: this.soft_list[this.soft_act].type,
      }).then(r => {
        let org = r || [],
          returnObj = {
            before: org.softdatabase || [],
            now: org.softdatacompare || [],
          };
        if (!org.softdatabase || !org.softdatacompare) return;
        this.trendChart(returnObj);
      });
    },
    hard_change(i) {
      this.hard_act = i;
      byIndustryTrendHard({
        industryId: this.industry,
        dataType: this.industryRang + 1,
        type: this.hard_list[this.hard_act].type,
      }).then(r => {
        let org = r || [],
          returnObj = {
            before: org.harddatabase || [],
            now: org.harddatacompare || [],
          };
        if (!org.harddatabase || !org.harddatacompare) return;
        this.industryChart(returnObj);
      });
    },
    soft_change(i) {
      this.soft_act = i;
      byIndustryTrendSoft({
        industryId: this.industry,
        dataType: this.industryRang + 1,
        type: this.soft_list[this.soft_act].type,
      }).then(r => {
        let org = r || [],
          returnObj = {
            before: org.softdatabase || [],
            now: org.softdatacompare || [],
          };
        if (!org.softdatabase || !org.softdatacompare) return;
        this.trendChart(returnObj);
      });
    },
    launchtrendData(list = { before: [], now: [] }, keyName) {
      const org = list;
      let old = org.before || [];
      let now = org.now || [];
      let len = Math.max(old.length, now.length),
        key = this.hard_list[this[keyName + "_act"]].proportionType;
      let keys = [],
        realKey = [[], []],
        value = [[], []],
        lendata = [];
      for (let i = 0; i < len; i++) {
        let o = old[i] || {},
          n = now[i] || {};
        if (old.length > now.length) keys.push(o.startTime);
        else keys.push(n.startTime);
        o.dt && realKey[0].push(o.dt);
        n.dt && realKey[1].push(n.dt);
        o[key] >= 0 && value[0].push(o[key]);
        n[key] >= 0 && value[1].push(n[key]);
      }
      if (old && old.length) {
        let sDate = old[0].startTime,
          eDate = old[old.length - 1].startTime;
        if (sDate === eDate) lendata.push(sDate);
        else lendata.push(`${sDate}到${eDate}`);
      }
      if (now && now.length) {
        let sDate = now[0].startTime,
          eDate = now[now.length - 1].startTime;
        if (sDate === eDate) lendata.push(sDate);
        else lendata.push(`${sDate}到${eDate}`);
      }
      return {
        keys,
        realKey,
        lendata,
        value,
      };
    },
    formatNum(num) {
      if (isNaN(num)) return 0;
      if (num >= 100000000) return (num / 10000).toFixed(2) - 0 + "亿";
      if (num >= 10000) return (num / 10000).toFixed(2) - 0 + "万";
      return num;
    },
    industryChart(list) {
      if (!this.$refs.launch) return;
      if (hard_chart && hard_chart.dispose) {
        hard_chart.dispose();
        hard_chart = undefined;
      }
      hard_chart = echarts.init(this.$refs.launch);
      let chartData = this.launchtrendData(list, "hard");
      hard_chart.resize({
        height: (this.$refs.launch.offsetWidth * 6) / 16,
      });
      let unit = this.hard_list[this.hard_act].unit;
      let c = ["#1b9ade", "#fd5555"]
      var option = {
        legend: {
          show: true,
          data: chartData.lendata,
        },
        xAxis: {
          type: "category",
          data: chartData.keys,
          boundaryGap: false,
        },
        color: c,
        yAxis: {
          name: '单位：' + this.hard_list[this.hard_act].unit,
          type: "value",
          scale: true,
          axisLabel: {
            formatter: arr => {
              return this.formatNum(arr);
            },
          },
        },
        tooltip: {
          trigger: "axis",
          confine: true,
          textStyle: {
            color: "#000000",
          },
          backgroundColor: "rgba(255,255,255,.8)",
          borderColor: "#1b9ade",
          borderWidth: 1,
          formatter: m => {
            let m0 = m[0] || {},
              m1 = m[1] || undefined;
            let tnow = list.now[m0.dataIndex] || {},
              tbefore = list.before[m0.dataIndex] || {};
            let out = `<div style='display:inline-block;width: 10px;height: 10px;border-radius: 50%;background: ${c[0]}' ></div> ${tbefore.startTime || ""}： ${
              m0.value ? m0.value - 0 : 0
            }${unit}`;
            m1 &&
              (out += ` <br /><div style='display:inline-block;width: 10px;height: 10px;border-radius: 50%;background: ${c[1]}' ></div> ${tnow.startTime || ""}： ${
                m1.value ? m1.value - 0 : 0
              }${unit}`);
            return out;
          },
        },
        grid: [{ left: 150, top: "10%", buttom: 0, right: 100 }],
        series: chartData.value.map((data, i) => {
          return {
            showSymbol: false,
            name: chartData.lendata[i],
            data,
            type: "line",
            smooth: true,
          };
        }),
      };
      option && hard_chart.setOption(option);
    },
    trendChart(list) {
      if (!this.$refs.trend) return;
      if (soft_chart && soft_chart.dispose) {
        soft_chart.dispose();
        soft_chart = undefined;
      }
      soft_chart = echarts.init(this.$refs.trend);
      let chartData = this.launchtrendData(list, "soft");
      soft_chart.resize({
        height: (this.$refs.trend.offsetWidth * 6) / 16,
      });
      let c = ["#1b9ade", "#fd5555"];
      let unit = this.soft_list[this.soft_act].unit;
      var option = {
        legend: {
          show: true,
          data: chartData.lendata,
        },
        xAxis: {
          type: "category",
          data: chartData.keys,
        },
        color: c,
        tooltip: {
          trigger: "axis",
          confine: true,
          textStyle: {
            color: "#000000",
          },
          backgroundColor: "rgba(255,255,255,.8)",
          borderColor: "#1b9ade",
          borderWidth: 1,
          formatter: m => {
            let m0 = m[0] || {},
              m1 = m[1] || undefined;
            let tnow = list.now[m0.dataIndex] || {},
              tbefore = list.before[m0.dataIndex] || {};
            let out = "<div style='display:inline-block;width: 10px;height: 10px;border-radius: 50%;background: " + c[0] + "' ></div> " + `${tbefore.startTime || ""}： ${
              m0.value ? m0.value - 0 : 0
            }${unit}`;
            m1 &&
              (out += ` <br /><div style='display:inline-block;width: 10px;height: 10px;border-radius: 50%;background: ${c[1]}' ></div> ${tnow.startTime || ""}： ${
                m1.value ? m1.value - 0 : 0
              }${unit}`);
            return out;
          },
        },
        yAxis: {
          type: "value",
          scale: true,
          name: '单位：' + this.soft_list[this.soft_act].unit,
          axisLabel: {
            formatter: arr => {
              return this.formatNum(arr);
            },
          },
        },
        grid: [{ left: 150, top: "10%", buttom: 0, right: 100 }],
        series: chartData.value.map((v, i) => {
          return {
            showSymbol: false,
            name: chartData.lendata[i],
            data: v,
            type: "line",
            smooth: true,
          };
        }),
      };

      option && soft_chart.setOption(option);
    },
  },
  beforeUnmount: function() {
    hard_chart && hard_chart.dispose();
    soft_chart && soft_chart.dispose();
    hard_chart && (hard_chart = undefined);
    soft_chart && (soft_chart = undefined);
  },
  components: {},
};
</script>

<style>
.AdvertisingEye .title_card {
  font-weight: 600;
  background-color: #1989fa;
  height: 40px;
  line-height: 40px;
  color: #fff;
  font-size: 18px;
  padding-left: 12px;
}
</style>
