<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: .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: .12rem; padding-left: .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'
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,
            }], // 默认加一个空的，做占位
          })
        } 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
    })
  },
  methods: {
    onSelectAccompany(item, index) {
      this.accompanimentStatus = true
      this.tabActiveList = item
      this.tabActiveIndex = index
    },
    delAccompany(music, index) {
      if(music.length == 1) {
        music[0] = {
          id: null,
          name: 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) {
      this.tabActiveList.musicScoreIdList[this.tabActiveIndex] = {
        id: value.examSongId,
        name: value.examSongName
      }
      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 = []
        subject.musicScoreIdList.forEach(music => {
          if(music.id) {
            scoreIdList.push(music.id)
          }
        })
        if(scoreIdList.length <= 0) {
          notAccompanySong.push(subject.subjectName)
        }
        musicScoreSubjectDto.push({
          musicScoreIdList: scoreIdList,
          userIdList: subject.userIdList
        })
      })
      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 query = this.$route.query
      let params = {
        title: this.title,
        content: this.content,
        courseScheduleId: query.courseId,
        expiryDate: dayjs(this.dateSection.currentDate).format('YYYY-MM-DD'),
        musicScoreSubjectDto: musicScoreSubjectDto
      }
      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: .14rem;
  padding: .12rem .16rem;
  line-height: .24rem;
}

.arrowDown {
  display: inline-block;
  margin-left: .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: .1rem;
    background: #ffffff;
  }
  .formTitle {
    padding: .12rem .21rem 0;
    font-size: .16rem;
    color: #333333;
    font-weight: 500;
  }
}

.endTime {
  margin-top: .1rem;
  .van-cell__title {
    font-size: .16rem;
    color: #1A1A1A;
  }

  /deep/.van-cell__value {
    // width: 30%;
    justify-content: flex-end;
    text-align: right;
    font-size: .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: .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: .14rem;
  padding: .16rem .08rem .14rem;
  color: #333;
  font-weight: 500;
  span {
    color: #808080;
  }
}
.addAccompaniment {
  width: 80%;
  height: .42rem;
  line-height: .42rem;
  text-align: center;
  margin: .1rem auto 0;
  border: 1px dashed #CCC;
  background: #FBFBFB;
  font-size: .14rem;
  color: #666666;
}

</style>
