<template>
    <div class="courseApply">
        <m-header v-if="statusList.headerStatus" />
        <van-cell-group>
            <van-field v-model="form.name" label="课程班名称" input-align="right" size="large" 
                placeholder="请输入班级名称" />
            <van-field v-model="formName.subjectListName" @click="onGetSheetList('subjectList')" 
                label="科目名称" :readonly="true" input-align="right" is-link size="large" placeholder="请选择" />
        </van-cell-group>
        <van-cell-group>
            <van-field v-model="form.studentNum" label="每班人数" :readonly="true" input-align="right" size="large" is-link placeholder="每班预计招收人数" @click="statusList.studentNumStatus = true" />
            <van-field v-model="form.singleClassMinutes" @click="onClickSingleClass" label="每课时长"  :readonly="true" input-align="right" is-link size="large" placeholder="请输入每课时长" />
        </van-cell-group>
        <van-cell-group>
            <van-field v-model="form.courseCount" label="排课数量" input-align="right" size="large" placeholder="请输入排课数量" type="digit" @input="onCourseChange" />
            <van-field @click="dataForm.status = true" v-model="formName.courseStart" label="排课开始时间" :readonly="true" input-align="right" is-link size="large" placeholder="请选择" />

            <van-cell title-class="title-time" v-for="(item, index) in scheduleList" :key="index">
                <template slot="title">
                    <span class="week">{{ item.weekStr }}</span>
                    <span class="timer">{{ item.startTime + '-' + item.endTime }}</span>
                </template>
                <template slot="default">
                    <van-button type="warning" @click="onScheduleRemove(item)" round size="small" plain >删除</van-button>
                </template>
            </van-cell>
            <div class="add-plan van-cell" @click="onCourseShedule">
                <p><van-icon name="add-o" />请设置循环周期/每周</p>
                <!-- <p style="color: #999; font-size: .14rem">请选择开课周期/上课时间点</p> -->
            </div>
            <van-field label="排课列表" v-if="scheduleList.length > 0" 
                disabled input-align="right" @click="onShowTimeTable" is-link size="large" />
        </van-cell-group>

        <van-cell-group>
            <van-field v-model="consumePeriodText" label="预计消耗课时" disabled input-align="right" size="large" placeholder="预计消耗课时" />
            <van-field v-model="usePeriodText" label="剩余可用课时" input-align="right" disabled size="large" placeholder="剩余可用课时" />
        </van-cell-group>

        <!-- <div class="agreeProtocol">
            <van-checkbox v-model="statusList.agreeStatus"></van-checkbox>
            <i style="font-style: normal;" @click="statusList.agreeStatus = !statusList.agreeStatus">已阅读并同意</i> <span>《课程创建协议》</span>
        </div> -->

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

        <!-- 每班人数 -->
        <van-action-sheet v-model="statusList.studentNumStatus" :round="false" :actions="loadData.studentNumList" cancel-text="取消"  @cancel="statusList.studentNumStatus = false" @select="onStudentSelect" />
        <!-- 每课时长 -->
        <van-popup v-model="statusList.classTimerStatus" position="bottom">
            <van-picker :columns="loadData.classTimer" show-toolbar @cancel="statusList.classTimerStatus = false" @confirm="onClassTimerSelect" />
        </van-popup>

        <!-- 课程信息所用 :close-on-click-overlay="false"  -->
        <van-popup v-model="sheetForm.sheetStatus" position="bottom">
            <van-picker :loading="sheetForm.loading" :default-index="sheetForm.index" :columns="sheetForm.columns" 
                show-toolbar @cancel="sheetForm.sheetStatus = false" @confirm="onSheetConfirm" />
        </van-popup>
        <!-- 课时安排 -->
        <van-popup v-model="dataForm.status" position="bottom">
            <van-datetime-picker v-model="dataForm.currentDate" type="date" :min-date="dataForm.minDate" 
                :max-date="dataForm.maxDate" :formatter="formatter" @cancel="dataForm.status = false" 
                @confirm="onCurrentConfirm" />
        </van-popup>
        <!-- 课时安排 -->
        <van-popup v-model="courseForm.teachingStatus" position="bottom">
            <van-picker :columns="courseForm.columns" show-toolbar @cancel="courseForm.teachingStatus = false" @confirm="onTeachinConfirm" />
        </van-popup>
        <!-- 课表展示 -->
        <van-popup v-model="statusList.classTime" position="bottom">
            <van-row>
                <!-- <van-col span="12">上课类型</van-col> -->
                <van-col span="24">上课时间</van-col>
            </van-row>
            <div class="tableContainer">
                <van-row v-for="(item, index) in timeTable" :key="index">
                    <!-- <van-col span="12">线上</van-col> -->
                    <van-col span="24">
                        {{ item.classDate }} {{ item.startClassTimeStr }} {{ getWeekStr(new Date(item.classDate).getDay()) }}
                    </van-col>
                </van-row>
            </div>
        </van-popup>
    </div>
