<template>
	<fs-page>
	
		<div class="schedule-wrapper">
			<div class="header">
				<div class="header-bar">
				<el-button type="primary" icon="el-icon-arrow-left" @click="prevWeek" circle ><</el-button>
				<span class="week-display">{{ displayWeek }} 周</span>
				<el-button type="primary" icon="el-icon-arrow-right" @click="nextWeek" circle
							:disabled="currentWeek + weekOffset >= totalWeeks" >></el-button>

				</div>
				<div>
					<el-button type="success" icon="el-icon-plus" @click="openDialog()">添加课程</el-button>
				</div>

			</div>

			<el-table :data="scheduleData" style="width: 100%; background-color: white" :header-cell-style="headerStyle">
			
			<el-table-column label="时间段" width="100">
				<template #default="scope">
				{{ scope.row.timeLabel }}
				</template>
			</el-table-column>
			<!-- 星期一至星期日列 -->
			<el-table-column
				v-for="(day, index) in weekDates"
				:key="index"
				:label="day"
				min-width="160"
			>
			<template #default="scope">
				<div
					:style="{
					backgroundColor: columnColorMap[index],
					padding: '6px',
					borderRadius: '4px',
					whiteSpace: 'pre-line',
					minHeight: '40px'
					}"
				>
					<div
					v-for="course in scope.row[`day${index + 1}`]"
					:key="course.id"
					style="margin-bottom: 4px; cursor: pointer"
					@click.stop="openDialogEdit(course)"
					>
						{{ course.classdetail }} 老师：({{ course.teacher_name }}) 班级：{{ course.classroom }}
					</div>
				</div>
			</template>

			</el-table-column>
			</el-table>




		</div>
		<fs-crud ref="crudRef" v-bind="crudBinding"> </fs-crud>

		<AdditionDialog ref="dialogRef" @saved="loadData"  />
		
	</fs-page>
</template>

<script lang="ts" setup name="timetablemanage">
import { useFs } from '@fast-crud/fast-crud';
import dayjs from 'dayjs';
import isLeapYear from 'dayjs/plugin/isLeapYear';
import isoWeek from 'dayjs/plugin/isoWeek';
import isoWeeksInYear from 'dayjs/plugin/isoWeeksInYear';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import { computed, onMounted, ref } from 'vue';
import { GetPermission,getScheduleData } from './api';
import { createCrudOptions } from './crud';
import { handleColumnPermission } from '/@/utils/columnPermission';
import AdditionDialog from './AdditionDialog/index.vue';



const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ createCrudOptions });

dayjs.extend(weekOfYear)
dayjs.extend(isoWeek)
dayjs.extend(isLeapYear)
dayjs.extend(isoWeeksInYear)

const currentWeek = ref(dayjs().isoWeek())
const totalWeeks = ref(dayjs().isoWeeksInYear())
const weekOffset = ref(0)


const columnColorMap: string[] = [
  '#e3f2fd', 
  '#e8f5e9', 
  '#fff3e0',
  '#fce4ec',
  '#ede7f6', 
  '#f3e5f5',
  '#fbe9e7'  
]



const timeLabels = ref<string[]>([]); // 从接口获取

function getTimeSlot(index: number): string {
  return timeLabels.value[index] || '—';
}

function getPeriodLabel(index: number): string {
  return `时间段`;
}


const displayWeek = computed(() => currentWeek.value + weekOffset.value)


const dialogRef = ref();

function openDialog(data?: any) {
  dialogRef.value.open(data);
}



const selectedCourses = ref<any[]>([]);
const courseSelectVisible = ref(false);

function editCourse(course: any) {
  courseSelectVisible.value = false;
  openDialog(course);
}


function openDialogEdit(course?: any) {
	// eslint-disable-next-line no-console
	console.log('course:::::', course);
	if (!course) {
		// 新建
		dialogRef.value.open({
		class_date: dayjs().format('YYYY-MM-DD'),
		time: 1,
		class_number: 1
		});
	} else {	
		dialogRef.value.open(course);
	}
}


// function handleCellClick(row: any, dayIndex: number) {
// 	const classText = row[`day${dayIndex + 1}`];
// 	// eslint-disable-next-line no-console
// 	console.log('classText:::::', classText);
// 	const timeIndex = timeLabels.value.indexOf(row.timeLabel) + 1;
// 	if (!classText || classText.length === 0) {
// 		openDialog({
//         class_date: dayjs().startOf('isoWeek').add(dayIndex, 'day').format('YYYY-MM-DD'),
//         time: timeIndex,
//       });
// 	}
// 	else if (classText.length === 1) {
//       openDialog(classText[0]);
//     } else {
// 		selectedCourses.value = classText;
// 		courseSelectVisible.value = true;
//     }

//   } else {

//     openDialog({
//       class_date: dayjs().startOf('isoWeek').add(dayIndex, 'day').format('YYYY-MM-DD'),
//       time: timeLabels.value.indexOf(row.timeLabel) + 1,
//       classdetail: '高等数学',
//       teacher: 13,
//       semester: 1,
//       grade: 1,
//       class_number: row.id,
//       classroom: 'A101',
//       total_lessons: 48
//     });
//   }
// }


// const weekDates = computed(() => {
//   const monday = dayjs().startOf('isoWeek').add(weekOffset.value, 'week')
//   return Array.from({ length: 7 }, (_, i) => {
//     const date = monday.add(i, 'day')
//     return `${['周一','周二','周三','周四','周五','周六','周日'][i]} (${date.format('MM.DD')})`
//   })
// })

function nextWeek() {
  if (currentWeek.value + weekOffset.value < totalWeeks.value){
	weekOffset.value++;
	loadData() ;
  } 
}
function prevWeek() {
	weekOffset.value--;
	loadData() ;
}

const headerStyle = {
  backgroundColor: '#f5f5f5', 
  fontWeight: 'bold',         
  color: '#333',
  textAlign: 'center'              
}



// const periodLabels = [
//   '第一节', '第二节', '第三节', '第四节', '第五节',
//   '第六节', '第七节', '第八节', '第九节', '第十节'
// ]
// function getPeriodLabel(index: number): string {
//   return periodLabels[index] || `第${index + 1}节`
// }


const scheduleData = ref<any[]>([])

const weekDates = ref<string[]>([]);

async function loadData() {
  const result = await GetPermission(weekOffset.value);
  timeLabels.value = result.data.time_labels;
  weekDates.value = result.data.week_labels_with_date;
//   scheduleData.value = await getScheduleData(weekOffset.value);
	scheduleData.value = await getScheduleData(result);
}



function getSchedule(row: any, index: number) {
  return row[`day${index + 1}`] || ''
}

// 页面打开后获取列表数据
onMounted(async () => {
	// 设置列权限
	const newOptions = await handleColumnPermission(GetPermission, crudOptions);
	//重置crudBinding
	resetCrudOptions(newOptions);
	// 刷新
	crudExpose.doRefresh();
	await loadData(); 
});
</script>



<style scoped>
   .header-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  margin: 16px auto;      
  width: fit-content;    
}

.week-display {
  font-size: 16px;
  font-weight: bold;
  padding: 0 12px;
  min-width: 80px;
  text-align: center;
}


</style>
