<template>
  <div class="selectStudent">
    <div class="selectStudentWrap">
      <van-search class="searchWrap" shape="round" show-action placeholder="学员姓名/编号/手机号" v-model="search" @search="onSearch()">
        <template #action>
          <div @click="onSearch()">搜索</div>
        </template>
      </van-search>
      <van-dropdown-menu class="selectStudent-dropdown" active-color="#01C1B5">
        <!-- <van-dropdown-item
          title="分部"
          ref="fenbu"
          @open="onOpenDropdown('fenbuDrop')"
        >
          <template slot="default">
            <DropSelect
              :options="option1"
              @onFilter="onFilter1"
              ref="fenbuDrop"
            />
          </template>
        </van-dropdown-item> -->
        <van-dropdown-item title="声部" ref="dropdown" @close="onOpenDropdown('dropdownDrop')">
          <template slot="default">
            <DropSelect :options="option2" @onFilter="onFilter2" ref="dropdownDrop" />
          </template>
        </van-dropdown-item>
        <van-dropdown-item v-if="options3.length" v-model="value3" :options="options3" @change="getStudents"></van-dropdown-item>
      </van-dropdown-menu>
    </div>

    <div class="students">
      <van-cell v-for="(stu, index) in studentsData" :key="stu.value" :title="stu.text" :label="stu.subjectName" center clickable @click="onSelectStudent(index)">
        <div slot="label">
          <span>{{ stu.subjectName }}</span>
          <span style="margin-left: 10px"> {{ stu.phone }}</span>
        </div>
        <img v-if="stu.avatar" slot="icon" class="stuAvatar" :src="stu.avatar" />
        <img v-else slot="icon" class="stuAvatar" src="@/assets/images/common/default_head_img.png" />
        <div class="students-right">
          <span style="margin-left: auto; margin-right: 20px">{{ stu.subCourseNum }}课时</span>
          <van-checkbox :value="stu.checked"></van-checkbox>
        </div>
      </van-cell>
      <MEmpty v-if="!loading && !studentsData.length" :msg="'暂无学员'" />
    </div>

    <div style="height: 50px"></div>

    <van-submit-bar button-text="下一步" button-type="info" class="selectStudent-submit-bar" @submit="onSubmit" :disabled="!selectStudents.length">
      <van-dropdown-menu active-color="#01C1B5" direction="up">
        <van-dropdown-item>
          <template #title>
            已选学生
            <span style="color: red">{{ selectStudents.length }}</span> 名
          </template>
          <template slot="default">
            <div class="submit-bar-popup-title">已选学生</div>
            <div class="students" style="padding: 0">
              <van-cell v-for="student in selectStudents" :key="student.value" :title="student.text" :label="student.subjectName" center>
                <div slot="label">
                  <span>{{ student.subjectName }}</span>
                  <span style="margin-left: 10px"> {{ student.phone }}</span>
                </div>
                <img v-if="student.avatar" slot="icon" class="stuAvatar" :src="student.avatar" />
                <img v-else slot="icon" class="stuAvatar" src="@/assets/images/common/default_head_img.png" />
                <van-icon name="clear" size="25" @click="onDelete(student)" />
              </van-cell>
            </div>
          </template>
        </van-dropdown-item>
      </van-dropdown-menu>
    </van-submit-bar>
  </div>
</template>

