<template>
  <div class="freeCourse">
    <div>
      <van-field
        label="课程声部"
        input-align="right"
        placeholder="请选择课程声部"
        v-model="subjectListName"
        @click="onSelect('subjectList')"
        readonly
        is-link
      />
      <van-cell
        class="courseStudent"
        title="上课学员"
        @click="onSelect('student')"
        :readonly="true"
        input-align="right"
        :is-link="checkboxSelectDataList.length > 0 ? false : true"
        :value="checkboxSelectDataList.length > 0 ? '重新选择' : '请选择'"
        :value-class="checkboxSelectDataList.length > 0 ? 'studentColor' : null"
      />
      <div
        v-if="checkboxSelectDataList.length > 0"
        style="
          text-align: center;
          line-height: 1.8;
          padding: 0.05rem 0;
          background: #fafbff;
        "
      >
        <p
          style="color: #323233"
          v-for="(item, index) in checkboxSelectDataList"
          :key="index"
        >
          {{ item.username }} - {{ desensitPhone(item.parentsPhone) }}
        </p>
      </div>
      <van-field
        label="教学模式"
        input-align="right"
        placeholder="输选择教学模式"
        readonly
        value="线下"
      />
      <van-field
        label="教学点"
        input-align="right"
        placeholder="请选择教学点"
        @click="onSelect('school')"
        readonly
        v-model="school"
        is-link
      />
      <van-field
        label="课程时长"
        input-align="right"
        placeholder="请选择课程时长"
        readonly
        value="25分钟"
      />
      <van-field
        label="上课日期"
        input-align="right"
        v-model="dataForm.date"
        placeholder="请选择上课日期"
        @click="dataForm.status = true"
        readonly
        is-link
      />

      <div style="margin: 16px">
        <van-button round block type="info" @click="onSubmit"
          >确认排课</van-button
        >
      </div>
    </div>
    <van-popup
      v-model="studentStatus"
      :lock-scroll="true"
      position="bottom"
      :style="{ height: '180%' }"
      class="studentChiose"
    >
      <van-sticky>
        <m-header :backUrl="backUrl" :isFixed="false" name="上课学员" />
        <van-search
          show-action
          shape="round"
          @search="onSearch"
          v-model="params.search"
          placeholder="请输入学生名或手机号"
        >
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
        </van-search>
      </van-sticky>
      <div class="paddingB80">
        <van-list
          v-model="loading"
          class="studentContainer"
          v-if="dataShow"
          key="data"
          :finished="finished"
          finished-text=""
          @load="getStudent"
        >
          <van-checkbox-group v-model="checkboxSelect">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in dataList"
                :key="index"
                @click="onCheckboxSelect(item)"
                class="input-cell"
                :center="true"
              >
                <template slot="icon">
                  <img
                    class="logo"
                    v-if="item.avatar"
                    :src="item.avatar"
                    alt=""
                  />
                  <img
                    class="logo"
                    v-else
                    src="@/assets/images/icon_student.png"
                    alt=""
                  />
                </template>
                <template slot="title">
                  {{ item.username }}
                </template>
                <template slot="label">
                  <span>{{ desensitPhone(item.parentsPhone) }}</span>
                </template>
                <template slot="default">
                  <van-checkbox :name="item.userId.toString()"></van-checkbox>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </van-list>
        <m-empty class="empty" v-else key="data" />
      </div>
      <div class="button-group-popup">
        <span class="btn" @click="onPopupCancel">取消</span>
        <span class="btn primary" @click="onPopupSubmit">确定</span>
      </div>
    </van-popup>

    <van-popup
      v-model="dataForm.status"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-datetime-picker
        v-model="dataForm.currentDate"
        :formatter="formatter"
        @cancel="dataForm.status = false"
        @confirm="choiceDate"
      />
    </van-popup>
    <van-popup
      v-model="infoForm.status"
      position="bottom"
    >
      <van-picker
        show-toolbar
        :columns="schoolList"
        @confirm="onConfirm"
        @cancel="infoForm.status = false"
      />
    </van-popup>

    <van-popup
      v-model="subjectStatus"
      position="bottom"
    >
      <van-picker
        :loading="subjectLoading"
        show-toolbar
        @confirm="onConfirmSubject"
        :columns="subjectList"
        @cancel="subjectStatus = false"
      />
    </van-popup>

  </div>
</template>

