<template v-loading="loading"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
  <el-card>
    <div slot="header" class="clearfix">
      <searchHeader
        :dates="mdate"
        :title="'课程数据'"
        @changeValue="changeValue"
        :isShowQuert="true"
      />
    </div>
    <statistic class="statistic" :cols="0" :col="5">
      <statistic-item
        v-for="(item, key) in items"
        :key="key"
        :class="{ active: active === key }"
        @click="active = key"
      >
        <span>
          {{ item.title }}
          <el-tooltip
            v-if="item.desc"
            :content="item.desc"
            :open-delay="0.3"
            placement="top"
          >
            <i
              style="margin-left: 5px; cursor: pointer"
              class="el-icon-warning-outline"
            />
          </el-tooltip>
        </span>
        <span> <count-to :endVal="item.percent" />节 </span>
      </statistic-item>
    </statistic>
    <div class="wrap">
      <div class="chioseBox">
        <el-radio-group v-model="timer" size="mini">
          <el-radio-button label="day">按天</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </div>
      <!-- :data-zoom="dataZoom" -->
      <ve-line
        :data="timer == 'day' ? chartData : chartDataForMoth"
        height="350px"
        :data-empty="dataEmpty"
        :extend="chartExtend"
        :legend="legend"
      />
    </div>
  </el-card>
