<template>
  <div>
    <back-box>
      <template slot="title">
        <span>使用分析</span>
      </template>
      <template slot="btns">
        <el-tooltip effect="dark" content="导出更多数据" placement="bottom">
          <el-button
            type="primary"
            icon="fa fa-cloud-download"
            size="mini"
            plain
            circle
            @click="downExc"
          ></el-button>
        </el-tooltip>
      </template>
    </back-box>
    <div class="page-content">
      <ul class="params-box">
        <li class="item item3">
          <span class="s-txt">时间段：</span>
          <div class="sel-box">
            <div class="d1">
              <el-date-picker
                v-model="query.startDay"
                type="date"
                @change="handleChangeTimeStart"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
                size="mini"
              >
              </el-date-picker>
              ~
              <el-date-picker
                v-model="query.endDay"
                type="date"
                placeholder="选择日期时间"
                @change="handleChangeTimeEnd"
                value-format="yyyy-MM-dd"
                size="mini"
              >
              </el-date-picker>
            </div>
            <p class="p1">
              <span
                @click="setDate(1)"
                :class="[date == 1 ? 'active' : '', 's1']"
                >今天</span
              >
              <span
                @click="setDate(2)"
                :class="[date == 2 ? 'active' : '', 's1']"
                >本周</span
              >
              <span
                @click="setDate(3)"
                :class="[date == 3 ? 'active' : '', 's1']"
                >本月</span
              >
              <span
                @click="setDate(4)"
                :class="[date == 4 ? 'active' : '', 's1']"
                >本季度</span
              >
            </p>
          </div>
          <el-button
            class="btn"
            v-if="role == 'ROLE_JITUAN'"
            type="primary"
            round
            size="small"
            @click="resetRank"
            >使用频率前十</el-button
          >
        </li>
        <li class="item item2" v-for="(item, index) in query.secGraClaSub">
          <span class="s-txt">对比项{{ setBigNum(index) }}：</span>
          <div class="sel-box">
            <el-cascader
              :ref="'cascader' + index"
              size="small"
              class="sel sel2"
              clearable
              placeholder="选择范围"
              @change="secGraClaSubChange($event, index)"
              v-model="query.secGraClaSub[index]"
              :options="gradeList"
              :props="props"
            ></el-cascader>
          </div>
          <i class="el-icon-delete" @click="removeQuery(index)"></i>
        </li>
        <li class="item">
          <span class="s-txt"></span>
          <div class="disflex-b">
            <el-button
              class="btn btn-none"
              :class="query.secGraClaSub.length < 10 ? '' : 'active'"
              icon="el-icon-plus"
              size="small"
              round
              @click="addQuery"
              >添加对比项</el-button
            >
            <el-button
              v-show="query.secGraClaSub.length"
              class="btn"
              type="primary"
              round
              size="small"
              @click="getData"
              >多项对比</el-button
            >
          </div>
        </li>
      </ul>
      <div class="chart-box">
        <barChart id="barChart" ref="barChart" />
      </div>
    </div>
  </div>
</template>