<script>
import MHeader from "@/components/MHeader";
import dayjs from "dayjs";
import {
  findBySubjectByIdList
} from "@/api/teacher";
import cleanDeep from 'clean-deep'
import { getStudents, createActivityVipGroup, findVipSchoolByTeacher } from "../api";
// import { findVipSchoolByTeacher } from "@/api/smallWeb";
import MEmpty from "@/components/MEmpty";
import setLoading from "@/utils/loading";
export default {
  components: {
    MHeader,
    MEmpty
  },
  name: "apply",
  data() {
    return {
      dataForm: {
        // 时间下拉框
        status: false,
        currentDate: new Date(),
        date: null,
      },
      backUrl: {
        status: true,
        callBack: () => {
          this.studentStatus = false
        }
      },
      infoForm: {
        status: false,
      },
      studentStatus: false,
      subjectListName: "",
      subjectId: "",
      subjectList: [], // 声部列表
      subjectIdList: null,
      subjectStatus: false,
      subjectLoading: false,
      params: {
        search: null,
        page: 1,
        rows: 20,
      },
      dataList: [],
      dataShow: false,
      loading: true,
      finished: false,
      checkboxSelect: [],
      checkboxSelectIds: [],
      checkboxSelectList: [], //选中学生列表
      checkboxSelectDataList: [],
      schoolList: [],
      school: "",
      schoolId: "",
      timeTable: [],
    };
  },
  methods: {
    async getSchool() {
      await findVipSchoolByTeacher({ userId: this.teacherId }).then((res) => {
        let result = res.data;
        this.schoolList = [];
        result.data.forEach((item) => {
          this.schoolList.push({
            text: item.name,
            id: item.id,
          });
        });
      });
    },
    async onSubmit() {
      if (!this.teacherId) {
        this.$toast("请选择授课老师");
        return;
      }
      if(!this.subjectId) {
        this.$toast('请选择课程声部')
        return;
      }
      if (this.checkboxSelectIds.length < 1) {
        this.$toast("请至少选择一名学员");
        return;
      }
      if (!this.schoolId) {
        this.$toast("请选择教学点");
        return;
      }
      if (!this.dataForm.date) {
        this.$toast("请选择上课日期");
        return;
      }
      let form = {};
      form.activityCourseType = "free_vip";
      form.studentIdList = this.checkboxSelectIds.join(",");
      form.teacherSchoolId = this.schoolId;
      form.totalClassTimes = 1;
      form.teacherId = this.teacherId;
      form.userId = this.teacherId;
      form.courseStart = dayjs(this.dataForm.currentDate).format("YYYY-MM-DD");
      form.firstStudentId =
        this.checkboxSelectDataList.length > 0
          ? this.checkboxSelectDataList[0].userId
          : null;
      form.singleClassMinutes = 25;
      form.onlineClassesNum = 0;
      form.offlineClassesNum = 1;
      form.offlineClassesUnitPrice = 0;
      form.onlineClassesUnitPrice = 0;
      form.subjectIdList = this.subjectId;
      this.timeTable = [
        {
          classDate: form.courseStart,
          startClassTimeStr: dayjs(this.dataForm.currentDate).format("HH:mm"),
          teachMode: "OFFLINE",
        },
      ];
      let params = {
        courseSchedules: this.timeTable,
        vipGroupApplyBaseInfo: form,
      };
      setLoading(true)
      await createActivityVipGroup(params).then((res) => {
        let result = res.data;
        setLoading(false);
        if (result.code == 200) {
          this.$toast("申请成功");
          setTimeout(() => {
            this.$emit('reLoad', 1)
            this.onSubmitStatus = true;
          }, 500);
        } else {
          this.onSubmitStatus = true;
          this.salaryStatus = true;
          this.$toast(result.msg);
        }
      }).catch(() => {
        setLoading(false)
      });
    },
    async onSelect(type) {
      if(type == "subjectList") {
        this.subjectStatus = true
        if(this.subjectList.length <= 0) {
          // 请求声部
          this.subjectLoading = true
          await findBySubjectByIdList({
            subjectIdList: this.subjectIdList,
          }).then((res) => {
            let result = res.data;
            if (result.code == 200 && result.data.length > 0) {
              let tempArr = [];
              result.data.forEach((item) => {
                item.value = item.id;
                item.text = item.name;
                tempArr.push(item);
              });
              this.subjectList = tempArr;
              this.subjectLoading = false;
            } else {
              this.$toast("暂无科目列表");
              this.subjectLoading = false;
            }
          });
        }
        return
      }
      if(type == 'student' && !this.subjectId) {
        this.$toast('请选择课程声部')
        return
      }
      if (type == "student") {
        this.studentStatus = true;
        this.onSearch();
        return;
      }
      this.infoForm.status = true;
    },
    onConfirm(value) {
      if (value) {
        (this.school = value.text), (this.schoolId = value.id);
      } else {
        this.school = "";
        this.schoolId = "";
      }

      this.infoForm.status = false;
    },
    onConfirmSubject(value) {
      this.subjectListName = value.text
      this.subjectId = value.id
      this.subjectStatus = false

      // 重置上课学员
      this.dataList = []
      this.params.search = null
      this.loading = false
      this.finished = false
      this.dataShow = true
      this.checkboxSelect = [];
      this.checkboxSelectIds = [];
      this.checkboxSelectList = []; //选中学生列表
      this.checkboxSelectDataList = [];
    },
    choiceDate(value) {
      if (value) {
        this.dataForm.date = dayjs(value).format("YYYY/MM/DD HH:mm");
      }

      this.dataForm.status = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      } else if (type == "day") {
        return `${val}日`;
      } else if (type == "hour") {
        return `${val}时`;
      } else if (type == "minute") {
        return `${val}分`;
      }
      return val;
    },
    onSearch() {
      this.params.page = 1;
      this.dataList = [];
      this.dataShow = true;
      this.loading = true;
      this.finished = false;
      this.getStudent();
    },
    getStudent() {
      let params = this.params;
      getStudents(cleanDeep({ ...params, activityCourseType: "free_vip", subjectId: this.subjectId })).then((res) => {
        let result = res.data;
        this.loading = false;
        if (result.code == 200) {
          if(this.dataList.length > 0 && result.data.pageNo == 1) {
              return
          }
          params.page = result.data.pageNo;
          this.dataList = this.dataList.concat(result.data.rows);
          if (params.page >= result.data.totalPage) {
            this.finished = true;
          }
          this.params.page++;
        } else {
          this.finished = true;
        }
        // 判断是否有数据
        if (this.dataList.length <= 0) {
          this.dataShow = false;
        }
      });
    },
    onPopupCancel() {
      // 关闭弹窗
      this.studentStatus = false;
      this.params.search = null;
      this.checkboxSelect = [];
      this.checkboxSelectList = [];
    },
    onPopupSubmit() {
      if (this.checkboxSelect.length == 0 || this.checkboxSelect.length > 2) {
        this.$toast(`请选择学生1~2名学生`);
        return;
      }
      this.checkboxSelectDataList = JSON.parse(
        JSON.stringify(this.checkboxSelectList)
      );
      this.checkboxSelectIds = JSON.parse(JSON.stringify(this.checkboxSelect));
      this.checkboxSelect = [];
      this.checkboxSelectList = [];

      this.studentStatus = false;
    },
    onCheckboxSelect(value) {
      if (this.checkboxSelect.includes(value.userId.toString())) {
        this.checkboxSelect.forEach((item, index) => {
          if (item == value.userId.toString()) {
            this.checkboxSelect.splice(index, 1);
          }
        });
        this.checkboxSelectList.forEach((item, index) => {
          if (item.userId == value.userId) {
            this.checkboxSelectList.splice(index, 1);
          }
        });
      } else {
        this.checkboxSelect.push(value.userId.toString());
        this.checkboxSelectList.push(value);
      }
      // checkboxSelect = item.userId
    },
    desensitPhone(phone) {
      // 手机号脱敏
      let first = "";
      let last = "";
      if (phone) {
        first = phone.substr(0, 3);
        last = phone.substr(-4);
      }
      return first + "****" + last;
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../assets/commonLess/variable.less");
.button-group-popup {
  position: fixed;
  bottom: 0;
  padding: 0.2rem 0;
  width: 100%;
  text-align: center;
  background-color: #ffffff;
  .btn {
    padding: 0 0.45rem;
    line-height: 0.4rem;
    display: inline-block;
    border: 1px solid @mColor;
    border-radius: 1rem;
    color: @mColor;
    background: #fff;
    font-size: 0.18rem;
    &.primary {
      color: #fff;
      background: @mColor;
    }
  }
  .btn + .btn {
    margin-left: 0.1rem;
  }
}

.studentContainer {
  /deep/.van-cell__title {
    font-size: 0.14rem;
    color: @mFontColor;
    flex: 1 auto;
  }

  .logo {
    width: 0.35rem;
    height: 0.35rem;
    margin-right: 0.12rem;
    border-radius: 100%;
  }

  .input-cell {
    padding: 0.12rem 0.16rem 0.2rem;

    .van-checkbox {
      justify-content: flex-end;
    }
  }

  /deep/.van-cell__value {
    height: 0.2rem;
  }

  /deep/.van-checkbox__icon .van-icon {
    border-color: @sFontColor;
  }

  /deep/.van-checkbox__icon--checked {
    .van-icon {
      border-color: @orangeColor;
      background: @orangeColor;
    }
  }

  .van-tag {
    margin-left: 0.08rem;
  }
}
/deep/.van-cell__title {
  -webkit-box-flex: 0;
  -webkit-flex: none;
  flex: none;
  box-sizing: border-box;
  margin-right: 12px;
  color: #646566;
  text-align: left;
  word-wrap: break-word;
  font-size: 14px;
}
.studentColor {
  color: @mColor !important;
}
.courseStudent {
  .van-cell__value {
    color: #c8c9cc;
  }
}
.paddingB80 {
  padding-bottom: .8rem;
}
</style>