</template>
<script>
import "echarts/lib/component/dataZoom";
import countTo from "vue-count-to";
import veLine from "v-charts/lib/line.common";
import searchHeader from "./modals/searchHeader";
import { getIndex } from "../api";
import { getTimes } from "@/utils";
import { descs, chioseNum } from "../constant";
export default {
  props: ["data", "search"],
  components: {
    "ve-line": veLine,
    "count-to": countTo,
    searchHeader,
  },
  computed: {
    legend() {
      return {
        left: "10px",
      };
    },
    items() {
      return {
        MUSIC_GROUP_COURSE: this.data["MUSIC_GROUP_COURSE"] || {},
        VIP_GROUP_COURSE: this.data["VIP_GROUP_COURSE"] || {},
        VIP_GROUP_ONLINE_COURSE: this.data["VIP_GROUP_ONLINE_COURSE"] || {},
        VIP_GROUP_OFFLINE_COURSE: this.data["VIP_GROUP_OFFLINE_COURSE"] || {},
        PRACTICE_GROUP_COURSE: this.data["PRACTICE_GROUP_COURSE"] || {},
      };
    },
    dataZoom() {
      return [
        {
          type: "slider",
          start: 50,
          end: 100,
        },
      ];
    },
    chartData() {
      const values = Object.values(this.items);
      const months = {};
      for (const item of values) {
        for (const row of item.indexMonthData || []) {
          const key = this.$helpers.dayjs(row.month).format("YYYY-MM-DD");
          if (!months[key]) {
            months[key] = {
              日期: key,
            };
          }
          months[key][item.title] = row.percent;
        }
      }
      return {
        columns: ["日期", ...values.map((item) => item.title)],
        rows: Object.values(months),
      };
    },
    chartDataForMoth() {
      const values = Object.values(this.items);
      //   console.log(values)
      // values['VIP_GROUP_COURSE'].forEach(item=>{
      //     console.log(item.month)
      //   })
      const months = {};

      for (const item of values) {
        for (const row of item.indexMonthData || []) {
          const key = this.$helpers.dayjs(row.month).format("YYYY-MM");
          if (!months[key]) {
            months[key] = {
              月份: key,
            };
            months[key][item.title] = row.percent;
          } else {
            if (months[key][item.title]) {
              months[key][item.title] += parseFloat(row.percent);
            } else {
              months[key][item.title] = row.percent;
            }
          }
        }
      }
      console.log(Object.values(months));
      return {
        columns: ["月份", ...values.map((item) => item.title)],
        rows: Object.values(months),
      };
    },
    dataEmpty() {
      return !this.chartData.rows.length;
    },
    chartExtend() {
      return {
        series: {
          smooth: false,
        },
        yAxis: {
          //纵轴标尺固定
          minInterval: 1,
          type: "value",
          scale: true,
          min: 0,
          axisLabel: {
            formatter: "{value}节",
          },
        },
        tooltip: {
          axisPointer: {
            type: "shadow",
            shadowStyle: {
              color: "rgba(150,150,150,0.2)",
            },
          },
          formatter: (item) => {
            let strArr = [];
            let dotStr =
              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;opacity:0;"></span>';
            let array = [
              ...item.map(
                (d) => `<br/>${d.marker}${d.seriesName}: ${d.value[1]}节`
              ),
            ];
            if (this.timer == "day") {
              strArr = this.setVipDayDetail(item);
            } else {
              let vipDEtail = this.setVipMonthDetail();
              item.forEach((i) => {
                if (i.seriesName == "VIP课") {
                  for (let items in vipDEtail[i.name]) {
                    strArr.push({ name: items, num: vipDEtail[i.name][items] });
                  }
                }
              });
              strArr.sort(function (item1, item2) {
                return item1.name.localeCompare(item2.name, "zh-CN");
              });
            }
            let vipIndex = 0;
            item.forEach((i, indx) => {
              if (i.seriesName == "VIP课") {
                vipIndex = indx;
              }
            });
            array.splice(
              vipIndex + 1,
              0,
              ...strArr.map((d) => `<br/>${dotStr}${d.name}: ${d.num}节`)
            );
            return [item[0].axisValueLabel, ...array].join("");
          },
        },
      };
    },
  },
  data() {
    return {
      active: "MUSIC_GROUP_COURSE",
      timer: "day",
      mdate: this.search?.dates,
      loading: false,
    };
  },
  watch: {},
  methods: {
    changeValue(date) {
      // 请求更改数据
      this.mdate = date;
      this.isDayOrMoth(date);

      this.FetchDetail();
    },
    async FetchDetail() {
      this.loading = true;
      let data = [];
      try {
        const { dates, ...rest } = this.search;
        const res = await getIndex({
          ...rest,
          ...getTimes(this.mdate, ["startDate", "endDate"]),
          dataTypes:
            "MUSIC_GROUP_COURSE,VIP_GROUP_COURSE,PRACTICE_GROUP_COURSE,VIP_GROUP_OFFLINE_COURSE,VIP_GROUP_ONLINE_COURSE",
        });
        for (const item of res.data) {
          // 再循环一遍
          for (const key in this.items) {
            if (item.dataType == key) {
              data[item.dataType] = {
                ...item,
                desc: descs[item.dataType],
              };
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
      this.loading = false;
      this.$emit("resetDate", data);
    },
    isDayOrMoth(arr) {
      if (!arr || arr.length < 1) {
        this.timer = "day";
      } else {
        const count = this.$helpers
          .dayjs(arr[0])
          .diff(this.$helpers.dayjs(arr[1]), "day");
        Math.abs(count) > chioseNum
          ? (this.timer = "month")
          : (this.timer = "day");
      }
    },
    setVipMonthDetail() {
      console.log("调用");
      const vipdetail = {};
      let datas = this.items["VIP_GROUP_COURSE"]["indexMonthData"];
      datas.forEach((item) => {
        let str = item.extendInfo;
        let strArr = [];
        let strObj = {};
        str.replace("/", "");
        if (str) {
          try {
            strObj = JSON.parse(str);
            // for (let item in strObj) {
            //   strArr.push({ name: item, num: parseFloat(strObj[item]) });
            // }
          } catch (e) {
            console.log(e);
            str = "";
          }
        }
        const key = this.$helpers.dayjs(item.month).format("YYYY-MM");
        if (!vipdetail[key]) {
          vipdetail[key] = strObj;
        } else {
          for (let element in strObj) {
            if (vipdetail[key].hasOwnProperty(element)) {
              vipdetail[key][element] += strObj[element];
            } else {
              vipdetail[key][element] = strObj[element];
            }
          }
        }
      });
      return vipdetail;
    },
    setVipDayDetail(item) {
      let strArr = [];
      let str = "";
      if (
        this.items["VIP_GROUP_COURSE"]["indexMonthData"][item[0].dataIndex]
          ?.extendInfo
      ) {
        str = this.items["VIP_GROUP_COURSE"]["indexMonthData"][
          item[0].dataIndex
        ]?.extendInfo;
        str.replace("/", "");
        try {
          let strObj = JSON.parse(str);
          for (let item in strObj) {
            strArr.push({ name: item, num: strObj[item] });
          }
          // console.log(strArr)
        } catch (e) {
          console.log(e);
          str = "";
        }
        // console.log(lodash.valuesIn(str))
      }
      return strArr;
    },
  },
};
</script>
<style lang="less" scoped>
// .statistic{
//   /deep/ .statistic-content{
//     cursor: pointer;
//     &.active > span{
//       color: #14928a !important;
//     }
//   }
// }
.chioseBox {
  position: absolute;
  right: 20px;
  z-index: 1000;
}
.wrap {
  position: relative;
}
</style>
