<template>
    <div>
        <!-- 搜索条件表单 -->
        <el-form :model="queryParams" ref="queryParams" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="日期" prop="startTime">
                <el-date-picker size="small" v-model="queryParams.startTime" type="date" placeholder="开始日期"
                    value-format="yyyy-MM-dd" format="yyyy-MM-dd" @change="changeDate" :picker-options="pickerOptions"
                    style="margin-right:10px">
                </el-date-picker>
                <el-date-picker size="small" type="date" v-model="endTime" disabled>
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="studioName" :rules="[{ required: true, message: '请选择录播室', trigger: 'change,blur' }]">
                <el-select @change="changeStudio" v-model="queryParams.studioId" placeholder="录播室">
                    <el-option v-for="item in options" :key="item.id" :label="item.studioName" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <!-- <el-button size="mini" type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
        </el-form>
        <p style="margin: 0 0 0 30px;font-size: 14px">
            说明：（1）录播室每天开放上午四节、下午四节、晚上三节。共计每天11节。（2）请提前一天进行预约。（3）预约不可跨天，跨天请进行多次预约</p>
        <!-- 录播室占用情况表格 -->
        <table style="margin-left: 30px">
            <thead>
                <tr>
                    <!-- 表头 -->
                    <th style="background:none"></th>
                    <!-- 表格表头日期-->
                    <th style="background:none;font-size:16px;font-weight:normal" v-for="day in days" :key="day">{{ day }}
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(timeSlot, index) in timeSlots" :key="index">
                    <td>{{ timeSlot }}</td>
                    <!--          <td v-for="(day, dayIndex) in days" :key="dayIndex" :class="{-->
                    <!--            occupied: isOccupied(day, index),-->
                    <!--            selected: isSelected(day, index),-->
                    <!--          }" @mousedown="handleMouseDown(day, index)" @mouseup="handleMouseUp(day, index)"-->
                    <!--            @mouseenter="handleMouseEnter(day, index)" @click="handleCellClick(day, index)">-->
                    <!--            {{ isOccupied(day, index) ? "占用" : "" }}-->
                    <!--          </td>-->
                    <td v-for="(day, dayIndex) in days" :key="dayIndex" :class="{
                        occupied: isOccupied(day, index),
                        selected: isSelected(day, index),
                    }" @click="handleCellClick(day, index)">
                        {{ isOccupied(day, index) ? "占用" : "" }}
                    </td>
                </tr>
            </tbody>
        </table>


    </div>
</template>

<script>
import {
    getAppointmentList, // 录播室下拉框列表
    addIdle, // 新增录播室预约
    getstudioUse, // 查询录播室使用情况
} from "@/api/smartSchool/personWork/recordingroomAppointment/IdleSituation";
import moment from 'moment'