<script>
import { getAllOrganization, studentsFilter, getStuSubject, getActivityCourseTimeList } from "./api";
import DropSelect from "./components/drop-select.vue";
import MEmpty from "../../components/MEmpty.vue";
import MHeader from "../../components/MHeader.vue";
export default {
  name: "selectStudent",
  components: { DropSelect, MEmpty, MHeader },
  data() {
    return {
      activityId: this.$route.query.categoryId,
      search: "",
      option1: [],
      option2: [],
      studentsData: [],
      selectStudents: [],
      value3: 0,
      options3: [],
      loading: true,
    };
  },
  mounted() {
    this.selectStudents = this.$store.state.activeStudents;
    this.init();
  },
  methods: {
    async init() {
      Promise.all([
        // getAllOrganization(),
        getStuSubject(),
        getActivityCourseTimeList({
          categoryId: this.$route.query.categoryId,
        }),
      ]).then((values) => {
        // const res = values[0];
        const subjects = values[0];
        const courseList = values[1];
        // if (res && res.data && Array.isArray(res.data)) {
        //   this.option1 = res.data.map((n) => {
        //     return {
        //       text: n.name,
        //       value: n.id,
        //       checked: true,
        //     };
        //   });
        // }

        if (subjects && subjects.data && Array.isArray(subjects.data)) {
          this.option2 = subjects.data
            .filter((n) => n)
            .map((n) => {
              return {
                text: n.value,
                value: n.key,
                checked: true,
              };
            });
        }

        if (courseList && courseList.data && Array.isArray(courseList.data)) {
          this.options3 = courseList.data.map((n, index) => {
            if (index === 0) {
              this.value3 = n;
            }
            return {
              text: `单课时长${n}分钟`,
              value: n,
            };
          });
        }
        this.getStudents();
        console.log(values);
      });
    },
    async getStudents() {
      this.loading = true;
      const subjectIds = this.option2.map((n) => (n.checked ? n.value : undefined)).filter((n) => n);
      const organIds = this.option1.map((n) => (n.checked ? n.value : undefined)).filter((n) => n);
      // 获取学员列表
      const res = await studentsFilter({
        categoryId: this.$route.query.categoryId,
        search: this.search,
        singleCourseTime: this.value3, // 单课时长
        subjectIds: subjectIds.join(",") || undefined, // 声部
        organIds: organIds.join(",") || undefined, // 分部
      });
      if (res && res.data && Array.isArray(res.data)) {
        this.studentsData = res.data.map((n) => {
          n.checked = this.selectStudents.filter((s) => s.value == n.userId).length > 0 ? true : false;
          n.text = n.username;
          n.value = n.userId;
          return {
            ...n,
          };
        });
      }
      this.loading = false;
    },
    onSearch() {
      // 搜索
      this.getStudents();
    },
    onFilter1(list) {
      this.option1 = list.map((n) => {
        return { ...n };
      });
      this.getStudents();
      this.$refs.fenbu.toggle(false);
    },
    onFilter2(list) {
      this.option2 = list.map((n) => {
        return { ...n };
      });
      this.getStudents();
      this.$refs.dropdown.toggle(false);
    },
    onOpenDropdown(key) {
      // 筛选弹框
      this.$nextTick(() => {
        this.$refs[key].setList();
      });
    },
    //选择学生
    onSelectStudent(index) {
      const i = this.selectStudents.findIndex((n) => n.value == this.studentsData[index].value);

      if (i > -1) {
        if (this.studentsData[index].checked) {
          this.selectStudents.splice(i, 1);
          this.studentsData[index].checked = false;
        }
      } else {
        const studentNum = parseInt(this.$route.query.studentNum);
        if (studentNum && this.selectStudents.length == studentNum) {
          this.$toast("已到达该类型课程学生人数上限");
          return;
        }
        this.studentsData[index].checked = true;
        this.selectStudents.push({
          ...this.studentsData[index],
        });
      }
    },
    // 删除已选学生
    onDelete(student) {
      const index = this.selectStudents.findIndex((n) => n.value == student.value);
      const stu = this.selectStudents.find((n) => n.value == student.value);
      this.selectStudents.splice(index, 1);
      if (stu) {
        const studentIndex = this.studentsData.findIndex((n) => n.value == student.value);
        if (studentIndex > -1) {
          this.studentsData[studentIndex].checked = false;
        }
      }
    },

    onSubmit() {
      // 下一步
      const studentNum = parseInt(this.$route.query.studentNum);
      if (this.$store.state.activeCourse.name == "小组课") {
        if (this.selectStudents.length > studentNum) {
          this.$toast("已到达该类型课程学生人数上限");
          return;
        }
      } else {
        if (studentNum != this.selectStudents.length) {
          this.$toast("所选学生人数不足");
          return;
        }
      }

      let subject = {
        id: null,
        name: null,
      };
      for (let i = 0; i < this.selectStudents.length; i++) {
        if (!subject.id) {
          subject.id = this.selectStudents[i].subjectId;
          subject.name = this.selectStudents[i].subjectName;
          continue;
        }
        // （小组课）
        if (this.$store.state.activeCourse.name == "小组课") {
          // 小组课不做处理
        } else {
          if (subject.id != this.selectStudents[i].subjectId) {
            this.$toast("所选学生声部不一致");
            return;
          }
        }
      }

      const category = {
        ...this.$store.state.activeCourse,
        subjectId: subject.id,
        subjectName: subject.name,
        courseTime: this.value3,
      };
      this.$store.commit("commit_set_active_course", category);
      this.$store.commit("commit_set_active_students", this.selectStudents);
      this.$router.push(`/classSchedule?activityId=${this.activityId}`);
    },
  },
};
</script>

<style>
body {
  background: #f3f4f8;
}
</style>

<style lang="less" scoped>
.searchWrap {
  position: relative;
  z-index: 100;
}
.selectStudentWrap {
  position: sticky;
  top: 0;
  z-index: 1000;
}
.students {
  padding: 12px 0;
  /deep/ .van-cell__value {
    flex: inherit;
  }
}
.students-right {
  display: flex;
  align-content: center;
}
.submit-bar-popup-title {
  text-align: center;
  padding: 10px 0;
  font-weight: bold;
}
</style>
<style lang="less">
.selectStudent-dropdown {
  .van-dropdown-menu__bar {
    // justify-content: space-around;
  }
  .van-dropdown-menu__item {
    // flex: inherit;
  }
  .checkboxs {
    max-height: calc(60vh - 50px);
    overflow-y: auto;
  }
}
.selectStudent-submit-bar {
  .van-submit-bar__bar {
    justify-content: space-between;
  }
  .van-dropdown-menu__bar {
    box-shadow: none;
  }
}
.stuAvatar {
  width: 0.5rem;
  height: 0.5rem;
  margin-right: 10px;
  border-radius: 50%;
}
</style>
