<template>
  <div class="trainModel">
    <div class="visit-tips" v-show="activeType == 'visited'">
      <span
        >上周练习时长不足{{ playTime }}分钟或练习次数小于{{ trainNum }}次的学员<br />
        需在每周三24:00前完成回访</span
      >
    </div>
    <search @onSearch="onSearch" placeholder="学生姓名或手机号">
      <template #left>
        <van-dropdown-menu style="padding-right: 0.1rem" :close-on-click-outside="false" active-color="#01C1B5">
          <van-dropdown-item title="筛选" ref="item" class="visitTime">
            <div class="search-group">
              <van-cell title="日期" is-link @click="showCalendar = true" title-style="font-size: .15rem;font-weight: 600" :value="calendarValue" value-class="calendarColor" class="studentCell"></van-cell>
              <van-cell title="是否会员" title-style="font-size: .15rem;font-weight: 600" class="studentCell">
                <!-- <van-radio-group v-model="memberFlag" direction="horizontal">
                <van-radio name="">全部学员</van-radio>
                <van-radio name="1">会员学员</van-radio>
                <van-radio name="0">普通学员</van-radio>
              </van-radio-group> -->
                <template slot="label"
                  ><div class="btn-group">
                    <van-button :plain="memberFlag === ''" round :type="memberFlag === '' ? 'info' : 'default'" @click="onCheckType('member', '')">全部学员</van-button>
                    <van-button :plain="memberFlag === '1'" :type="memberFlag === '1' ? 'info' : 'default'" round @click="onCheckType('member', '1')">会员学员</van-button>
                    <van-button :plain="memberFlag === '0'" :type="memberFlag === '0' ? 'info' : 'default'" round @click="onCheckType('member', '0')">普通学员</van-button>
                  </div>
                </template>
              </van-cell>
              <van-cell title="学员类型" title-style="font-size: .15rem;font-weight: 600" class="studentCell">
                <template slot="label">
                  <div class="btn-group">
                    <van-button round :plain="studentType === ''" :type="studentType === '' ? 'info' : 'default'" @click="onCheckType('type', '')">全部学员</van-button>
                    <van-button :plain="studentType === '1'" :type="studentType === '1' ? 'info' : 'default'" round @click="onCheckType('type', '1')">乐团学员</van-button>
                    <van-button :plain="studentType === '2'" :type="studentType === '2' ? 'info' : 'default'" round @click="onCheckType('type', '2')">已结束小课学员</van-button>
                    <van-button :plain="studentType === '3'" :type="studentType === '3' ? 'info' : 'default'" round @click="onCheckType('type', '3')">进行中小课学员</van-button>
                  </div>
                </template>
              </van-cell>
              <van-cell title="乐团" is-link @click="showMusicGroup = true" title-style="font-size: .15rem;font-weight: 600" :value="musicGroupName" value-class="calendarColor" class="studentCell"></van-cell>
              <van-cell
                title="班级"
                is-link
                @click="
                  () => {
                    if (!musicGroupId) {
                      $toast('请选择乐团');
                      return;
                    }
                    showClass = true;
                  }
                "
                title-style="font-size: .15rem;font-weight: 600"
                :value="className"
                value-class="calendarColor"
                class="studentCell"
              ></van-cell>
            </div>
            <div class="submit-group van-hairline--top">
              <van-button block round @click="onReset" style="margin-right: 12px"> 重置 </van-button>
              <van-button type="primary" block round @click="onSubmit"> 确认 </van-button>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
      </template>
    </search>
    <van-row class="searchArray">
      <van-col span="6" class="title-style" @click="onSort(0)">
        练习时长
        <div>
          <i class="box box-up" :class="{ active: searchArray[0] == 'ASC' }" style="margin-bottom: 0.03rem"></i>
          <i class="box box-down" :class="{ active: searchArray[0] == 'DESC' }"></i>
        </div>
      </van-col>
      <van-col span="6" class="title-style" @click="onSort(1)">
        练习次数
        <div>
          <i class="box box-up" :class="{ active: searchArray[1] == 'ASC' }" style="margin-bottom: 0.03rem"></i>
          <i class="box box-down" :class="{ active: searchArray[1] == 'DESC' }"></i>
        </div>
      </van-col>
      <van-col span="6" class="title-style" @click="onSort(2)">
        练习天数
        <div>
          <i class="box box-up" :class="{ active: searchArray[2] == 'ASC' }" style="margin-bottom: 0.03rem"></i>
          <i class="box box-down" :class="{ active: searchArray[2] == 'DESC' }"></i>
        </div>
      </van-col>
      <van-col span="6" class="title-style" @click="onSort(3)">
        评测次数
        <div>
          <i class="box box-up" :class="{ active: searchArray[3] == 'ASC' }" style="margin-bottom: 0.03rem"></i>
          <i class="box box-down" :class="{ active: searchArray[3] == 'DESC' }"></i>
        </div>
      </van-col>
    </van-row>
    <van-calendar v-model="showCalendar" :minDate="minDate" :default-date="defaultDate" :first-day-of-week="1" :formatter="formatterDay" color="#01C1B5" type="range" get-container="body" @select="selectDate" @confirm="onConfirm" @close="onClose" />

    <van-popup v-model="showMusicGroup" position="bottom" round>
      <van-picker :columns="musicGroupList" :default-index="musicGroupIndex" show-toolbar @cancel="showMusicGroup = false" @confirm="onSetMusicGroup" />
    </van-popup>
    <van-popup v-model="showClass" position="bottom" round>
      <van-picker :columns="classList" :default-index="classIndex" show-toolbar @cancel="showClass = false" @confirm="onSetClass" />
    </van-popup>
  </div>
