<template>
    <div class="program">
        <van-cell-group class="van-cell-group--inset">
            <van-cell :title="vipGroup.name" class="titleContent" title-class="titleStyle" label-class="labelStyle">
                <template #label>
                    <p>{{ vipGroup.description }}</p>
                    <!-- <p>排课时间范围：{{ vipGroup.coursesStartTime }} 至 {{ vipGroup.coursesEndTime }}</p> -->
                </template>
            </van-cell>
        </van-cell-group>

        <h2 class="van-block__title">{{ typeStatus ? '付费' : '赠送' }}课程排课</h2>
        <van-cell-group>
            <van-field
                :value="typeStatus ? courseType[vipGroup.courseType] : courseType[vipGroup.giveCourseType]"
                label="课程类型"
                :readonly="true"
                input-align="right"
                size="large"
                placeholder="请选择"
            />
            <van-field
                :value="typeStatus ? vipGroup.vipGroupCategoryNames : vipGroup.giveCategoryName"
                label="课程形式"
                v-if="courseTypeIsVip"
                :readonly="true"
                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-field
                v-model="formName.educationalTeacherName"
                @click="onGetSheetList('teacherList')"
                label="乐团主管"
                :readonly="true"
                input-align="right"
                is-link
                size="large"
                placeholder="请选择"
            />
        </van-cell-group>

        <template v-if="studentList.length > 0">
            <h2 class="van-block__title">上课学员</h2>
            <van-cell-group>
                <van-cell title-style="flex: 1 auto; color: #1A1A1A;" size="large" v-for="(item, index) in studentList" :key="index">
                    <template #title>
                        {{ item.username }} - {{ item.phone }}
                    </template>
                    <template #default>
                        <span @click="onDelete('student', item)"><van-icon name="delete-o" size=".14rem" /> <span style="font-size: .12rem;">删除</span></span>
                    </template>
                </van-cell>
            </van-cell-group>
        </template>
        <div class="addButton" @click="studentStatus = true">
            <van-icon name="plus" /> 添加学员
        </div>

        <h2 class="van-block__title">课时组成</h2>
        <van-cell-group>
            <van-field
                v-if="statusList.hasOnline && teachMode == -1"
                v-model="form.onlineClassesNums"
                @keyup="onClassKeyUp"
                label="线上课次数"
                input-align="right"
                size="large"
                placeholder="请输入次数"
                type="number"
            />
            <van-field
                v-if="statusList.hasOffline && teachMode == -1"
                v-model="form.offlineClassesNums"
                @keyup="onClassKeyUp('offLine')"
                label="线下课次数"
                input-align="right"
                size="large"
                placeholder="请输入次数"
                type="number"
            />
            <van-field
                v-if="tempOfflineNum > 0"
                v-model="formName.teacherSchoolName"
                @click="onGetSheetList('teacherSchool')"
                label="线下课地址"
                :readonly="true"
                input-align="right"
                is-link
                size="large"
                placeholder="请选择"
            />
            <!-- 不影响判断逻辑 -->
            <van-field
                v-if="isMusicTheory"
                :value="'1-' + (form.studentNum || 0) + '人'"
                label="班级人数"
                :readonly="true"
                input-align="right"
                size="large"
            />
            <van-field
                v-else
                :value="(form.studentNum || 0) + '人'"
                label="班级人数"
                :readonly="true"
                input-align="right"
                size="large"
            />
            <van-field
                :value="(form.singleClassMinutes || 0) + '分钟'"
                label="单课时时长"
                :readonly="true"
                input-align="right"
                size="large"
            />
        </van-cell-group>

        <h2 class="van-block__title">课时安排</h2>
        <van-cell-group>
            <van-cell
                title="最早排课时间"
                :readonly="true"
                v-if="vipGroup.coursesStartTime"
                input-align="right"
                size="large"
                value-class="showText"
                :value="vipGroup.coursesStartTime"
            >
            </van-cell>
            <van-cell
                title="最晚排课时间"
                :readonly="true"
                v-if="vipGroup.coursesEndTime"
                input-align="right"
                size="large"
                value-class="showText"
                :value="vipGroup.coursesEndTime"
            >
            </van-cell>
            <!-- 为了处理，付费网管课程 -->
            <!-- {{ !courseTypeIsVip && isLimitNum && typeStatus ? false : true }} -->
            <van-field
                v-model="form.totalClassTime"
                label="课时总数"
                :readonly="!courseTypeIsVip && !isLimitNum && typeStatus ? false : true"
                input-align="right"
                size="large"
                placeholder="请输入排课课时数"
            >
                <template #extra v-if="form.totalClassTime">
                    <span style="color: #808080; font-size: 16px;">课时</span>
                </template>
            </van-field>
            <van-field
                v-model="form.courseStart"
                label="排课开始时间"
                :readonly="true"
                input-align="right"
                is-link
                size="large"
                placeholder="请选择"
                @click="dataForm.status = true"
            />
        </van-cell-group>

        <van-cell-group :border="false" style="margin-top: .1rem">
            <van-cell
                title-class="title-time"
                v-for="(item, index) in scheduleList"
                :key="index"
            >
                <template slot="title">
                    <span class="online">{{ item.type }}</span>
                    <span class="week">{{ item.weekStr }}</span>
                    <span class="timer">{{ item.startTime + "~" + item.endTime }}</span>
                </template>
                <template slot="default">
                    <span @click="onDelete('class', item)"><van-icon name="delete-o" size=".14rem" /> <span style="font-size: .12rem;">删除</span></span>
                </template>
            </van-cell>
        </van-cell-group>
        <div class="addButton" @click="teachingStatus = true">
            <van-icon name="plus" /> 添加课时安排
        </div>

        <van-cell-group>
            <van-field
                label="排课列表"
                v-if="scheduleList.length > 0"
                disabled
                input-align="right"
                @click="onShowTimeTable"
                is-link
                size="large"
            />
        </van-cell-group>

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

        <!-- 选择上课学员 -->
        <van-popup
            v-model="studentStatus"
            :lock-scroll="true"
            position="bottom"
            :style="{ height: '5.16rem','overflow': 'hidden' }"
            class="studentChose"
        >
            <student-list
                @close="studentStatus = false"
                :studentList="studentList"
                :activityId="activityId"
                :studentNum="form.studentNum"
                :courseTypeIsVip="courseTypeIsVip"
                :typeStatus="typeStatus"
                :isMusicTheory="isMusicTheory"
                @submit="onSelectStudent" />
        </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="teachingStatus" position="bottom">
            <course-modal :scheduleList="scheduleList" :singleClassMinutes="form.singleClassMinutes" @close="teachingStatus = false" />
        </van-popup>

        <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="statusList.classTime" position="bottom" >
            <van-row>
                <van-col span="12">上课类型</van-col>
                <van-col span="12">上课时间</van-col>
            </van-row>
            <div class="tableContainer">
                <van-row v-for="(item, index) in timeTable" :key="index">
                <van-col span="12">
                    {{ item.teachMode == "ONLINE" ? "线上" : "线下" }}
                </van-col>
                <van-col span="12">
                    {{ item.classDate }} {{ item.startClassTimeStr }}
                </van-col>
                </van-row>
            </div>
        </van-popup>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import studentList from './modal/studentList'