</template>
<script>
/* eslint-disable */
import MHeader from '@/components/MHeader'
import { browser, calcMinute }  from '@/common/common'
import { subjectFindSubSubjects } from '@/api/teacher'
import { createCourseGroup, sysTenantAccountGet } from '@/api/app'
let minutes = []  // 分钟数
for(let i = 0; i < 60; i++) {
    let mi = i < 10 ? '0' + i : i
    minutes.push(mi + '分')
}
export default {
    name: 'courseApply',
    components: { MHeader },
    data() {
        // 获取有没有传参
        let courseList = localStorage.getItem('courseApply')
        courseList = courseList ? JSON.parse(courseList) : null
        localStorage.removeItem('courseApply')
        return {
            dataForm: { // 时间下拉框
                status: false,
                minDate: new Date(),
                maxDate: new Date(2025, 10, 1),
                currentDate: new Date()
            },
            statusList: { // 散状态集合
                classTime: false, // 课表展示
                headerStatus: true, // 头部是否展示
                studentNumStatus: false, // 每班人数
                classTimerStatus: false, // 每课时长状态
                agreeStatus: false // 协议状态
            },
            loadData: { // 下拉加载数据
                subjectList: [], // 声部列表
                subjectListSelect: [], // 选中的声部JSON
                classTimer: [{
                    values: [15, 30, 45, 60, 75, 90, 105, 120],
                    className: 'classTimer'
                }], // 每课时长
                // studentNumList: [{ name: 1, subname: '(人)'},{ name: 2, subname: '(人)'},{ name: 3, subname: '(人)'},{ name: 4, subname: '(人)'},{ name: 5, subname: '(人)'}]
                studentNumList: [{ name: 1, subname: '(人)'}]
            },
            sheetForm: { // 上拉弹窗
                currentType: null, // 当前选择的类型
                sheetStatus: false,
                loading: true, // 加载数据
                index: 0, // 选中的索引值
                columns: []
            },
            courseForm: { // 排课弹窗
                teachingStatus: false, // 课时安排状态
                columns: [{
                    values: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                    className: 'week'
                }, {
                    values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
                    className: 'hours',
                    defaultIndex: 7
                }, {
                    values: minutes,
                    className: 'minutes'
                }]
            },
            form: courseList ? courseList.form : {
                name: null,
                subjectIdList: null,
                studentNum: null,
                singleClassMinutes: null,
                courseCount: null,
                courseStart: null
            },
            formName: courseList ? courseList.formName : {
                subjectListName: null, // 声部名称
                subjectListIndex: 0, // 声部名称
                courseStart: null
            },
            scheduleList: courseList ? courseList.scheduleList : [], // 课时安排
            timeTable: [], // 生成的课表
            onSubmitStatus: true, // 点击
            consumePeriod: courseList ? courseList.consumePeriod : 0, // 消耗课时
            consumePeriodText: courseList ? courseList.consumePeriodText : '0分钟',
            usePeriod: 0, // 可用课时
            usePeriodText: '0分钟',
        }
    },
    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.statusList.headerStatus = false
        }

        sysTenantAccountGet().then(res => {
            let result = res.data
            if(result.code == 200) {
                let tempResult = result.data
                if(tempResult) {
                    this.usePeriod = tempResult.availableMinutes ? tempResult.availableMinutes : 0
                    this.usePeriodText = calcMinute(this.usePeriod)
                }
            } else {
                this.$toast(result.msg)
            }
        })
    },
    methods: {
        onGetSheetList(name) { // 获取科目列表
            let sheetForm = this.sheetForm
            sheetForm.sheetStatus = true
            sheetForm.loading = true
            sheetForm.currentType = name
            sheetForm.index = 0
            let arr = this.loadData[name]
            if(arr.length > 0) {
                sheetForm.columns = arr
                sheetForm.index = this.formName[name + 'Index']
                sheetForm.loading = false
            } else {
                this.onLoadingData(name)
            }
            
        },
        onLoadingData() { // 加载数据
            let sheetForm = this.sheetForm
            if(sheetForm.currentType == 'subjectList') { // 声部列表
                subjectFindSubSubjects().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.loadData.subjectList = tempArr
                        sheetForm.columns = tempArr
                        sheetForm.loading = false
                    } else {
                        this.$toast('暂无科目列表')
                        sheetForm.loading = false
                    }
                })
            }
        },
        onSheetConfirm(value, index) { // 上拉弹窗
            let sheetForm = this.sheetForm,
                form = this.form,
                formName = this.formName,
                loadData = this.loadData
            if(!value) {
                return
            }
            if(sheetForm.currentType == 'subjectList') { // 科目名称赋值
                form.subjectIdList = value.value
                formName.subjectListName = value.text
                formName.subjectListIndex = index
                loadData.subjectListSelect = value
            }
            sheetForm.sheetStatus = false
        },
        onClickSingleClass() {
            this.statusList.classTimerStatus = true
        },
        onCourseChange() {
            // 计算消耗课时
            this.calcTimer()
            this.scheduleList = []
            this.timeTable = []
            // 重新生成课表
            this.setTimeTable()
        },
        onClassTimerSelect(value) { // 每课时长设置
            // 判断两次选的时间是否一致
            if(this.form.singleClassMinutes == value[0]) {
                return
            }
            this.form.singleClassMinutes = value[0]
            this.statusList.classTimerStatus = false
            // 计算消耗课时
            this.calcTimer()

            // 重置课表和课时安排
            this.scheduleList = [] // 课时安排
            this.timeTable = [] // 生成的课表
        },
        onStudentSelect(value) { // 每班人数
            this.form.studentNum = value.name
            this.statusList.studentNumStatus = false
        },
        onCurrentConfirm(value) { // 排课开始时间
            let selectDate = new Date(value)
            let tempMonth = selectDate.getMonth() + 1 >= 10 ? selectDate.getMonth() + 1 : '0' + (selectDate.getMonth() + 1)
            let tempDay = selectDate.getDate() >= 10 ? selectDate.getDate() : '0' + selectDate.getDate()
            this.form.courseStart = selectDate.getFullYear() + '-' + tempMonth + '-' + tempDay
            this.formName.courseStart = selectDate.getFullYear() + '-' + tempMonth + '-' + tempDay + ' ' + this.getWeekStr(selectDate.getDay())
            this.dataForm.status = false
        },
        onCourseShedule() { // 课时安排
            if(!this.form.singleClassMinutes) {
                this.$toast('请选择每课时长')
                return
            }
            if(!this.form.courseCount) {
                this.$toast('请选择排课数')
                return
            }
            if(!this.form.courseStart) {
                this.$toast('请选择排课开始时间')
                return
            }
            if(this.scheduleList.length >= this.form.courseCount) {
                this.$toast('循环周期次数不能大于排课数量')
                return
            }

            this.courseForm.teachingStatus = true
        },
        onScheduleRemove(item) { // 删除课程安排
            let index = this.scheduleList.indexOf(item)
            if(index !== -1) {
                this.scheduleList.splice(index, 1)
            }
        },
        onTeachinConfirm(value) { // 添加课程
            let scheduleList = this.scheduleList
            let startTime = (value[1] >= 10 ? value[1] : '0' + value[1]) + ':' + value[2].split('分')[0]
            let endTime = this.MinutesTest(value[1], value[2], this.form.singleClassMinutes)

            let isAdd = true
            scheduleList.forEach(item => {
                let isStartTime = this.timeIsrange(startTime, endTime, item.startTime);
                let isEndTime = this.timeIsrange(startTime, endTime, item.endTime);
                if(isAdd) { // 
                   if(value[0] == item.weekStr) {
                        if(isStartTime || isEndTime) {
                            isAdd = false
                        } else {
                            isAdd = true
                        }
                    } else if(value[0] != item.weekStr) {
                        isAdd = true
                    } 
                }
            })

            if(isAdd) { // 判断时间范围是否有重复
                scheduleList.push({
                    weekStr: value[0],
                    weekIndex: this.getWeek(value[0]),
                    startTime: startTime,
                    endTime: endTime,
                    id: Date.now()
                })

                this.courseForm.teachingStatus = false

                // this.setTimeTable()
            } else {
                this.$toast('该时间段已排课请重选时间')
                return
            }
        },
        calcTimer() { // 计算课时
            let form = this.form
            // ...
            if(!form.singleClassMinutes || !form.courseCount) {
                return
            }
            let countMinutes = form.singleClassMinutes * form.courseCount
            this.consumePeriod = countMinutes
            this.consumePeriodText = calcMinute(countMinutes)
        },
        onShowTimeTable() { // 显示排课列表
            this.statusList.classTime = true
            this.setTimeTable()
        },
        setTimeTable () {
            // 重置排课列表
            this.timeTable = []

            let form = this.form,
                scheduleList = this.scheduleList
            // 判断是否有课程安排
            if (scheduleList.length <= 0) {
                return
            }
            // debugger
            let totalCount = this.form.courseCount
            let tempCourseStart = form.courseStart.replace(/-/ig, '/')
            let dateOperation  = new Date(tempCourseStart)
            let forMark = 0
            while(totalCount && totalCount > 0) {
                for(let i = 0; i < scheduleList.length; i++) {
                    let num = scheduleList[i].weekIndex - dateOperation.getDay()
                    if(forMark > 0 && num == 0 && i == 0) {
                        num = num + 7
                    }
                    if(num < 0) { // 如果为负数则为下周
                        num = num + 7
                    } 
                    let dataStr = this.getThinkDate(dateOperation, num)

                    // 判断是否大于当前时间
                    let nowGetTime = new Date().getTime()
                    let courseTime = new Date(dataStr.replace(/-/ig, '/') + ' ' + scheduleList[i].startTime + ':00').getTime()
                    if(nowGetTime < courseTime) {
                        let tempArr = {
                            'classDate': dataStr,
                            'startClassTimeStr': scheduleList[i].startTime,
                            "endClassTimeStr": scheduleList[i].endTime
                        }
                        this.timeTable.push(tempArr)
                        totalCount--
                    }
                    if(totalCount <= 0) {
                        return
                    }
                }
                // 加一周
                if(scheduleList.length == 1) {
                    dateOperation.setDate(dateOperation.getDate() + 7)
                } else if(scheduleList.every( item => item.weekStr === scheduleList[0].weekStr)) {
                    // 标记循环次数(标记判断课程安排是不是同一天)
                    forMark++
                }
            }
        },
        getThinkDate (date, num) {
            let Stamp = date
            Stamp.setDate(date.getDate() + num) // 获取当前月数的第几天
            var year = Stamp.getFullYear(); //获取完整的年份(4位,1970-????)
            var month = Stamp.getMonth() + 1; //获取当前月份(0-11,0代表1月)
            var mvar = '';
            if (month < 10) {
                mvar = '0' + month;
            } else {
                mvar = month + '';
            }
            var day = Stamp.getDate();
            var dvar = '';
            if (day < 10) {
                dvar = '0' + day;
            } else {
                dvar = day + '';
            }
            return year + "-" + mvar + '-' + dvar;
        },
        // 分钟小时相加减
        MinutesTest (houer, mins, interval) {
            let min = mins.split('分')[0]
            let sdate1 = new Date(1900, 1, 1, houer, min)
            sdate1.setMinutes(sdate1.getMinutes() + parseInt(interval))
            let H = sdate1.getHours()
            let M = sdate1.getMinutes()
            if (H < 10) H = '0' + H
            if (M < 10) M = '0' + M
            return H + ':' + M
        },
        // 判断时间是否在时间段内
        timeIsrange (beginTime, endTime, nowTime) {
            var strb = beginTime.split(":");
            if (strb.length != 2) {
                return false;
            }
            var stre = endTime.split(":");
            if (stre.length != 2) {
                return false;
            }
            var strn = nowTime.split(":");
            if (stre.length != 2) {
                return false;
            }
            var b = new Date();
            var e = new Date();
            var n = new Date();
            b.setHours(strb[0]);
            b.setMinutes(strb[1]);
            e.setHours(stre[0]);
            e.setMinutes(stre[1]);
            n.setHours(strn[0]);
            n.setMinutes(strn[1]);

            if (n.getTime() - b.getTime() >= 0 && n.getTime() - e.getTime() <= 0) {
                // 在时间范围内
                return true
            } else {
                // 不在时间范围内
                return false
            }
        },
        getWeek(str) { // 获取周几索引值
            let template = {
                '周一': 1,
                '周二': 2,
                '周三': 3,
                '周四': 4,
                '周五': 5,
                '周六': 6,
                '周日': 0
            }
            return template[str]
        },
        getWeekStr(str) { // 获取周几索引值
            let template = {
                1: '周一',
                2: '周二',
                3: '周三',
                4: '周四',
                5: '周五',
                6: '周六',
                0: '周日'
            }
            return template[str]
        },
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            } else if (type === 'month') {
                return `${value}月`
            } else if (type === 'day') {
                return `${value}日`
            }
            return value;
        },
        onSubmit() {
            let form = this.form
            let statusList = this.statusList
            // 排课
            this.setTimeTable()

            if(!(form.name)) {
                this.$toast('请输入课程班名称')
                return false
            }
            if(!form.subjectIdList) {
                this.$toast('请选择科目')
                return false
            }
            
            if(!form.singleClassMinutes) {
                this.$toast('请选择每课时长')
                return false
            }

            if(this.scheduleList.length <= 0) {
                this.$toast('课时安排不能为空')
                return false
            }

            let courseTime = []
            this.scheduleList.forEach(item => {
                courseTime.push({
                    dayOfWeek: item.weekIndex == 0 ? 7 : item.weekIndex,
                    startClassTime: item.startTime + ':00'
                })
            })

            // 判断剩余时长是否足够
            if(this.consumePeriod > this.usePeriod) {
                this.$dialog.confirm({
                    message: '余额不足，请充值。',
                    confirmButtonText: '充值'
                }).then(() => {
                    let params = {
                        form: form,
                        scheduleList: this.scheduleList,
                        formName: this.formName,
                        consumePeriod: this.consumePeriod, // 消耗课时
                        consumePeriodText: this.consumePeriodText,
                    }
                    localStorage.setItem('courseApply', JSON.stringify(params))
                    // 跳转充值页面
                    this.$router.push('/periodExchange')
                }).catch(() => {
                    // on cancel
                })
                return
            }

            let params = {
                coursesGroup: {
                    name: form.name,
                    subjectId: form.subjectIdList,
                    maxStudentNum: form.studentNum
                },
                courseCycleInfo: {
                    courseCreateStartTime: form.courseStart,
                    teachMode: 'ONLINE',
                    courseCount: Number(form.courseCount),
                    singleClassMinutes: form.singleClassMinutes,
                    courseTimes: courseTime
                }
            }
            if(!this.onSubmitStatus) {
                return
            }
            this.onSubmitStatus = false
            this.$dialog.confirm({
                title: '确认创建',
                message: '确认创建课程组？'
            }).then(() => {
                this.$toast.loading({
                    duration: 0,
                    message: '加载中...',
                    forbidClick: true,
                    loadingType: 'spinner'
                })
                createCourseGroup(params).then(res => {
                    let result =res.data
                    this.$toast.clear()
                    if(result.code == 200) {
                        this.$toast('创建成功')
                        setTimeout(() => {
                            this.onSubmitStatus = true
                            if(browser().iPhone) {
                                window.webkit.messageHandlers.DAYA.postMessage(JSON.stringify({api: 'back'}))
                            } else if(browser().android) {
                                DAYA.postMessage(JSON.stringify({api: 'back'}))
                            }
                            //  else {
                            //     this.$router.push('/business')
                            // }
                        }, 500)
                    } else if(result.code == 302) {
                        this.onSubmitStatus = true
                        this.$dialog.alert({
                            title: '课程冲突',
                            message: result.msg,
                            messageAlign: 'left'
                        }).then(() => {
                        // on close
                        });
                    } else {
                        this.onSubmitStatus = true
                        this.$toast(result.msg)
                    }
                })
            }).catch(() => {
                // on cancel
                this.onSubmitStatus = true
            })
            
        }
    }
}
</script>
<style lang='less' scoped>
@import url("../../assets/commonLess/variable.less");
.courseApply {
    min-height: 100vh;
}
.vip-title {
    padding: .06rem .14rem .04rem;
    font-size: .14rem;
    color: #808080;

}