<script>
import barChart from "@/components/charts/barChart";
import { formatDate, downloadFile } from "@/utils";
export default {
  components: {
    barChart,
  },
  data() {
    return {
      role: "",
      loading: false,
      date: "", //今天-本周-本月-本季度
      type: 1, //集团管理员 表格切换
      query: {
        //搜索条件
        startDay: "",
        endDay: "",
        day: "",
        secGraClaSub: [],
        secGraClaSubName: [],
      },
      props: {
        multiple: false,
        checkStrictly: true,
      },
      params: [],
      gradeList: [],
      chartData: [
        {
          name: "课时数",
          value: [],
        },
        {
          name: "测练数",
          value: [],
        },
      ],
      xAxis: [],
    };
  },
  async created() {
    let that = this;
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    if (this.role == "ROLE_JITUAN") {
      (this.props.lazy = true),
        (this.props.lazyLoad = function (node, resolve) {
          const { level } = node;
          if (level == 3) {
            console.log(node);
            that.$request
              .tenantSubjectList({
                schoolId: node.path[0],
                grade: node.value,
              })
              .then((res) => {
                let children = res.data?.subjectNames.map((item) => {
                  return {
                    label: item,
                    value: item,
                    leaf: true,
                  };
                });
                const nodes = [...children];
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes);
              });
          } else {
            resolve(node);
          }
        });
      await this._QuerySchool();
    }
    await this._QueryGradeList();
    if (this.role == "ROLE_XUEXIAO") {
      await this._QueryClassList();
    }
    let startDay = this.query?.startDay;
    if (!startDay) {
      this.query.startDay = formatDate(new Date(), "yyyy-MM-dd");
      this.query.endDay = formatDate(new Date(), "yyyy-MM-dd");
    }
    this.setDate(3);
    this._QueryData();
  },
  methods: {
    async downExc() {
      if (this.exportLoading == true) return;
      let query = {
        //搜索条件
        startDay: this.query.startDay,
        endDay: this.query.endDay,
        day: this.query.day,
      };
      this.exportLoading = true;

      const exportUsageAnalysis =
        this.role != "ROLE_JITUAN"
          ? this.$request.exportUsageAnalysis
          : this.$request.exportSchoolContrast;
      const data = await exportUsageAnalysis({ ...query });
      this.exportLoading = false;
      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        downloadFile("使用分析.xlsx", blob);
      } else {
        this.$message.error("下载失败");
      }
    },
    addQuery() {
      this.query.secGraClaSub.push([]);
      this.query.secGraClaSubName.push("");
    },
    filterObj(arr, value) {
      return arr.filter((item) => {
        return value == item.value;
      })[0];
    },
    secGraClaSubChange(event, index) {
      console.log(event);
      let txt = "";
      let xx = this.filterObj(this.gradeList, event[0]);
      txt += xx.label;
      if (event.length > 1) {
        let grade = this.filterObj(xx.children, event[1]);
        txt += "/" + grade.label;
        if (event.length > 2) {
          let clazz = this.filterObj(grade.children, event[2]);
          txt += "/" + clazz.label;
          if (event.length > 3) {
            txt += "/" + event[3];
          }
        }
      }
      this.query.secGraClaSubName[index] = txt;
    },
    setBigNum(num) {
      let txt = "";
      let bigNum = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
      txt = bigNum[num];

      return txt;
    },
    setDate(index) {
      const that = this;
      this.date = index == this.date ? "" : index;
      let aYear = new Date().getFullYear();
      let aMonth = new Date().getMonth() + 1;
      that.query.day = "";
      that.query.startDay = "";
      that.query.endDay = "";
      switch (index) {
        case 1:
          that.query.day = formatDate(new Date(), "yyyy-MM-dd");
          that.query.startDay = that.query.day;
          that.query.endDay = that.query.day;
          break;
        case 2:
          let day = new Date().getDay();
          if (day == 0) {
            //中国式星期天是一周的最后一天
            day = 7;
          }
          day--;
          let aTime = new Date().getTime() - 24 * 60 * 60 * 1000 * day;
          that.query.startDay = formatDate(new Date(aTime), "yyyy-MM-dd");
          that.query.endDay = formatDate(new Date(), "yyyy-MM-dd");
          break;
        case 3:
          aMonth = aMonth < 10 ? "0" + aMonth : aMonth;
          that.query.startDay = `${aYear}-${aMonth}-01`;
          that.query.endDay = formatDate(new Date(), "yyyy-MM-dd");
          break;
        case 4:
          if (aMonth > 0 && aMonth < 4) {
            aMonth = "1";
          } else if (aMonth > 3 && aMonth < 7) {
            aMonth = "4";
          } else if (aMonth > 6 && aMonth < 10) {
            aMonth = "7";
          } else {
            aMonth = "10";
          }

          aMonth = aMonth < 10 ? "0" + aMonth : aMonth;
          that.query.startDay = `${aYear}-${aMonth}-01`;
          that.query.endDay = formatDate(new Date(), "yyyy-MM-dd");
          break;
      }
    },
    removeQuery(index) {
      let secGraClaSubLen = this.query.secGraClaSub.length;
      let xAxisLen = this.xAxis.length;
      this.query.secGraClaSub.splice(index, 1);
      this.query.secGraClaSubName.splice(index, 1);
      this.xAxis.splice(index, 1);
      if (
        secGraClaSubLen == xAxisLen ||
        (secGraClaSubLen > xAxisLen && index < xAxisLen)
      ) {
        this.chartData[0].value.splice(index, 1);
        this.chartData[1].value.splice(index, 1);
        this.$refs.barChart.initData(this.xAxis, this.chartData);
      }
    },
    handleChangeTimeStart(val) {
      this.query.day = "";
      this.date = "";
      if (this.query.endDay) {
        if (new Date(val).getTime() > new Date(this.query.endDay).getTime()) {
          this.$message.error("任务结束时间不能任务开始时间前面，请重新设置");
          this.query.startDay = "";
        }
      }
    },
    handleChangeTimeEnd(val) {
      this.query.day = "";
      this.date = "";
      if (this.query.startDay) {
        if (new Date(val).getTime() < new Date(this.query.startDay).getTime()) {
          this.$message.error("任务结束时间不能任务开始时间前面，请重新设置");
          this.query.endDay = "";
        }
      }
    },
    getData() {
      if (!this.query.secGraClaSub.length) {
        this.$message.warning("请添加对比项，并选择对比条件！");
        return;
      }
      let hasSpace = null;
      for (let i = 0; i < this.query.secGraClaSub.length; i++) {
        if (!this.query.secGraClaSub[i].length) {
          hasSpace = i;
          break;
        }
      }
      if (hasSpace !== null) {
        this.$message.warning(
          `对比项${this.setBigNum(hasSpace)}对比条件不能为空请检查！`
        );
        return;
      }
      this.xAxis = [...this.query.secGraClaSubName];
      this._QueryData();
    },
    setQuery() {
      let query = { ...this.query };
      delete query.secGraClaSub;
      if (this.role != "ROLE_JITUAN") {
        query.params = this.query.secGraClaSub.map((item) => {
          let jsons = {};
          jsons.section = item[0];
          item.length > 1 ? (jsons.grade = item[1]) : "";
          item.length > 2 ? (jsons.classId = item[2]) : "";
          item.length == 4 ? (jsons.subjectName = item[3]) : "";
          return jsons;
        });
      } else {
        query.params = this.query.secGraClaSub.map((item) => {
          let jsons = {};
          jsons.schoolId = item[0];
          item.length > 1 ? (jsons.section = item[1]) : "";
          item.length > 2 ? (jsons.grade = item[2]) : "";
          item.length == 4 ? (jsons.subjectName = item[3]) : "";
          return jsons;
        });
      }
      delete query.secGraClaSubName;
      return query;
    },
    async resetRank() {
      this.query.secGraClaSub = [];
      this.query.secGraClaSubName = [];
      this.chartData[0].value = [];
      this.chartData[1].value = [];
      this.xAxis = [];
      this.$refs.barChart.clearChart();
      await this._QuerySchool();
      await this._QueryGradeList();
      this._QueryData();
    },
    async _QueryData() {
      this.loading = true;
      let query = this.setQuery();
      const usageStatistics =
        this.role != "ROLE_JITUAN"
          ? this.$request.usageStatistics
          : this.$request.tenantUsageStatistics;
      const { data, status, info } = await usageStatistics({
        ...query,
      });
      this.loading = false;
      if (status === 0) {
        this.chartData[0].value = [];
        this.chartData[1].value = [];
        this.xAxis = this.query.secGraClaSubName.map((item) => {
          let arr = item.split("/");
          return arr[0] + "\n" + arr.slice(1, arr.length).join("/");
        });
        data?.list.map((item, index) => {
          this.chartData[0].value.push(item.periodCount);
          this.chartData[1].value.push(item.examCount);
        });
        this.$refs.barChart.initData(this.xAxis, this.chartData);
      } else {
        this.$message.error(info);
      }
    },
    // 查找nian级
    async _QueryGradeList() {
      this.loading = true;
      const gradeList =
        this.role != "ROLE_JITUAN"
          ? this.$request.sectionAndGradeList
          : this.$request.tenantSectionAndGradeList;
      const { data, status, info } = await gradeList();
      if (status === 0) {
        if (!!data.list) {
          this.query.secGraClaSub = [];
          this.query.secGraClaSubName = [];
          if (this.role != "ROLE_JITUAN") {
            this.gradeList =
              data.list?.map((item) => {
                let gradeIds = [];
                let children = item.gradeList.map((items) => {
                  gradeIds.push(items.grade);
                  return {
                    value: items.grade,
                    label: items.gradeName,
                  };
                });
                return {
                  value: item.section,
                  label: item.sectionName,
                  gradeIds: [...gradeIds],
                  children: [...children],
                };
              }) || [];
          } else {
            let children = data.list?.map((item) => {
              let children = item.gradeList.map((items) => {
                return {
                  value: items.grade,
                  label: items.gradeName,
                };
              });
              return {
                value: item.section,
                label: item.sectionName,
                children: [...children],
              };
            });
            this.gradeList = this.schoolList.map((item) => {
              if (this.query.secGraClaSub.length < 10) {
                this.query.secGraClaSub.push([item.id]);
                this.query.secGraClaSubName.push(item.schoolName);
              }
              return {
                value: item.id,
                label: item.schoolName,
                children: [...children],
              };
            });
          }
        }
      } else {
        this.$message.error(info);
      }
    },
    // 查找班级
    async _QueryClassList() {
      const { data, status, info } = await this.$request.gradeList();
      if (status === 0) {
        if (!!data.list) {
          if (this.role == "ROLE_XUEXIAO") {
            this.query.secGraClaSub = [];
            this.query.secGraClaSubName = [];
            data.list?.map((item) => {
              let subList = item.subjectNames?.map((items) => {
                return {
                  value: items,
                  label: items,
                };
              });
              let children = item.classList.map((clazz) => {
                return {
                  value: clazz.id,
                  label: clazz.className,
                  id: clazz.id,
                  children: [...subList],
                };
              });
              this.gradeList.map((sec) => {
                if (sec.gradeIds.includes(item.grade)) {
                  sec.children[sec.gradeIds.indexOf(item.grade)].children = [
                    ...children,
                  ];
                }
              });
            }) || [];
            this.gradeList.map((sec) => {
              sec.children.map((items) => {
                if (this.query.secGraClaSub.length < 10) {
                  this.query.secGraClaSub.push([sec.value, items.value]);
                  this.query.secGraClaSubName.push(
                    `${sec.label}/${items.label}`
                  );
                }
              });
            });
          }
        }
      } else {
        this.$message.error(info);
      }
    },
    async _QuerySchool() {
      this.loading = true;
      const { data, status, info } = await this.$request.schoolList({
        needSort: 1,
        day: this.query.day,
        startDay: this.query.startDay,
        endDay: this.query.endDay,
      });
      this.loading = false;
      if (status === 0) {
        this.schoolList = [...data.list] || [];
      } else {
        this.$message.error(info);
      }
    },
  },
};
</script>
<style>
div::-webkit-scrollbar {
  width: 3px;
  height: 10px;
}
div::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #ccc;
}
</style>
<style lang="scss" scoped>
.page-content {
  padding: 20px 40px;
}
.disflex-b {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .btn-none {
    border: none;
    background: none;
  }
  .active {
    transform: translateX(-999999px);
  }
}
.item3 {
  .sel-box {
    flex: 1;
  }
}
.sel-box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  .btn {
    margin-left: 100px;
  }
  .sel {
    width: 8%;
    min-width: 160px;
    margin-right: 20px;
  }
  :deep(.el-input__inner) {
    border: 1px solid #e2e2e2;
    border-radius: 20px;
    height: 32px;
    line-height: 30px;
  }

  .el-input__icon {
    line-height: 34px;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 160px;
  }

  .p1 {
    flex: 1;

    .s1 {
      margin-left: 36px;
      cursor: pointer;
      color: #7f7f7f;

      &:hover {
        color: #409eff;
      }

      &.active {
        color: #667ffd;
      }
    }
  }
  .sel2 {
    width: 240px;
  }
}
.params-box {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .s-txt {
      width: 120px;
    }
    .btn {
      font-size: 14px;
    }
    .disflex-b {
      flex: 1;
      padding-right: 100px;
    }
    &:hover {
      .el-icon-delete {
        display: block;
      }
    }
    .el-icon-delete {
      cursor: pointer;
      display: none;
      &:hover {
        color: #667ffd;
      }
    }
  }
  .item2 {
    width: 50%;
  }
  .item3 {
    padding-right: 100px;
  }
}
.chart-box {
  height: 400px;
}
</style>