<template>
  <div class="arrangeWork">
    <m-header v-if="headerStatus" />
    <van-cell :title="classGroupName" title-style="font-size: .18rem; color: #333333;">
      <template #extra>
        <van-tag type="primary" plain style="background-color: #f1fcf9">课后练习</van-tag>
      </template>
    </van-cell>
    <van-cell class="endTime" readonly is-link title-style="font-size: .16rem; color: #333333;" @click="studentStatus = true">
      <template #title>
        <span style="padding-right: 0.3rem"
          >学员共<i style="font-style: normal; color: #01c1b5">{{ params.studentCount }}</i
          >人</span
        >
        <span
          >会员 <i style="font-style: normal; color: #ff802c">{{ params.studentMemberCount }}</i
          >人</span
        >
      </template>
    </van-cell>
    <div class="container">
      <div class="formGroup">
        <div class="dot"></div>
        <div class="formTitle">练习标题</div>
        <van-field v-model="title" type="text" maxlength="25" show-word-limit placeholder="请输入练习标题" />
      </div>
      <div class="formGroup">
        <div class="dot"></div>
        <div class="formTitle">练习内容</div>
        <van-field rows="4" v-model="content" maxlength="600" show-word-limit type="textarea" placeholder="请输入练习内容" />
      </div>
    </div>
    <!-- <van-cell
      class="endTime"
      style="padding: 0.12rem 0.21rem;"
      title="练习提交截止时间"
      @click="onEndTime"
      is-link
      readonly
      placeholder="请选择截止时间"
    >
      <template #title>
        <div class="dot"></div>
        练习提交截止时间
      </template>
      <template #default>
        {{ dateSection.showStartDate }}
      </template>
    </van-cell> -->

    <div class="accompanyHeader">云练习曲目选择<span>(若练习内容非云练习曲目则无需选择)</span></div>
    <van-tabs v-model="tabActive" color="#01C1B5">
      <van-tab v-for="(item, i) in params.subjectList" :title="item.subjectName" :name="item.id" :key="i" class="van-hairline--bottom">
        <van-cell class="endTime" v-for="(music, index) in item.musicScoreIdList" :key="index" style="margin-top: 0; padding: 0.12rem 0.21rem" title="练习曲目" @click="onSelectAccompany(item, index)" readonly is-link placeholder="请选择练习曲目">
          <template #title>
            <div class="dot"></div>
            练习曲目
          </template>
          <template #default>
            <template v-if="music.name">
              {{ music.name }}
            </template>
            <span v-else style="color: #808080">请选择</span>
          </template>
          <template #right-icon>
            <span v-if="music.name" @click.stop="delAccompany(item.musicScoreIdList, index)" style="color: #999999; font-size: 0.12rem; padding-left: 0.12rem"><van-icon size="14" name="delete-o" />删除</span>
          </template>
          <template #extra>
            <!-- <span><van-icon name="delete-o" />删除</span> -->
            <span style="height: 24px; font-size: 16px; line-height: 24px; color: #dadada !important"><van-icon name="arrow" /></span>
          </template>
        </van-cell>
        <div class="addAccompaniment" v-if="item.musicScoreIdList.length < 3" @click="addCloud(item)"><van-icon name="plus" size="16px" />增加云练习练习曲目</div>
      </van-tab>
    </van-tabs>

    <div class="button-group">
      <van-button type="primary" round size="large" @click="onSubmit">确定</van-button>
    </div>

    <!-- 日期开始弹窗 -->
    <van-popup position="bottom" v-model="dateSection.status">
      <van-datetime-picker v-model="dateSection.currentDate" type="date" :min-date="dateSection.minDate" :max-date="dateSection.maxDate" :formatter="formatter" @confirm="confirmStartTime()" @cancel="dateSection.status = false" />
    </van-popup>

    <van-popup position="bottom" v-model="accompanimentStatus" :style="{ height: '100%' }" style="border-radius: 0; overflow: inherit">
      <!-- <van-sticky>
        <m-header name="练习曲目" :backUrl="backUrl" />
      </van-sticky> -->
      <!-- <accompaniment-modal @onSelectMusic="onSelectMusic" ref="accompaniment" style="margin-bottom: 0.8rem;" :searchSubjectId="tabActive" /> -->
      <!-- style="margin-bottom: 0.8rem;" -->
      <workModel @onSelectMusic="onSelectMusic" @close="accompanimentStatus = false" ref="accompaniment" :searchSubjectId="tabActive" />
      <!-- <div class="button-group-popup">
        <span class="btn" @click="accompanimentStatus = false">关闭</span>
      </div> -->
    </van-popup>

    <van-popup v-model="studentStatus" :lock-scroll="true" position="bottom" :style="{ height: '180%' }">
      <!-- <van-sticky>
        <m-header name="学员列表" :backUrl="backUrlStudent" />
      </van-sticky> -->
      <student-list-model :dataList="dataList" style="margin-bottom: 0.8rem" @close="studentStatus = false" :dataSubjectList="dataSubjectList"></student-list-model>
    </van-popup>
  </div>