import courseModal from './modal/course'
import { courseType } from '../../constant'
import { getActivityWaitCourseStudentNum, createVipGroup, createPracticeGroup } from './api'
import { findSubSubjects, findEducationUsers, findVipSchoolByTeacher2 } from "@/api/teacher";
export default {
    components: { studentList, courseModal },
    data() {
        const query = this.$route.query
        return {
            courseType,
            type: query.type,
            activityId: query.activityId,
            vipDetail: {},
            vipGroup: {},
            studentStatus: false,
            studentList: [],
            checkboxSelectIds: [],
            teachMode: null, // -1：所有；0：线上；1：线下"
            sheetForm: {
                // 上拉弹窗
                currentType: null, // 当前选择的类型
                sheetStatus: false,
                loading: true, // 加载数据
                index: 0, // 选中的索引值
                columns: [],
            },
            timeTable: [], // 生成的课表
            loadData: {
                // 下拉加载数据
                subjectList: [], // 声部列表
                teacherList: [],
                teacherSchool: [], // 线下课地址
            },
            tempOfflineNum: 0, // 临时存放线下课次数
            form: {
                vipGroupCategoryId: null,
                subjectIdList: null,
                educationalTeacherId: null,
                singleClassMinutes: null,
                onlineClassesNums: null,
                offlineClassesNums: null,
                totalClassTime: null, // 总课时数
                studentNum: null, // 每班人数
                courseStart: null, // 排课开始时间
                teacherSchoolId: null,
                vipGroupActivityId: query.activityId,
            },
            formName: {
                vipGroupCategoryId: null,
                subjectListName: null,
                subjectListIndex: 0, // 声部名称
                educationalTeacherName: null, // 乐团主管
                educationalTeacherIndex: 0,
                teacherSchoolName: null,
                teacherSchoolIndex: 0, // 线下课地址
            },
            statusList: {
                hasOnline: false, // 是否显示线上
                hasOffline: false, // 是否显示线下
                classTime: false, // 查看排课列表
            },
            scheduleList: [],
            // 排课弹窗
            teachingStatus: false, // 课时安排状态
            dataForm: {
                // 时间下拉框
                status: false,
                minDate: new Date(),
                maxDate: new Date(2035, 10, 1),
                currentDate: new Date(),
            },
            isMusicTheory: false,
        }
    },
    computed: {
        typeStatus() { // 是否是付费课程
            return this.type == 'pay' ? true : false
        },
        courseTypeIsVip() { // 目前只有两种课程，VIP 网管课，则可以这样判断
            const type = this.typeStatus ? this.vipGroup.courseType : this.vipGroup.giveCourseType
            return type == 'VIP' ? true : false
        },
        isLimitNum() { // 是否限制排课
            return this.vipGroup.minCourseNum > 0 ? true : false
        }
    },
    mounted() {
        this.__init()
    },
    methods: {
        async __init() {
            try {
                let res = await getActivityWaitCourseStudentNum({ activityId: this.activityId })
                this.vipDetail = res.data
                let vipGroup = res.data.vipGroupActivity
                vipGroup.coursesStartTime = vipGroup.coursesStartTime ? dayjs(vipGroup.coursesStartTime).format('YYYY-MM-DD') : null
                vipGroup.coursesEndTime = vipGroup.coursesEndTime ? dayjs(vipGroup.coursesEndTime).format('YYYY-MM-DD') : null
                this.vipGroup = vipGroup
                let form = this.form
                // 课程形式
                form.vipGroupCategoryId = this.typeStatus ? vipGroup.vipGroupCategoryIdList : vipGroup.giveCategoryId
                // 单课时长
                form.singleClassMinutes = this.typeStatus ? vipGroup.singleCourseTime : vipGroup.giveSingleCourseTime

                const name = this.typeStatus ? vipGroup.vipGroupCategoryNames : vipGroup.giveCategoryName
                this.isMusicTheory = name === '小组课'

                if(this.courseTypeIsVip) {
                    // 每班人数
                    form.studentNum = this.typeStatus ? vipGroup.vipGroupCategoryNum : vipGroup.giveCategoryNum
                    this.statusList.hasOnline = this.typeStatus ? this.formatStatus('online', vipGroup.teachMode) : this.formatStatus('online', vipGroup.giveTeachMode)
                    this.statusList.hasOffline = this.typeStatus ? this.formatStatus('offline', vipGroup.teachMode) : this.formatStatus('offline', vipGroup.giveTeachMode)
                } else {
                    form.totalClassTime = null
                    form.studentNum = 1
                    this.statusList.hasOnLine = false
                    this.statusList.hasOffLine = false
                }

                if(this.isLimitNum || !this.typeStatus) { // 是否限制了排课
                    // 排课次数，活动排课没有范围一说，最大次数和最小次数必须一致
                    form.totalClassTime = this.typeStatus ? vipGroup.minCourseNum : vipGroup.giveCourseNum
                }

                // 如果
                if(this.teachMode == 0) {
                    form.onlineClassesNums = form.totalClassTime || 0
                    form.offlineClassesNums = 0
                } else if(this.teachMode == 1) {
                    form.onlineClassesNums = 0
                    form.offlineClassesNums = form.totalClassTime || 0
                    this.tempOfflineNum = form.totalClassTime || 0
                }
            } catch {
                //
            }
        },
        onGetSheetList(name) {
            // 获取科目列表
            let sheetForm = this.sheetForm;
            sheetForm.columns = [];
            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") {
                // 声部列表
                findSubSubjects().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;
                }
                });
            } else if (sheetForm.currentType == "teacherSchool") {
                // 教师教学点
                findVipSchoolByTeacher2().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.teacherSchool = tempArr;
                        sheetForm.columns = tempArr;
                        sheetForm.loading = false;
                    } else {
                        this.$toast("暂无教学点");
                        sheetForm.loading = false;
                    }
                });
            } else if (sheetForm.currentType == "teacherList") {
                // 乐团主管
                findEducationUsers().then((res) => {
                    let result = res.data;
                    const EDUCATION = result.data.EDUCATION || [];
                    if (result.code == 200 && EDUCATION.length > 0) {
                        let tempArr = [];
                        EDUCATION.forEach((item) => {
                            item.value = item.userId;
                            item.text = item.userName;
                            tempArr.push(item);
                        });
                        this.loadData.teacherList = 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
            if (sheetForm.currentType == "subjectList") {
                // 科目名称赋值
                form.subjectIdList = value.value;
                formName.subjectListName = value.text;
                formName.subjectListIndex = index;
            } else if (sheetForm.currentType == "teacherSchool") {
                // 线下课地址
                form.teacherSchoolId = value.value;
                formName.teacherSchoolName = value.text;
                formName.teacherSchoolIndex = index;
            } else if (sheetForm.currentType == "teacherList") {
                // 乐团主管
                form.educationalTeacherId = value.value;
                formName.educationalTeacherName = value.text;
                formName.educationalTeacherIndex = index;
            }

            sheetForm.sheetStatus = false;
        },
        async onSubmit() {
            // 次数限制是否可以继续创建
            let form = this.form;
            let statusList = this.statusList;

            if (!form.subjectIdList) {
                this.$toast("请选择排课声部");
                return false;
            }
            if (!form.educationalTeacherId) {
                this.$toast("请选择乐团主管");
                return;
            }
            if (this.checkboxSelectIds.length <= 0) {
                this.$toast("请选择上课学员");
                return;
            }

            if (this.isMusicTheory) {
                if (!(this.checkboxSelectIds.length >= 1 && this.checkboxSelectIds.length <= this.form.studentNum)) {
                    this.$toast(`请选择1-${this.form.studentNum}名学生，当前选择${this.checkboxSelectIds.length}名`);
                    return;
                }
            } else {
                if (this.checkboxSelectIds.length != this.form.studentNum) {
                    this.$toast(`请选择学生${this.form.studentNum}名，当前选择${this.checkboxSelectIds.length}名`);
                    return;
                }
            }
            let onlineNums = form.onlineClassesNums || 0
            if(form.onlineClassesNums && form.onlineClassesNums.length > 0) {
                onlineNums = Number(form.onlineClassesNums)
            }
            let offlineNums = form.offlineClassesNums || 0
            if(form.offlineClassesNums && form.offlineClassesNums.length > 0) {
                offlineNums = Number(form.offlineClassesNums)
            }
            let onlineClassesStatus = onlineNums === "" ? true : false;
            let offlineClassesStatus = offlineNums === "" ? true : false;
            if (statusList.hasOnline && onlineClassesStatus) {
                this.$toast("请输入线上课次数");
                return false;
            }
            if (statusList.hasOffline) {
                if (offlineClassesStatus) {
                    this.$toast("请输入线下课次数");
                    return false;
                }

                // 判断是否有线下
                if (form.offlineClassesNums > 0 && !form.teacherSchoolId) {
                    this.$toast("请选择线下课地址");
                    return false;
                }
            }

            if (
                statusList.hasOffline &&
                statusList.hasOnline &&
                parseFloat(form.onlineClassesNums || 0) + parseFloat(form.offlineClassesNums || 0) != this.form.totalClassTime
            ) {
                this.$toast('线上课次数+线下课次数不等于总课次数')
                return
            }
            if (!this.checkCourseList()) {
                return;
            }
            if (this.scheduleList.length <= 0) {
                this.$toast("课时安排不能为空");
                return false;
            }
            // 排课
            const checkmMsg = this.checkTimeTable()
            if (checkmMsg) {
                this.$toast(checkmMsg)
                return
            }
            this.setTimeTable();

            form.studentIdList = this.checkboxSelectIds.join(",");

            form.firstStudentId = this.studentList.length > 0 ? this.studentList[0].userId : null;
            form.onlineClassesNum = Number(form.onlineClassesNums || 0);
            form.offlineClassesNum = Number(form.offlineClassesNums || 0);
            let params = {
                courseSchedules: this.timeTable
            }
            // return
            if(this.courseTypeIsVip) {
                params.vipGroupApplyBaseInfo = form
                params.giveFlag = !this.typeStatus
                await this.onPayVip(params)
            } else {
                params.practiceGroupApplyBaseInfoDto = form
                params.practiceGroupApplyBaseInfoDto.studentId = form.studentIdList
                params.practiceGroupApplyBaseInfoDto.allCourseNum = form.totalClassTime
                params.practiceGroupApplyBaseInfoDto.subjectId = form.subjectIdList
                params.giveFlag = !this.typeStatus
                await this.onPayPractice(params)
            }
        },
        async onPayVip(params) {
            try {
                await createVipGroup(params)
                this.$toast("排课成功");
                setTimeout(() => {
                    this.$router.back()
                }, 1000);
            } catch {
                //
            }
        },
        async onPayPractice(params) {
            try {
                await createPracticeGroup(params)
                this.$toast("排课成功");
                setTimeout(() => {
                    this.$router.back()
                }, 1000);
            } catch {
                //
            }
        },
        onSelectStudent(items) {
            // 选中的数据
            const tempItems = items || []
            this.studentList = tempItems
            // if(tempItems.length <= 0) { // 判断是否有选择学员
                this.checkboxSelectIds = []
            // }
            tempItems.forEach(item => {
                this.checkboxSelectIds.push(item.userId)
            })
            this.studentStatus = false
        },
        onDelete(type, item) {
            if(type == 'student') {
                // 删除上课学员
                this.$dialog.confirm({
                    title: '提示',
                    message: '是否删除该学员？',
                    confirmButtonText: '确定',
                    confirmButtonColor: '#269a93',
                    cancelButtonText: '取消'
                }).then(() => {
                    let index = this.studentList.indexOf(item);
                    if (index !== -1) {
                        this.studentList.splice(index, 1);
                        this.checkboxSelectIds.splice(index, 1);
                    }
                })
            } else if(type == 'class') {
                // 删除上课学员
                this.$dialog.confirm({
                    title: '提示',
                    message: '是否删除该课时安排？',
                    confirmButtonText: '确定',
                    confirmButtonColor: '#269a93',
                    cancelButtonText: '取消'
                }).then(() => {
                    let index = this.scheduleList.indexOf(item);
                    if (index !== -1) {
                        this.scheduleList.splice(index, 1);
                    }
                })
            }
        },
        onCurrentConfirm(value) {
            // 排课开始时间
            this.form.courseStart = dayjs(value).format('YYYY-MM-DD')
            this.dataForm.status = false;
        },
        onClassKeyUp(type) {
            // 线上课&线下课修改时
            if(this.teachMode != -1) return
            let form = this.form
            let onlineNum = form.onlineClassesNums
            let offLineNum = form.offlineClassesNums
            // 重置次数，不能
            if(parseInt(onlineNum || 0) + parseInt(offLineNum || 0) >= form.totalClassTime) {
                if(type == 'offLine') {
                    let diffNum = form.totalClassTime - parseInt(onlineNum || 0)
                    offLineNum = diffNum < 0 ? 0 : diffNum
                } else {
                    let diffNum = form.totalClassTime - parseInt(offLineNum || 0)
                    onlineNum = diffNum < 0 ? 0 : diffNum
                }
            }
            this.form.onlineClassesNums = onlineNum
            this.form.offlineClassesNums = offLineNum
            this.tempOfflineNum = offLineNum || 0
        },
        onShowTimeTable() {
            // 显示排课列表
            if (!this.checkCourseList()) {
                return;
            }

            const checkmMsg = this.checkTimeTable()
            if (checkmMsg) {
                this.$toast(checkmMsg)
                return
            }
            this.statusList.classTime = true;
            this.setTimeTable();
        },
        checkTimeTable() {
            let form = this.form,
                scheduleList = this.scheduleList;
            let online = parseInt(
                form.onlineClassesNums ? form.onlineClassesNums : 0
            );
            let offline = parseInt(
                form.offlineClassesNums ? form.offlineClassesNums : 0
            );
            // 网管课默认只有线上课次
            if(!this.courseTypeIsVip) {
                online = parseInt(form.totalClassTime || 0)
            }
            // let totalCount = Number(online) + Number(offline)
            let hasOnlineSchedule = false,
                hasOfflineSchedule = false

            for (let i = 0; i < scheduleList.length; i++) {
                const item = scheduleList[i];
                if (item.type == '线上') {
                    hasOnlineSchedule = true;
                }
                if (item.type == '线下') {
                    hasOfflineSchedule = true;
                }
                if (hasOnlineSchedule && hasOfflineSchedule) {
                    break;
                }
            }
            if (online > 0 && !hasOnlineSchedule) {
                return '请添加线上课时安排';
            }
            if (offline > 0 && !hasOfflineSchedule) {
                return '请添加线下课时安排';
            }
            console.log({...form}, online, offline, hasOnlineSchedule, hasOfflineSchedule)
        },
        setTimeTable() {
            if (!this.checkCourseList(false)) {
                return;
            }
            // 重置排课列表
            this.timeTable = [];

            let form = this.form,
                scheduleList = this.scheduleList;

            // 拿到线上课数与线下课数 以及
            let online = parseInt(
                form.onlineClassesNums ? form.onlineClassesNums : 0
            );
            let offline = parseInt(
                form.offlineClassesNums ? form.offlineClassesNums : 0
            );
            // 网管课默认只有线上课次
            if(!this.courseTypeIsVip) {
                online = parseInt(form.totalClassTime || 0)
            }
            // 判断是否有课程安排
            if (scheduleList.length <= 0) {
                return;
            }
            let totalCount = Number(online) + Number(offline);
            let tempCourseStart = form.courseStart.replace(/-/gi, "/");
            let dateOperation = new Date(tempCourseStart);
            let forMark = 0;
            while (totalCount && totalCount > 0) {
                for (let i = 0; i < scheduleList.length; i++) {
                    if (online == 0 && offline == 0) break;
                    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(/-/gi, "/") +" " + scheduleList[i].startTime + ":00").getTime();
                    if (nowGetTime < courseTime) {
                        let tempArr = {
                            classDate: dataStr,
                            startClassTimeStr: scheduleList[i].startTime,
                            endClassTimeStr: scheduleList[i].endTime,
                        };
                        if (scheduleList[i].type == "线上" && online > 0) {
                            tempArr.teachMode = "ONLINE";
                            this.timeTable.push(tempArr);
                            online--;

                            totalCount--;
                        } else if (scheduleList[i].type == "线下" && offline > 0) {
                            tempArr.teachMode = "OFFLINE";
                            this.timeTable.push(tempArr);
                            offline--;

                            totalCount--;
                        }
                    }
                }
                // 加一周
                if (scheduleList.length == 1) {
                    dateOperation.setDate(dateOperation.getDate() + 7);
                } else if (
                    scheduleList.every((item) => item.weekStr === scheduleList[0].weekStr)
                ) {
                    // 标记循环次数(标记判断课程安排是不是同一天)
                    forMark++;
                }
            }

            this.timeTable.sort((a, b) => {
                let aStr = dayjs(dayjs(a.classDate).format("YYYY-MM-DD") + " " + a.startClassTimeStr + ":00").valueOf();
                let bStr = dayjs(dayjs(b.classDate).format("YYYY-MM-DD") + " " + b.startClassTimeStr + ":00").valueOf();
                return aStr - bStr;
            });
        },
        getThinkDate(date, num) {
            let Stamp = date;
            Stamp.setDate(date.getDate() + num); // 获取当前月数的第几天
            return dayjs(Stamp).format('YYYY-MM-DD')
        },
        checkCourseList(isShowToast = true) {
            let form = this.form;
            let scheduleList = this.scheduleList || [];
            let hasOnLine = false; // 是否有线上课时安排
            let hasOffLine = false;
            scheduleList.forEach((item) => {
                if (item.type == "线上") {
                    hasOnLine = true;
                }
                if (item.type == "线下") {
                    hasOffLine = true;
                }
            });
            let statusList = this.statusList;
            let onlineClassesStatus = !form.onlineClassesNums && form.onlineClassesNums <= 0 ? true : false;
            let offlineClassesStatus = !form.offlineClassesNums && form.offlineClassesNums <= 0 ? true : false;
            if (statusList.hasOnline) {
                if (onlineClassesStatus) {
                    if (isShowToast) {
                        this.$toast("请输入线上课次数");
                    }
                    return false;
                }
                if (!onlineClassesStatus && !hasOnLine && form.onlineClassesNums > 0) {
                    if (isShowToast) {
                        this.$toast("课时安排缺少线上课类型");
                    }
                    return false;
                }
            }
            if (statusList.hasOffline && !statusList.hasOnline) {
                if (offlineClassesStatus) {
                    if (isShowToast) {
                        this.$toast("请输入线下课次数");
                    }
                    return false;
                }
                if (
                !offlineClassesStatus &&
                !hasOffLine &&
                form.offlineClassesNums > 0
                ) {
                    if (isShowToast) {
                        this.$toast("课时安排缺少线下课类型");
                    }
                    return false;
                }
            }
            if (
                statusList.hasOffline &&
                statusList.hasOnline &&
                parseFloat(form.onlineClassesNums || 0) + parseFloat(form.offlineClassesNums || 0) != this.form.totalClassTime
            ) {
                if (isShowToast) {
                    this.$toast('线上次数+线下课次数不等于总课次数')
                }
                return false
            }
            if(!this.form.courseStart) {
                if(isShowToast) {
                    this.$toast('请选择排课开始时间')
                }
                return false
            }
            return true;
        },
        formatStatus(type, teachMode) {
            // -1：所有；0：线上；1：线下
            this.teachMode = teachMode
            if(type == 'online' && teachMode == 0) {
                return true
            } else if(type == 'offline' && teachMode == 1) {
                return true
            } else if(teachMode == -1) {
                return true
            } else {
                return false
            }
        },
        formatter(type, value) {
            if (type === "year") {
                return `${value}年`;
            } else if (type === "month") {
                return `${value}月`;
            } else if (type === "day") {
                return `${value}日`;
            }
            return value;
        },
    }
}
</script>

