<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 :col="6" class="statistic" :cols="0">
      <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
        style="width: 100%"
        height="350px"
        :data="timer == 'day' ? chartData : chartDataForMoth"
        :data-empty="dataEmpty"
        :extend="chartExtend"
        :legend="legend"
      ></ve-line>
    </div>
    <!-- <ve-funnel v-else style="width: 100%;" height="350px" :data="funnelData" :data-empty="dataEmpty"></ve-funnel> -->
  </el-card>
</template>
<script>
import countTo from "vue-count-to";
import veLine from "v-charts/lib/line.common";
import veFunnel from "v-charts/lib/funnel.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-funnel": veFunnel,
    "ve-line": veLine,
    "count-to": countTo,
    searchHeader,
  },
  computed: {
    legend() {
      return {
        left: "10px",
      };
    },
    items() {
      return {
        ADD_STUDENT_REGISTRATION_NUM:
          this.data["ADD_STUDENT_REGISTRATION_NUM"] || {},
        MUSIC_GROUP_STUDENT: this.data["MUSIC_GROUP_STUDENT"] || {},
        NEWLY_STUDENT_NUM: this.data["NEWLY_STUDENT_NUM"] || {},
        QUIT_MUSIC_GROUP_STUDENT_NUM:
          this.data["QUIT_MUSIC_GROUP_STUDENT_NUM"] || {},
        VIP_PRACTICE_STUDENT_NUM: this.data["VIP_PRACTICE_STUDENT_NUM"] || {},
        VIP_PRACTICE_ADD_STUDENT_NUM:
          this.data["VIP_PRACTICE_ADD_STUDENT_NUM"] || {},
      };
    },
    chartExtend() {
      return {
        yAxis: {
          //纵轴标尺固定
          minInterval: 1,
          type: "value",
          scale: true,
          min: 0,
          axisLabel: {
            formatter: "{value}人",
          },
        },
        series: {
          smooth: false,
        },
        tooltip: {
          axisPointer: {
            type: "shadow",
            shadowStyle: {
              color: "rgba(150,150,150,0.2)",
            },
          },
          formatter: (item) => {
            return [
              item[0].axisValueLabel,
              ...item.map(
                (d) => `<br/>${d.marker}${d.seriesName}: ${d.value[1]}人`
              ),
            ].join("");
          },
        },
      };
    },
    dataZoom() {
      return [
        {
          type: "slider",
          start: 60,
          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);
      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;
            }
          }
        }
      }

      return {
        columns: ["月份", ...values.map((item) => item.title)],
        rows: Object.values(months),
      };
    },
    funnelData() {
      const { indexMonthData = [] } = this.data["STUDENT_CONVERSION"] || {};
      return {
        columns: ["类型", "数值"],
        rows: indexMonthData.map((item) => ({
          类型: item.title,
          数值: item.percent,
        })),
      };
    },
    dataEmpty() {
      return !this.chartData.rows.length;
    },
  },
  data() {
    return {
      active: "NEWLY_STUDENT_NUM",
      isHistogram: true,
      timer: "day",
      mdate: this.search?.dates,
      loading: false,
    };
  },
  methods: {
    changeValue(date) {
      // 请求更改数据
      this.mdate = date;
      this.isDayOrMoth(date);
      this.FetchDetail();
    },
    async FetchDetail() {
      this.loading = true;
      const data = this.data;
      try {
        const { dates, ...rest } = this.search;
        const res = await getIndex({
          ...rest,
          ...getTimes(this.mdate, ["startDate", "endDate"]),
          dataTypes:
            "ADD_STUDENT_REGISTRATION_NUM,MUSIC_GROUP_STUDENT,NEWLY_STUDENT_NUM,QUIT_MUSIC_GROUP_STUDENT_NUM,VIP_PRACTICE_STUDENT_NUM,VIP_PRACTICE_ADD_STUDENT_NUM",
        });
        for (const item of res.data) {
          // 再循环一遍
          for (const key in this.items) {
            // console.log(key);
            if (item.dataType == key) {
              data[item.dataType] = {
                ...item,
                desc: descs[item.dataType],
              };
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
      console.log(data);
      this.loading = false;
      this.dataInfo = data;
      this.$emit("resetDate", data);
    },

    isDayOrMoth(arr) {
      console.log(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");
      }
    },
  },
};
</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>