</template>
<script>
import MHeader from "@/components/MHeader";
import { browser, _throttle } from "@/common/common";
import dayjs from "dayjs";
import { addHomeWork } from "@/api/audition";
import { getCourseStudents } from "@/api/teacher";
// import AccompanimentModal from './modal/accompanimentModal'
import workModel from "./modal/workModel";
import StudentListModel from "./modal/studentList";
import cleanDeep from "clean-deep";
import deepClone from "@/helpers/deep-clone";
import { postMessage, listenerMessage } from "@/helpers/native-message";
export default {
  name: "teacherList",
  components: { MHeader, workModel, StudentListModel },
  data() {
    let tempDate = new Date(); // 默认显示T+3
    tempDate.setDate(tempDate.getDate() + 3);
    let query = this.$route.query;
    return {
      headerStatus: true,
      backUrl: {
        status: true,
        callBack: () => {
          this.accompanimentStatus = false;
        },
      },
      backUrlStudent: {
        status: true,
        callBack: () => {
          this.studentStatus = false;
        },
      },
      classGroupName: query.classGroupName,
      courseId: query.courseId || query.id,
      dateSection: {
        status: false,
        minDate: new Date(),
        maxDate: new Date(2025, 10, 1),
        currentDate: tempDate,
        showStartDate: dayjs(tempDate).format("YYYY年MM月DD日"),
        musicScoreId: null,
        musicScoreName: null,
      },
      title: "",
      content: "", // 课程编号
      expiryDate: null, // 练习截止日期
      accompanimentStatus: false, // 伴奏弹窗
      tabActive: 0,
      tabOriginActive: 0,
      tabActiveList: {}, // 选中当前信息
      tabActiveIndex: 0,
      params: {
        studentCount: 0, // 学员总数
        studentMemberCount: 0, // 学员会员数
        subjectIdList: [],
        subjectList: [],
      },
      dataList: [],
      dataSubjectList: [],
      studentStatus: false,
    };
  },
  async mounted() {
    let params = this.$route.query;
    if (params.Authorization) {
      localStorage.setItem("Authorization", decodeURI(params.Authorization));
      localStorage.setItem("userInfo", decodeURI(params.Authorization));
    }
    document.title = "布置练习";
    if (browser().android || browser().iPhone) {
      this.headerStatus = false;
    }
    // 获取课程学员【根据接口初始化声部列表】
    await getCourseStudents({ courseScheduleId: this.courseId }).then((res) => {
      const result = res.data;
      if (result.code != 200) {
        return;
      }
      const tempData = result.data || [];
      let params = {
        studentCount: tempData.length, // 学员总数
        studentMemberCount: 0, // 学员会员数
        subjectIdList: [],
        subjectList: [],
      };
      tempData.forEach((item) => {
        // 判断当前学员是否有会员
        if (item.memberRankSettingId) {
          params.studentMemberCount++;
        }
        if (!params.subjectIdList.includes(item.subjectIdList || -1)) {
          params.subjectIdList.push(item.subjectIdList || -1);
          params.subjectList.push({
            id: item.subjectIdList || -1,
            subjectName: item.subjectName || "无声部",
            userIdList: [item.userId],
            musicScoreIdList: [
              {
                id: null,
                name: null,
                songPart: null,
              },
            ], // 默认加一个空的，做占位
          });
        } else {
          params.subjectList.forEach((subject) => {
            if (subject.id == item.subjectIdList) {
              subject.userIdList.push(item.userId);
            }
            if (!item.subjectIdList && subject.id == -1) {
              subject.userIdList.push(item.userId);
            }
          });
        }
        if (!item.subjectIdList) {
          item.subjectIdList = -1;
        }
      });
      this.dataList = tempData;
      // 默认选中第1条数据
      this.tabActive = params.subjectIdList[0];
      this.tabOriginActive = params.subjectIdList[0];
      this.dataSubjectList = deepClone(params.subjectList);
      this.params = params;
    });

    // 获取当前课程的练习列表
    let _this = this;
    listenerMessage("getAccompany", (res) => {
      console.log(res);
      if (res && res.content) {
        _this.tabActiveList.musicScoreIdList[this.tabActiveIndex] = {
          id: res.content.songId,
          name: res.content.songName,
          songPart: res.content.songPart,
        };
        _this.$forceUpdate();
        console.log(res.content, _this.tabActiveList, this.params);
      }
    });
  },
  methods: {
    onSelectAccompany(item, index) {
      // this.accompanimentStatus = true;
      // 唤起弹窗
      postMessage({
        api: "openAccompany",
        content: {
          subjectId: item.id,
        },
      });
      this.tabActiveList = item;
      this.tabActiveIndex = index;
    },
    delAccompany(music, index) {
      if (music.length == 1) {
        music[0] = {
          id: null,
          name: null,
          songPart: null,
        };
        this.$forceUpdate();
      } else {
        music.splice(index, 1);
      }
    },
    addCloud(item) {
      if (item.musicScoreIdList.length < 3) {
        item.musicScoreIdList.push("");
      }
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      } else if (type == "day") {
        return `${val}日`;
      }
      return val;
    },
    onSelectMusic(value) {
      // console.log(value);
      this.tabActiveList.musicScoreIdList[this.tabActiveIndex] = {
        id: value.examSongId,
        name: value.name,
      };
      this.accompanimentStatus = false;
    },
    confirmStartTime() {
      this.dateSection.showStartDate = dayjs(this.dateSection.currentDate).format("YYYY年MM月DD日");
      this.dateSection.status = false;
    },
    onEndTime() {
      this.dateSection.status = true;
    },
    onSubmit: _throttle(function (type) {
      if (!this.title) {
        this.$toast("请输入练习标题");
        return;
      }
      if (!this.content) {
        this.$toast("请输入练习内容");
        return;
      }
      let tempSubjectList = this.params.subjectList;
      let musicScoreSubjectDto = [];
      let notAccompanySong = []; // 用于判断没有设置练习曲目的数据
      let subjectLength = this.params.subjectIdList.length;
      tempSubjectList.forEach((subject) => {
        let scoreIdList = [];
        let scoreList = [];
        subject.musicScoreIdList.forEach((music) => {
          if (music.id) {
            scoreIdList.push(music.id);
            scoreList.push({
              musicScoreId: music.id,
              partIndex: music.songPart,
            });
          }
        });
        if (scoreIdList.length <= 0) {
          notAccompanySong.push(subject.subjectName);
        }
        musicScoreSubjectDto.push({
          musicScoreIdList: scoreIdList,
          userIdList: subject.userIdList,
          musicScoreHomeworkDtoList: scoreList,
        });
      });
      if (notAccompanySong.length - subjectLength <= 0 && notAccompanySong != 0 && type[0] != 1) {
        // console.log('选择曲目')
        this.$dialog
          .confirm({
            message: notAccompanySong.join(",") + "声部未选择云练习练习曲目，是否继续布置练习？",
            confirmButtonColor: "#01C1B5",
          })
          .then(() => {
            // on confirm
            this.onSubmit(1);
          })
          .catch(() => {
            // on cancel
          });
        return;
      }
      // this.$toast.loading({
      //   message: '加载中...',
      //   duration: 10000,
      //   forbidClick: true,
      //   loadingType: 'spinner',
      // })
      let params = {
        title: this.title,
        content: this.content,
        courseScheduleId: this.courseId,
        // expiryDate: dayjs(this.dateSection.currentDate).format("YYYY-MM-DD"),
        musicScoreSubjectDto: musicScoreSubjectDto,
      };
      // console.log(params, "params");
      addHomeWork(cleanDeep({ ...params })).then((res) => {
        let result = res.data;
        this.$toast.clear();
        if (result.code == 200) {
          this.$toast("练习布置成功");
          setTimeout(() => {
            let query = this.$route.query;
            const path = query.isNewJoin == 1 ? "/afterClassEvaluateDetail" : "/courseEvaluation";
            this.$router.replace({
              path,
              query: {
                id: query.id,
                reviewId: query.reviewId,
                isInside: query.isInside,
                work: 1,
              },
            });
          }, 500);
        } else {
          this.$toast(result.msg);
        }
      });
    }, 500),
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable.less");
.arrangeWork {
  min-height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #f3f4f8;
}
/deep/.van-cell {
  font-size: 0.14rem;
  padding: 0.12rem 0.16rem;
  line-height: 0.24rem;
}

.arrowDown {
  display: inline-block;
  margin-left: 0.1rem;
  width: 0.1rem;
  height: 0.07rem;
  background: url("../../assets/images/audition/arrow_down.png") no-repeat center center;
  background-size: 100%;
}

.container {
  .formGroup {
    position: relative;
    margin-top: 0.1rem;
    background: #ffffff;
  }
  .formTitle {
    padding: 0.12rem 0.21rem 0;
    font-size: 0.16rem;
    color: #333333;
    font-weight: 500;
  }
}

.endTime {
  margin-top: 0.1rem;
  .van-cell__title {
    font-size: 0.16rem;
    color: #1a1a1a;
  }

  /deep/.van-cell__value {
    // width: 30%;
    justify-content: flex-end;
    text-align: right;
    font-size: 0.16rem;
    color: #1a1a1a;
    display: flex;
    align-items: center;
  }
}

.button-group {
  margin: 0.3rem 0.26rem 0.2rem;
  .van-button--primary {
    background: @mColor;
    border: 1px solid @mColor;
    font-size: 0.18rem;
  }
}

.dot {
  width: 4px;
  height: 0.17rem;
  background: #01c1b5;
  border-radius: 3px;
  position: absolute;
  z-index: 98;
  top: 0.15rem;
  left: 0.12rem;
}
/deep/.van-tab {
  font-size: 16px;
}
/deep/.van-popup--bottom {
  border-radius: 0px 0px 0px 0px !important;
  overflow: auto !important;
}
.accompanyHeader {
  font-size: 0.14rem;
  padding: 0.16rem 0.08rem 0.14rem;
  color: #333;
  font-weight: 500;
  span {
    color: #808080;
  }
}
.addAccompaniment {
  width: 80%;
  height: 0.42rem;
  line-height: 0.42rem;
  text-align: center;
  margin: 0.1rem auto 0;
  border: 1px dashed #ccc;
  background: #fbfbfb;
  font-size: 0.14rem;
  color: #666666;
}
</style>