export default {
    data() {
        return {
            //选择日期限制
            pickerOptions: {
                disabledDate(time) {
                    //包含今天
                    // return time.getTime() < Date.now() - 8.64e7;
                    //不含今天
                    return time.getTime() < Date.now();
                }
            },
            time: '',
            studioUseData: [], // 存储录播室占用情况数据
            showSearch: true, // 是否显示搜索条件
            successDialogVisible: false, // 预约录播室成功的弹窗是否可见
            //弹框表单
            form: {
                studioContent: ''
            },
            days: [], // 存储日期的数组
            timeSlots: [], // 存储时间段的数组
            selectedTimeSlots: [], // 存储已选时间段的数组
            isMouseDown: false, // 鼠标按下标志位
            startSelection: null, // 选中的开始时间段
            endSelection: null, // 选中的结束时间段
            options: "",
            bookingForm: {
                startTime: "", // 录播开始时间
                timeSlots: "", // 预约的时间段
            },
            queryParams: {
                studioId: "", // 录播室名称
                startTime: "", // 查询的开始时间
            },
            //表格占用数据
            occupiedData: [],
            //弹框标记符
            remark: false,
            rooms: [], //录播室下拉列表存储
            endTime: ''
        };
    },
    created() {
        this.queryParams.startTime = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
        this.endTime = moment(this.queryParams.startTime).add(9, 'days')
        // 初始化日期和时间段
        this.initDays();
        this.initTimeSlots();
        // 获取录播室下拉框列表
        this.getRoomList();
        this.fetchStudioUseData();
        // this.fetchData();
    },
    methods: {
        changeDate() {
            this.endTime = moment(this.queryParams.startTime).add(9, 'days')
        },
        changeStudio(value) {
            this.selectedTimeSlots = []; // 在切换录播室时清空已选时间段
            this.queryParams.studioId = value;
            this.fetchStudioUseData();
        },

        fetchStudioUseData() {
            // 调用接口获取录播室占用情况数据
            console.log(123654, this.queryParams);
            getstudioUse(this.queryParams.startTime, this.queryParams.studioId).then((res) => {
                this.studioUseData = res.rows;
                console.log(123, this.studioUseData);
            });
        },
        //表格占用显示
        isOccupied(day, index) {
            // 判断指定的时间段是否被占用
            const occupiedData = this.studioUseData.find((item) => {
                // console.log('Array.from(item.useJc)',item.useJc.split(','))
                // console.log('Array.from(item.useJc)',index + 1)
                return item.useDate === day && item.useJc.split(',').includes((index + 1).toString());
            });
            return occupiedData ? occupiedData.useUserId : false;
        },
        //表格点击选中
        isSelected(day, index) {

            if (this.isOccupied(day, index)) {
                return false
            } else {
                // 检查时间段是否已选中
                return this.selectedTimeSlots.some((selectedSlot) => {
                    // console.log('selectedSlot',selectedSlot)
                    return selectedSlot.day === day && selectedSlot.index === index;
                });
            }
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryParams");
            this.fetchStudioUseData();
        },
        // 表单重置
        reset() {
            this.queryParams = {
                startTime: "",
                studioName: "",

            };
            this.resetForm("queryParams");
        },
        //表格点击事件
        handleCellClick(day, index) {
            console.log('day', day)
            console.log('index', index + 1)
            //占用点击不生效
            if (this.isOccupied(day, index) && this.selectedTimeSlots.length == 0) {
                this.remark = false
                return
            } else if (this.selectedTimeSlots.length == 0) {
                // 处理单元格点击事件，点击第一个
                this.selectedTimeSlots.push({ day, index })
                this.remark = true
                //没有选同一天
            } else if (this.selectedTimeSlots[0].day != day) {
                this.remark = true
                this.$modal.alertWarning("预约不可跨天");
                return;
            } else {
                this.remark = true
                //筛选出符合条件的对象
                const selectObj = this.selectedTimeSlots.find((item) => {
                    console.log('find', item.day == day && item.index == index)
                    return item.day == day && item.index == index
                })
                console.log('selectObj', selectObj)
                if (selectObj != undefined) {
                    this.remark = true
                    this.selectedTimeSlots = this.selectedTimeSlots.filter(item => item.index != index)
                    this.selectedTimeSlots.length == 0 ? this.remark = false : this.selectedTimeSlots
                } else {
                    this.selectedTimeSlots.push({ day, index })
                }
            }
        },
        // -----------------------------------------------------
        /**录播室下拉框列表*/
        getRoomList() {
            getAppointmentList({}).then((res) => {
                this.options = res.rows;
                console.log('res', res)
                if (this.options.length > 0) {
                    // 默认选中第一个录播室
                    this.queryParams.studioId = this.options[0].id;
                    // 立即执行搜索表单
                    this.fetchStudioUseData();
                }

            });
        },

        initTimeSlots() {
            // 初始化时间段
            this.timeSlots = [
                "第一节(上午)",
                "第二节(上午)",
                "第三节(上午)",
                "第四节(上午)",
                "第五节(下午)",
                "第六节(下午)",
                "第七节(下午)",
                "第八节(下午)",
                "第九节(晚上)",
                "第十节(晚上)",
                "第十一节(晚上)",
            ];
        },
        //表格头部日期
        initDays() {
            // 假设从明天开始，获取未来10天的日期
            // const startDate = new Date();
            // startDate.setDate(startDate.getDate() + 1);
            // console.log('startDate',startDate)
            for (let i = 0; i < 10; i++) {
                const formattedDate = moment(this.queryParams.startTime).add(i, 'days').format("YYYY-MM-DD");
                console.log('formattedDate', formattedDate)
                //   const currentDate = new Date(startDate);
                //   currentDate.setDate(currentDate.getDate() + i);
                //   const formattedDate = this.formatDate(currentDate);
                this.days.push(formattedDate);
            }
        },
        // formatDate(date) {
        //   // 格式化日期为'YYYY-MM-DD'的形式
        //   const year = date.getFullYear();
        //   const month = String(date.getMonth() + 1).padStart(2, "0");
        //   const day = String(date.getDate()).padStart(2, "0");
        //   return `${year}-${month}-${day}`;
        // },

        // isOccupied(day, index) {
        //   // 判断指定的时间段是否被占用
        //   // 这里假设你有一个函数可以根据日期和时间段查询录播室的占用情况
        //   const isOccupied = false; // 使用你的接口或数据来判断
        //   return isOccupied;
        // },
        handleMouseDown(day, index) {
            // 处理鼠标按下事件
            this.isMouseDown = true;
            this.startSelection = { day, index };
            this.endSelection = { day, index };
        },
        handleMouseUp(day, index) {
            // 处理鼠标松开事件
            this.isMouseDown = false;
            this.endSelection = { day, index };

            // 根据按下的键盘按键进行选择操作
            if (event.ctrlKey) {
                // 按住 Ctrl 键进行跨格单选
                this.selectedTimeSlots = [this.startSelection];
            } else if (event.shiftKey) {
                // 按住 Shift 键进行不跨格多选（同一天内）
                this.selectedTimeSlots = [];
                this.selectMultipleSlots();
            } else {
                // 单格单选
                this.selectedTimeSlots = [this.startSelection];
            }
        },
        handleMouseEnter(day, index) {
            // 处理鼠标进入单元格事件（用于 Shift 键多选）
            if (this.isMouseDown && event.shiftKey) {
                this.endSelection = { day, index };
                this.selectMultipleSlots();
            }
        },
        //多选事件
        selectMultipleSlots() {
            // 选择多个时间段（同一天内）
            const startDay = this.startSelection.day;
            const endDay = this.endSelection.day;
            const startIndex = this.startSelection.index;
            const endIndex = this.endSelection.index;
            const selectedTimeSlots = [];
            // 遍历日期范围内的时间段，选择符合条件的时间段
            for (
                let dayIndex = this.days.indexOf(startDay);
                dayIndex <= this.days.indexOf(endDay);
                dayIndex++
            ) {
                const day = this.days[dayIndex];
                // 对于同一天内的时间段，根据索引范围进行选择
                if (
                    dayIndex === this.days.indexOf(startDay) &&
                    dayIndex === this.days.indexOf(endDay)
                ) {
                    for (let index = startIndex; index <= endIndex; index++) {
                        selectedTimeSlots.push({ day, index });
                    }
                } else if (dayIndex === this.days.indexOf(startDay)) {
                    // 对于起始日期，选择从起始索引到最后一个时间段
                    for (let index = startIndex; index < this.timeSlots.length; index++) {
                        selectedTimeSlots.push({ day, index });
                    }
                } else if (dayIndex === this.days.indexOf(endDay)) {
                    // 对于结束日期，选择从第一个时间段到结束索引
                    for (let index = 0; index <= endIndex; index++) {
                        selectedTimeSlots.push({ day, index });
                    }
                } else {
                    // 其他日期完全选择
                    for (let index = 0; index < this.timeSlots.length; index++) {
                        selectedTimeSlots.push({ day, index });
                    }
                }
            }
            this.selectedTimeSlots = selectedTimeSlots;
        },
        fetchData() {
            this.studioUseData = []
            this.fetchStudioUseData()
            // this.days = [];
            // // 查询按钮的点击事件处理程序
            // this.initDays()
            // getstudioUse({
            //   startTime: this.queryParams.startTime,
            //   studioId: this.queryParams.studioId,
            // })
            //   .then((res) => {
            //     this.studioUseData = res;
            //   })
            //   .then((response) => {
            //     // console.log(response);
            //     if (response.code == 200) {
            //       this.studioUseData = response.rows;
            //       console.log(222, response.rows);
            //     }
            //   });
            // // 在这里，你可以发送请求获取录播室占用情况等数据
            // console.log("查询成功");
        },


    },
};
</script>

<style scoped>
table {
    border-collapse: collapse;
    margin-top: 20px;
}

.el-form {
    margin-top: 20px;
    margin-left: 30px;
}

th,
td {
    border: 1px solid #000;
    padding: 8px;
    text-align: center;
}

th {
    background-color: #ccc;
}

.occupied {
    background-color: #ccc;
    color: #000;
    cursor: not-allowed;
}

.selected {
    background-color: #66b3ff;
}
</style>
