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

				</div>
				<div><!-- :icon="Plus" -->
					<el-button type="success"  @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: 6px;
							cursor: pointer;
							border: 1px solid #ccc;
							border-radius: 6px;
							padding: 3px;
							background-color: transparent;
							box-shadow: 0 1px 2px rgba(0,0,0,0.05);
						"
					@click.stop="openDialogEdit(course)"
					>
						{{ course.classdetail }} 老师：({{ course.teacher_name }}) 教室：{{ course.classroom }}
					<el-link
						v-if="!isEmbedded"
						type="danger"
						style="font-size: 12px;  top: 0; right: 0"
						@click.stop="deleteCourse(course.id)"
					>
						删除
					</el-link>
					</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,DelObj } from './api';
import { createCrudOptions } from './crud';
import { handleColumnPermission } from '/@/utils/columnPermission';
import AdditionDialog from './AdditionDialog/index.vue';
import { inject } from 'vue';
import { ElMessage } from 'element-plus';
import { ArrowLeft, ArrowRight, Plus} from '@element-plus/icons-vue';


const isEmbedded = inject<boolean>('isEmbedded', false);
type CourseSelectedPayload = { course_id: string | number; course_Name: string; expected_start_time: string };
const onCourseSelected = inject<(payload: CourseSelectedPayload) => void>('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);
}



async function deleteCourse(courseId: number) {
  try {
    await DelObj(courseId);
    ElMessage.success('删除成功');
    await loadData(); // 重新加载数据以刷新视图
  } catch (error) {
    ElMessage.error('删除失败，请稍后重试');
    // console.error('删除课程失败:', error);
  }
}


function getStartTime(time: number): string {
  const timeMap: Record<number, string> = {
    1: '09:00:00',
    2: '14:00:00',
    3: '19:00:00'
  };
  return timeMap[time] ?? '09:00:00';
}


function openDialogEdit(course?: any) {
	const courseId = course?.id || '';
	const courseClassdetail = course?.classdetail || '';
	const courseteacher_name = course?.teacher_name || '';
	const courseclassroom = course?.classroom || '';
	const coursetime_label = course?.time_label || '';
	const courseclassdate=course?.class_date||'';

	const timeStr = getStartTime(course?.time); 
	const expectedStartTime = `${courseclassdate} ${timeStr}`;
	const courseName = `${courseClassdetail} - ${courseteacher_name} - ${courseclassroom} - ${coursetime_label}`;
	// eslint-disable-next-line no-console
	// console.log("expectedStartTime:::",expectedStartTime)
	// eslint-disable-next-line no-console
	// console.log("courseName:::",courseName)
  if (isEmbedded && typeof onCourseSelected === 'function' && onCourseSelected) {
	
	try {
      onCourseSelected({
		course_id: courseId,
		course_Name:courseName,
		expected_start_time: expectedStartTime
      	});
		// dialogRef.value.open(course);
    } catch (e) {
		// eslint-disable-next-line no-console
      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;
}


:deep(.el-button.is-circle) {
  width: 36px;
  height: 36px;
  padding: 0;
}

:deep(.el-button .el-icon) {
  font-size: 18px;
}

.schedule-table :deep(.el-table__cell) {
  padding-top: 12px;
  padding-bottom: 12px;
  font-size: 14px;
}

.schedule-table :deep(.el-table__header .cell) {
  font-size: 15px;
}

</style>