.add-plan {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: .2rem 0;
    font-size: .16rem;
    color: @tFontColor;
    .van-icon {
        margin-right: .05rem;
        font-size: .20rem;
    }
    p {
        display: flex;
        align-items: center;
    }
}

.title-time {
    display: flex;
    align-items: center;
    flex: 1 auto;
    color: #4A4A4A;
    .online {
        color: @tFontColor;
    }
    .week {
        padding-right: .15rem;
    }
}
/deep/.van-cell-group {
    margin-bottom: .15rem;
}

/deep/.van-field__label, /deep/.van-cell__value {
    flex: 1 auto;
    font-size: .16rem;
}
/deep/.van-field__control {
    &:disabled {
        color: #6a6969;
    }
}

.button-group {
    margin: .2rem .26rem;
    .van-button--primary {
        background: @mColor;
        font-size: .18rem;
    }
}

.van-row {
    line-height: .4rem;
    border-top: 1px solid #edeef0;
    text-align: center;
    font-size: .14rem;
    &:first-child {
        border-top: 0;
        background: #edeef0;
        color: #444;
        font-size: .15rem;
    }
}
.tableContainer {
    max-height: 2.44rem;
    overflow: auto;
    .van-row {
        color: #444;
        &:first-child {
            border-top: 0;
            background: #fff;
            font-size: .14rem;
        }
    }
}

.agreeProtocol {
    font-size: .14rem;
    display: flex;
    align-items: center;
    color: #333333;
    padding: .05rem .16rem;
    .van-checkbox {
        padding-right: .08rem;
        
    }
    /deep/.van-checkbox__icon .van-icon {
        // border-color: #14928A;
        background: #fff;
    }
    /deep/.van-checkbox__icon--checked .van-icon {
        color: #fff;
        background-color: #F85043;
        border-color: #F85043;
    }
    span {
        color: #14928A;
    }
}
</style>