<template>
	<!-- <fs-page> -->
		<div>
	
		<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, scope.row.timeLabel, index)"
					>
						{{ 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> -->
   </div>
</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';
import { inject } from 'vue';

const isEmbedded = inject('isEmbedded', false);
const onCourseSelected = inject('onCourseSelected', () => {});



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, timeLabel?: string, dayIndex?: number) {
  const courseName = course?.classdetail || '';
  const dateLabel = weekDates.value[dayIndex]; 
  const dateMatch = dateLabel.match(/\d{4}-\d{2}-\d{2}/);
  const dateStr = dateMatch ? dateMatch[0] : dayjs().format('YYYY-MM-DD');
  const timeStr = timeLabel?.split('-')[0] || '09:00';
  const expectedStartTime = `${dateStr} ${timeStr}:00`;

  if (isEmbedded && typeof onCourseSelected === 'function') {
	try {
      onCourseSelected({
		course_name: courseName,
		expected_start_time: expectedStartTime
      	});
		dialogRef.value.open(course);
    } catch (e) {
      console.warn('onCourseSelected failed:', e);
    }
  } else {
    dialogRef.value.open(course);
  }
}



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 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>