<style lang="less" scoped>
@import url("../../assets/commonLess/variable.less");
.program {
    background-color: #F5F5F5;
    min-height: 100vh;
    overflow: hidden;
}
.van-cell-group--inset {
    margin: .12rem .12rem 0;
    overflow: hidden;
    border-radius: 8px;
    .titleContent {
        padding: .14rem .16rem;
    }
    .titleStyle {
        font-size: .2rem;
        color: #333333;
        font-size: 500;
    }
    .labelStyle {
        padding-top: .08rem;
        color: #666666;
        font-size: .13rem;
        line-height: .2rem;
    }
}
.van-row {
    line-height: 0.4rem;
    border-top: 1px solid #edeef0;
    text-align: center;
    font-size: 0.14rem;

    &:first-child {
        border-top: 0;
        background: #edeef0;
        color: #444;
        font-size: 0.15rem;
    }
}
.tableContainer {
    max-height: 2.44rem;
    overflow: auto;
    .van-row {
        color: #444;
        &:first-child {
            border-top: 0;
            background: #fff;
            font-size: 0.14rem;
        }
    }
}
.van-block__title {
    padding: .12rem .14rem .06rem;
    color: #808080;
    font-size: .14rem;
    line-height: .2rem;
}
.button-group {
    margin: 0.3rem 0.26rem 0.2rem;

    .van-button--primary {
        background: @mColor;
        border-color: @mColor;
        font-size: 0.18rem;
    }
}
.title-time {
    display: flex;
    align-items: center;
    flex: 1 auto;
    color: #1A1A1A;
    font-size: .16rem;
    .week {
        padding-left: 0.4rem;
        padding-right: 0.15rem;
    }
}
/deep/.studentChose {
    border-radius: .1rem .1rem 0px 0px;
    overflow: auto;
    background: #F5F5F5;
}
/deep/.van-field__label {
    color: #1A1A1A;
}
/deep/.van-field__control, .showText {
    font-size: 16px;
    color: #808080;
}
.addButton {
    margin: .1rem .28rem;
    border: 1px dashed #CFCFCF;
    line-height: .42rem;
    text-align: center;
    background: #FBFBFB;
    color: #666666;
    font-size: .14rem;
    border-radius: .05rem;
}
</style>
