<template>
  <div>
    <el-card>
      <headers
        title="活跃用户统计"
        @changeOrgan="changeOrgan"
        :special="true"
      />
      <div class="chioseBox">
        <el-radio-group v-model="timers" @change="changeQuick">
          <el-radio-button label="month">本月</el-radio-button>
          <el-radio-button label="year">本年度</el-radio-button>
          <el-radio-button label="lastYear">去年</el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-model="mdate"
          type="daterange"
          class="datePick"
          style="width: 300px; padding: 0 10px"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="changeValue"
          :picker-options="bigin()"
        >
        </el-date-picker>
        <p>单位:</p>

        <el-radio-group v-model="timer">
          <el-radio-button label="day">按天</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </div>
      <ve-line
        style="width: 100%"
        height="350px"
        :data="timer == 'day' ? chartData : chartDataForMoth"
        :data-empty="dataEmpty"
        :extend="chartExtend"
        :legend="legend"
      ></ve-line>
    </el-card>
  </div>
</template>
<script>
import "v-charts/lib/style.css";
import "echarts/lib/component/dataZoom";
import headers from "./modals/headers.vue";
import veLine from "v-charts/lib/line.common";
import { getNowDateAndSunday, getNowDateAndMonday } from "@/utils/date";
import { getIndex } from "../api";
import { getTimes } from "@/utils";
import { descs, chioseNum } from "../constant";
export default {
  components: {
    headers,
    veLine,
  },
  data() {
    return {
      timer: "day", // 按天 按月
      timers: "", // 本月 本年 去年
      mdate: [],
      data: [],
      organId: "",
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    legend() {
      return {
        left: "10px",
      };
    },
    items() {
      let obj = {};
      let arr = [
        "MEMBER_STUDENT_NUM",
        "CLOUD_STUDY_LIVELY_STUDENT_NUM",
        "CLOUD_STUDY_DAY_USE_STUDENT_NUM",
        "CLOUD_STUDY_NEW_STUDENT_NUM",
      ];
      arr.forEach((str) => {
        if (this.data[str]) {
          obj[str] = this.data[str];
        }
      });
      /**
       *  {
        HOMEWORK_CREATE_RATE:this.data["HOMEWORK_CREATE_RATE"] || {},
        HOMEWORK_SUBMIT_RATE: this.data["HOMEWORK_SUBMIT_RATE"] || {},
        HOMEWORK_COMMENT_RATE: this.data["HOMEWORK_COMMENT_RATE"] || {},
      };
       */
      return obj;
    },
    chartExtend() {
      return {
        series: {
          type: "line",
          smooth: false,
        },
        yAxis: {
          //纵轴标尺固定
          minInterval: 1,
          type: "value",
          scale: true,
          min: 0,
          max: 100,
          axisLabel: {
            formatter: "{value}%",
          },
        },
        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 [
        {
          grid: {
            left: "0%",
          },
          type: "slider",
          start: 40,
          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] &&
              item.dataType == "CLOUD_STUDY_NEW_STUDENT_NUM"
            ) {
              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: {
          type: "line",
          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) => {
            return [
              item[0].axisValueLabel,
              ...item.map(
                (d) => `<br/>${d.marker}${d.seriesName}: ${d.value[1]}人`
              ),
            ].join("");
          },
        },
      };
    },
  },
  methods: {
    init() {
      let nowTiem = this.$helpers.dayjs(new Date()).format("YYYY-MM-DD");

      let startTime = this.$helpers
        .dayjs(nowTiem)
        .subtract(8, "day")
        .format("YYYY-MM-DD");

      let endTime = this.$helpers
        .dayjs(nowTiem)
        .subtract(1, "day")
        .format("YYYY-MM-DD");
      this.mdate = [startTime, endTime];
      this.FetchDetail();
    },
    changeValue(date) {
      // 请求更改数据
      this.mdate = date;
      this.isDayOrMoth(date);
      console.log("调用", date);
      this.FetchDetail();
    },
    async FetchDetail() {
      this.loading = true;
      let data = [];
      try {
        // const { dates, ...rest } = this.search;
        //   ...rest,
        const res = await getIndex({
          ...getTimes(this.mdate, ["startDate", "endDate"]),
          organId: this.organId,
          dataTypes:
            "MEMBER_STUDENT_NUM,CLOUD_STUDY_LIVELY_STUDENT_NUM,CLOUD_STUDY_DAY_USE_STUDENT_NUM,CLOUD_STUDY_NEW_STUDENT_NUM",
        });
        for (const item of res.data) {
          data[item.dataType] = {
            ...item,
            desc: descs[item.dataType],
          };
        }
        this.data = data;
        // 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.data = data;
      // this.$emit("resetDate", data);
    },
    changeQuick(val) {
      let startDate;
      let endDate;
      if (val == "month") {
        // 获取本月的第一天 获取本月的今天
        let nowDate =  this.$helpers.dayjs(new Date()).get("date");

        if (nowDate == 1) {
          startDate =  this.$helpers.dayjs()
            .add(-1, "month")
            .startOf("month")
            .format("YYYY-MM-DD");
          endDate =  this.$helpers.dayjs(new Date()).subtract(1, "day").format("YYYY-MM-DD");
        } else {
          startDate =  this.$helpers.dayjs(new Date()).set("date", 1).format("YYYY-MM-DD");
          endDate =  this.$helpers.dayjs(new Date()).subtract(1, "day").format("YYYY-MM-DD");
        }
        this.mdate = [startDate, endDate];
        this.isDayOrMoth(this.mdate);
        this.FetchDetail();
        // this.submitDate(this.date);
      } else if (val == "year") {
        let nowDate = this.$helpers.dayjs(new Date()).get("date");
        let nowMonth = this.$helpers.dayjs(new Date()).get("month") + 1;
        if (nowDate == 1 && nowMonth == 1) {
          startDate = this.$helpers
            .dayjs(new Date())
            .add(-1, "year")
            .set("month", 0)
            .set("date", 1)
            .format("YYYY-MM-DD");
          endDate = this.$helpers
            .dayjs(new Date())
            .subtract(1, "day")
            .format("YYYY-MM-DD");
        } else {
          startDate = this.$helpers
            .dayjs(new Date())
            .set("month", 0)
            .set("date", 1)
            .format("YYYY-MM-DD");
          this.endDate
            ? (endDate = this.endDate)
            : (endDate = this.$helpers
                .dayjs(new Date())
                .subtract(1, "day")
                .format("YYYY-MM-DD"));
        }
        this.mdate = [startDate, endDate];
        this.isDayOrMoth(this.mdate);
        this.FetchDetail();
        // this.submitDate(this.date);
      } else if (val == "lastYear") {
        startDate = this.$helpers
          .dayjs(new Date())
          .subtract(1, "year")
          .set("month", 0)
          .set("date", 1)
          .format("YYYY-MM-DD");
        endDate = this.$helpers
          .dayjs()
          .subtract(1, "year")
          .endOf("year")
          .format("YYYY-MM-DD");
        this.mdate = [startDate, endDate];
        this.isDayOrMoth(this.mdate);
        this.FetchDetail();
        // this.submitDate(this.date);
      }
    },
    bigin() {
      let self = this;
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          if (self.endDate) {
            let endTime = self.$helpers.dayjs(self.endDate).valueOf();
            return time.getTime() > endTime;
          } else {
            return time.getTime() >= Date.now() - 24 * 60 * 60 * 1000;
          }
        },
      };
    },
    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");
      }
    },
    changeOrgan(val) {
      this.organId = val;
      this.FetchDetail();
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-card__body {
  padding-top: 0 !important;
}

.chioseBox {
  position: absolute;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: row;
  align-items: center;
  p {
    font-size: 14px;
    margin: 0 5px 0 10px;
  }
  .datePick {
    margin-left: 10px;
  }
}
.wrap {
  position: relative;
}
</style>