</template>

<script>
import Search from "@/components/Search";
import dayjs from "dayjs";
import { getNowDateAndMonday, getNowDateAndSunday } from "@/common/common";
import { queryTeacherMusicGroup, queryTeacherMusicClass } from "./api";
export default {
  props: {
    active: {
      type: String,
      default: "all",
    },
    selectValues: {
      type: Object,
      default: () => {},
    },
    defaultTime: {
      type: Number,
      default: 0,
    },
    trainNum: {
      type: [Number, String],
      default: 0,
    },
    playTime: {
      type: [Number, String],
      default: 0,
    },
  },
  components: { Search },
  data() {
    return {
      musicGroupIndex: 0,
      classIndex: 0,
      showCalendar: false,
      showMusicGroup: false,
      musicGroupList: [],
      showClass: false,
      classList: [],
      minDate: new Date(2000, 0, 1),
      defaultDate: [],
      memberFlag: "",
      studentType: "", // 1 -> musicFlag，2 -> hasEndVipFlag，3 -> hasNotStartVipFlag
      // 类型为全部时
      startDay: null,
      endDay: null,
      search: null,
      searchArray: [null, null, null, null],
      searchType: {
        // ASC DESC
        totalPlayTime: null,
        trainNum: null,
        trainDay: null,
        recordNum: null,
      },
      musicGroupId: "",
      musicGroupName: "全部乐团",
      classId: "",
      className: "全部班级",
    };
  },
  async mounted() {
    let defaultTime = this.defaultTime;
    let day = defaultTime * 7;
    let startTime = new Date(),
      endTime = new Date();
    const selectValues = this.selectValues;
    const searchType = ["totalPlayTime", "trainNum", "trainDay", "recordNum"];
    if (selectValues.sort) {
      const index = searchType.findIndex((item) => item === selectValues.sort);
      this.searchArray[index] = selectValues.order;
    }
    if (selectValues.musicFlag) {
      this.studentType = "1";
    } else if (selectValues.hasEndVipFlag) {
      this.studentType = "2";
    } else if (selectValues.hasNotStartVipFlag) {
      this.studentType = "3";
    }

    if (selectValues.startTime && selectValues.endTime) {
      startTime = selectValues.startTime;
      endTime = selectValues.endTime;
    } else {
      if (day > 0) {
        startTime = getNowDateAndMonday(dayjs().add(day, "day").format("YYYY-MM-DD"));
        endTime = getNowDateAndSunday(dayjs().add(day, "day").format("YYYY-MM-DD"));
      } else {
        startTime = getNowDateAndMonday(dayjs().subtract(Math.abs(day), "day").format("YYYY-MM-DD"));
        endTime = getNowDateAndSunday(dayjs().subtract(Math.abs(day), "day").format("YYYY-MM-DD"));
      }
    }

    this.defaultDate = [new Date(startTime), new Date(endTime)];
    this.startDay = startTime;
    this.endDay = endTime;

    this.memberFlag = selectValues.memberFlag || "";
    this.musicGroupId = selectValues.musicGroupId;
    await this.getOrchestraList();

    if (selectValues.musicGroupId) {
      await this.getClassList();
      this.musicGroupList.forEach((item, index) => {
        if (item.value === this.musicGroupId) {
          this.musicGroupName = item.text;
          this.musicGroupIndex = index;
        }
      });
    }

    if (selectValues.classGroupId) {
      this.classId = selectValues.classGroupId;
      this.classList.forEach((item, index) => {
        if (item.value === this.classId) {
          this.className = item.text;
          this.classIndex = index;
        }
      });
    }

    this.onSort();
  },
  computed: {
    calendarValue() {
      return `${dayjs(this.startDay).format("YYYY/MM/DD")} - ${dayjs(this.endDay).format("YYYY/MM/DD")}`;
    },
    activeType() {
      return this.active;
    },
  },
  methods: {
    async getOrchestraList() {
      // this.orchestraLoading = true;
      try {
        const { data } = await queryTeacherMusicGroup({});
        const result = data || [];
        const tempList = [
          {
            text: "全部乐团",
            value: "",
          },
        ];
        result.forEach((item) => {
          tempList.push({
            text: item.name,
            value: item.id,
          });
        });
        this.musicGroupList = tempList;
      } catch {
        //
      }
      // this.orchestraLoading = false;
    },
    async getClassList() {
      try {
        const { data } = await queryTeacherMusicClass({
          musicGroupId: this.musicGroupId,
        });
        const result = data || [];
        const tempList = [
          {
            text: "全部班级",
            value: "",
          },
        ];
        result.forEach((item) => {
          tempList.push({
            text: item.name,
            value: item.id,
          });
        });
        this.classList = tempList;
      } catch {
        //
      }
    },
    onSetMusicGroup(val) {
      this.musicGroupId = val.value;
      this.musicGroupName = val.text;

      this.classId = "";
      this.className = "全部班级";
      this.showMusicGroup = false;
      this.getClassList();
    },
    onSetClass(val) {
      this.classId = val.value;
      this.className = val.text;
      this.showClass = false;
    },
    onCheckType(type, value) {
      if (type === "member") {
        this.memberFlag = value;
      } else if (type === "type") {
        this.studentType = value;
      }
    },
    onSort(type) {
      if (type !== undefined && type !== null) {
        let searchArray = this.searchArray;
        searchArray.forEach((item, index) => {
          if (index != type) {
            searchArray[index] = null;
          }
        });
        if (searchArray[type] == "ASC") {
          searchArray[type] = "DESC";
        } else if (searchArray[type] == "DESC") {
          searchArray[type] = null;
        } else {
          searchArray[type] = "ASC";
        }
        this.$forceUpdate();
      }
      this.onAllFilter();
    },
    onSearch(val) {
      this.search = val;
      this.onAllFilter();
    },
    onAllFilter() {
      const searchArray = this.searchArray;
      let currentIndex = null;
      let currentType = null;
      searchArray.forEach((item, index) => {
        if (item) {
          currentIndex = index;
          currentType = item;
        }
      });
      const searchType = ["totalPlayTime", "trainNum", "trainDay", "recordNum"];
      // 1 -> musicFlag,2 -> hasEndVipFlag,3 -> hasNotStartVipFlag
      let params = {
        search: this.search,
        memberFlag: this.memberFlag,
        musicFlag: this.studentType === "1" ? true : false,
        hasEndVipFlag: this.studentType === "2" ? true : false,
        hasNotStartVipFlag: this.studentType === "3" ? true : false,
        startTime: this.startDay,
        endTime: this.endDay,
        classGroupId: this.classId,
        musicGroupId: this.musicGroupId,
        page: 1,
        sort: searchType[currentIndex],
        order: currentType,
      };
      this.$listeners.onLoad(params);
    },
    changeDropDownItemStatus() {
      this.$refs.item.toggle(false);
    },
    selectDate(date) {
      let [start, end] = date;
      if (start) {
        const num = dayjs(start).get("day");
        if (num === 0) {
          start = dayjs(start).subtract(6, "day");
        } else {
          start = dayjs(start).subtract(num - 1, "day");
        }
      }
      if (start) {
        const num = 7 - dayjs(start).get("day");
        if (num < 7) {
          end = dayjs(start).add(num, "day");
        }
      }
      this.defaultDate = [new Date(start.valueOf()), new Date(end.valueOf())];
    },
    onConfirm(date) {
      let [start, end] = date;
      this.showCalendar = false;
      if (start) {
        const num = dayjs(start).get("day");
        if (num === 0) {
          start = dayjs(start).subtract(6, "day");
        } else {
          start = dayjs(start).subtract(num - 1, "day");
        }
      }
      if (end) {
        const num = 7 - dayjs(end).get("day");
        if (num < 7) {
          end = dayjs(end).add(num, "day");
        }
      }
      this.startDay = dayjs(start).format("YYYY-MM-DD");
      this.endDay = dayjs(end).format("YYYY-MM-DD");
      //
      //   this.changeDropDownItemStatus();
      //   this.onAllFilter();
    },
    onSubmit() {
      this.changeDropDownItemStatus();
      this.onAllFilter();
    },
    onReset() {
      let defaultTime = this.defaultTime;
      let day = defaultTime * 7;
      let startTime = new Date(),
        endTime = new Date();
      if (day > 0) {
        startTime = getNowDateAndMonday(dayjs().add(day, "day").format("YYYY-MM-DD"));
        endTime = getNowDateAndSunday(dayjs().add(day, "day").format("YYYY-MM-DD"));
      } else {
        startTime = getNowDateAndMonday(dayjs().subtract(Math.abs(day), "day").format("YYYY-MM-DD"));
        endTime = getNowDateAndSunday(dayjs().subtract(Math.abs(day), "day").format("YYYY-MM-DD"));
      }
      this.defaultDate = [new Date(startTime), new Date(endTime)];
      this.startDay = startTime;
      this.endDay = endTime;
      this.memberFlag = "";
      this.studentType = "";
      this.musicGroupId = "";
      this.musicGroupName = "全部乐团";
      this.classId = "";
      this.className = "全部班级";
      this.onSubmit();
    },
    onClose() {
      // 关闭弹窗时初始化默认日期
      this.defaultDate = [new Date(this.startDay), new Date(this.endDay)];
    },
    formatterDay(day) {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();
      let nowDate = new Date();
      if (month == nowDate.getMonth() + 1 && date == nowDate.getDate()) {
        day.text = "今天";
      }
      return day;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.van-dropdown-menu__title::after {
  border-color: transparent transparent #aaaaaa #aaaaaa;
}
/deep/.van-dropdown-menu__title--active::after {
  border-color: transparent transparent #01c1b5 #01c1b5;
}
/deep/.van-dropdown-item__content {
  border-radius: 0px 0px 12px 12px;
  max-height: 100%;
}
.search-group {
  max-height: 4rem;
  overflow-x: hidden;
  overflow-y: auto;
}
.calendarColor {
  font-size: 15px;
  color: #333333;
}
.studentCell {
  padding: 0.18rem 0.13rem;
}
.visit-tips {
  background-color: #fff;
  // padding: 10px 10px 0;
  padding: 10px 12px 0;
  text-align: center;
  span {
    display: block;
    padding: 6px 12px;
    background-color: #fff6de;
    font-size: 12px;
    color: #ff802c;
    text-align: left;
  }
}
.searchArray {
  font-size: 0.14rem;
  padding-top: 0.15rem;
  padding-bottom: 0.12rem;
  color: #1a1a1a;
  background-color: #f5f5f5;
}
.title-style {
  display: flex;
  align-items: center;
  justify-content: center;
}
.box {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 0.02rem;
}
.box-up {
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-bottom: 5px solid #ccc;
  &.active {
    border-bottom-color: #01c1b5;
  }
}
.box-down {
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 5px solid #ccc;
  &.active {
    border-top-color: #01c1b5;
  }
}

.studentCell {
  /deep/.van-cell__title {
    flex-shrink: 0;
    flex: auto;
  }
  /deep/.van-cell__value {
    flex: 1 auto;
  }
}

.btn-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  // gap: 0 10px;
  margin: 0 -0.05rem;

  /deep/.van-button {
    margin: 0.1rem 0.05rem 0;
    padding: 0;
    font-weight: 400;
    font-size: 0.13rem;
    width: calc(33.3% - 0.1rem);
    height: 0.34rem;
  }

  /deep/.van-button--default {
    background: #f6f6f6;
    border-color: #f6f6f6;
  }
}
.submit-group {
  padding: 0.14rem 0.16rem;
  display: flex;
  /deep/.van-button {
    font-size: 0.16rem;
    height: 0.44rem;
  }
}
</style>
