<template>
	<el-dialog v-model="visible" title="课堂借用申请单" width="80%" :close-on-click-modal="false" @close="onCancel">
		<div style="margin-bottom: 16px">
			<div style="font-weight: bold; font-size: 18px; margin-bottom: 8px">课程信息</div>
			<el-row :gutter="8" style="margin-bottom: 8px; align-items: center">
				<el-col :span="6">
					<el-select v-model="form.purpose" placeholder="请选择课程" @change="onCourseChange">
						<el-option
							v-for="course in weeklyCourses"
							:key="course.id"
							:label="`${course.classdetail} - ${course.teacher_name} - ${course.classroom} - ${course.time_label}`"
							:value="course.classdetail"
						/>
					</el-select>
				</el-col>
				

				<!-- <el-col :span="3">
					<el-button>手动输入</el-button>
				</el-col> -->
				<!-- <el-col :span="6">
					<el-input v-model="form.course_input" placeholder="请输入课程名称" />
				</el-col>
				<el-col :span="3">
					<el-button type="primary">搜索</el-button>
				</el-col> -->
			</el-row>
			<div style="max-height: 400px; overflow-y: auto; border: 1px solid #eee; padding: 8px; margin-bottom:0px">
				<timetablemanage />
			</div>
		</div>
		<el-form :model="form" label-width="110px" label-position="top" :rules="rules" ref="formRef">
			<el-row :gutter="16">
				<el-col :span="8">
					<el-form-item label="借用单编号" prop="application_no">
						<el-input v-model="form.application_no" placeholder="自动生成" disabled />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="借用人" prop="emergency_contact">
						<el-input v-model="form.emergency_contact" placeholder="请输入借用人"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="学号/工号" prop="app_user_borrower">
						<el-input v-model="form.app_user_borrower" placeholder="请输入学号/工号"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="联系电话" prop="emergency_phone">
						<el-input v-model="form.emergency_phone" placeholder="请输入联系电话"  />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="借用部门" prop="borrower_dept">
						<el-input v-model="form.borrower_dept" placeholder="请输入借用部门"  />
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="团队人数" prop="team_members_count">
						<el-input v-model="form.team_members_count" placeholder="请输入" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="团队其他人员名单" prop="team_members">
						<el-input v-model="form.team_members" placeholder="请输入团队其他人员名单" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="备注" prop="applicant_remark">
						<el-input v-model="form.applicant_remark" placeholder="请输入备注" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="预计归还时间" prop="expected_end_time">
						<el-date-picker v-model="form.expected_end_time" type="datetime" placeholder="请选择预计归还时间" style="width: 100%" />
					</el-form-item>
				</el-col>
			</el-row>
			<div style="margin: 16px 0 8px 0; font-weight: bold">借用明细表</div>
			<el-table :data="form.items" border style="width: 100%; margin-bottom: 12px">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="remark" label="设备分类" />
				<el-table-column label="借用数量">
				<template #default="{ row }">
				<el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" />
				</template>
				</el-table-column>
				<el-table-column prop="location" label="存放仓库" />
				<el-table-column label="操作" width="80">
					<template #default="{ row, $index }">
						<el-button type="text" style="color: red" @click="removeItem($index)">移除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-button type="primary" @click="addItem">添加设备</el-button>

			<!-- <div style="margin: 16px 0 8px 0; font-weight: bold">附件</div>
			<el-upload
			drag
			list-type="picture"
			:show-file-list="true"
			:http-request="handleCustomUpload"
			>
			<i class="el-icon-upload"></i>
			<div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
			</el-upload> -->
			<div>
			<el-upload
			list-type="picture-card"
			:show-file-list="true"
			:http-request="handleCustomUpload"
			:file-list="fileList"
			style="margin-top: 10px;"
			>
			<el-icon><Plus /></el-icon>
			</el-upload>
		    </div>


		</el-form>


		<!-- 审批信息流程展示 -->
		<div v-if="isView"  style="margin-top: 24px; padding: 0 12px">
		<div style="font-weight: bold; margin-bottom: 12px">审批流程进度</div>
		<el-steps :active="activeStep" align-center>
			<el-step
			title="创建申请"
			:description="`创建时间：${ timeline.create }`"
			icon="CircleCheck"
			:status="activeStep >= 1 ? 'finish' : 'wait'"
			/>
			<el-step
			title="待审批"
			description="待超级管理员审批"
			icon="CircleCheck"
			:status="activeStep >= 2 ? 'finish' : 'wait'"
			/>
			<el-step
			title="审批通过"
			:description="`审批人：${timeline.approver}，时间：${timeline.approve}`"
			icon="CircleCheck"
			:status="activeStep >= 3 ? 'finish' : 'wait'"
			/>
			<el-step
			title="流程完成"
			description="流程已结束"
			icon="CircleCheck"
			:status="activeStep >= 4 ? 'finish' : 'wait'"
			/>
		</el-steps>
		</div>

		<template #footer>
			<el-button @click="onCancel">关闭</el-button>
			<el-button v-if="!isViewMode" type="primary" @click="onSave">提交</el-button>
		</template>
		<SelectDeviceDialog v-model:visible="showSelectDeviceDialog" @confirm="onDeviceSelected" />
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, onMounted, computed,inject,Ref, } from 'vue';
import SelectDeviceDialog from '../SpecialBorrow/SelectDeviceDialog/index.vue';
import timetablemanage from '../../../timetablemanage/index.vue';
import * as apis from '../../../timetablemanage/api';
import * as api from '../../api';
import { provide } from 'vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash-es';
import Cookies from 'js-cookie';
import { request } from '/@/utils/service';
import { Plus } from '@element-plus/icons-vue';



const fileList = ref([]);

// const fileList = ref([]);
const handleCustomUpload = async ({ file, onProgress, onSuccess, onError }: any) => {
  const token = Cookies.get('token'); 
  const formData = new FormData();
  formData.append('file', file);
  console.log("token::::",token);

  try {
    const res = await request({
		url: `/api/system/upload/`,
		method: 'post',
		headers: {
			'Content-Type': 'multipart/form-data',
			Authorization: 'JWT '+ token,
		},
		data: formData,
		timeout: 60000,
		onUploadProgress: (p: any) => {
                            onProgress({percent: Math.round((p.loaded / p.total) * 100)});
		}
    });

	// 构造 Element Plus 需要的 file 对象
	const fileObj = {
      name: res.data.name,
      url: res.data.url,
      status: 'success',
      response: res.data
    };

    // 添加到附件列表
	form.value.attachments = fileObj.url; 

    ElMessage.success('上传成功');
    onSuccess(fileObj); 
  } catch (error) {
    ElMessage.error('上传失败');
    onError(error);
  }
};


provide('isEmbedded', true);
provide('onCourseSelected', handleCourseSelected);

const props = defineProps<{ visible: boolean; modelValue?: any ; lastFormSnapshot: Record<string, any>;}>();
const emit = defineEmits(['update:visible', 'update:modelValue', 'submit','update:lastFormSnapshot']);
const visible = ref(props.visible);
const formRef = ref();

const isEdit = computed(() => props.modelValue?.mode === 'edit');
const isView = computed(() => props.modelValue?.mode === 'view');
const isAdd = computed(() => props.modelValue?.mode === 'add');



function handleCourseSelected({ course_id, course_Name,expected_start_time }) {
	// eslint-disable-next-line no-console
  console.log("kebiao=form.value.expected_start_time:::",form.value.expected_start_time)
  form.value.purpose = course_Name;
  form.value.expected_start_time = expected_start_time;
}


const weeklyCourses = ref<any[]>([]);

async function fetchWeeklySchedule() {
  const res = await apis.GetCurrentWeekList();
  	// eslint-disable-next-line no-console
	// console.log("res.data:::",res.data)
  const schedule = res.data.schedule;

  const courseMap = new Map<string, any>();

  for (const dayKey in schedule) {
    const daySchedule = schedule[dayKey];
    for (const timeKey in daySchedule) {
      const courses = daySchedule[timeKey];
      for (const course of courses) {
        if (!courseMap.has(course.classdetail)) {
          courseMap.set(course.classdetail, course);
        }
      }
    }
  }

  weeklyCourses.value = Array.from(courseMap.values());
}

function onCourseChange(selectedName: string) {
  const selectedCourse = weeklyCourses.value.find(c => c.classdetail === selectedName);
  if (selectedCourse) {
    form.value.expected_start_time = `${selectedCourse.class_date} ${getStartTime(selectedCourse.time)}`;
    form.value.teacher_name = selectedCourse.teacher_name;
    form.value.classroom = selectedCourse.classroom;
  }
  console.log("form.value.expected_start_time ::",form.value.expected_start_time );
}

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




const form = ref({
	application_no: '',
	emergency_contact: '',
	purpose:'',
	emergency_phone: '',
	app_user_borrower: 1,
	borrower_dept: '',
	team_type: 1,
	team_members_count: 2,
	team_members: '',
	expected_start_time:'',
    expected_end_time: "",
	applicant_remark: '',
	return_location:'',
	items: [],
	borrow_type:1,
	course_input: '',
	attachments:'',
});
const showSelectDeviceDialog = ref(false);
const isViewMode = computed(() => props.modelValue?.mode === 'view');


const rules = {
  emergency_contact: [
    { required: true, message: '请输入借用人', trigger: 'change' },
  ],
  app_user_borrower: [
    { required: true, message: '请输入学号或工号', trigger: 'change' },
  ],
  emergency_phone: [
    { required: true, message: '请输入联系电话', trigger: 'change' },
  ],
  team_members_count: [
  	{ required: true, message: '请输入团队人数', trigger: 'change' },
	{
		validator: (_rule, value, callback) => {
		if (value <= 1) {
			callback(new Error('团队人数必须大于 1'));
		} else {
			callback();
		}
		},
		trigger: 'change'
	}
	],
  borrower_dept: [
    { required: true, message: '请输入借用部门', trigger: 'change' },
  ],
  expected_end_time: [
    { required: true, message: '请输选择归还时间', trigger: 'change' },
  ],
  team_members:[
    { required: true, message: '请输入团队其他人员名单', trigger: 'change' },
  ],
  team_type: [
    { required: true, message: '请选择个人或者团队', trigger: 'change' },
  ],
  purpose: [
    { required: true, message: '请输入借用原因', trigger: 'change' },
  ],
  applicant_remark: [
    { required: true, message: '请输入备注', trigger: 'change' },
  ],
};

onMounted(() => {
	try {
		const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
		if (userInfo) {
			form.value.emergency_contact = userInfo.username || '';
			form.value.app_user_borrower = Number(userInfo.dept_info?.dept_id )|| 1;
			form.value.emergency_phone = userInfo.mobile || '';
			form.value.borrower_dept = userInfo.dept_info?.dept_name || '';
		}
	} catch (e) {console.error(e)}
	fetchWeeklySchedule();
});



function resetForm() {
  form.value = {
    application_no: '',
    emergency_contact: '',
    purpose: '',
    emergency_phone: '',
    app_user_borrower: 1,
    borrower_dept: '',
    team_type: 1,
    team_members_count: 2,
    team_members: '',
    expected_start_time: '',
    expected_end_time: '',
    applicant_remark: '',
    return_location: '',
    items: [],
    borrow_type: 1,
    course_input: '',
	attachments:'',
  };
}



watch(() => props.visible, (v) => {
  visible.value = v;
//   console.log("快照visible.value：：",visible.value)
  if (v) {
    if (props.lastFormSnapshot) {
		console.log("快照lastFormSnapshot.value：：",props.lastFormSnapshot )
		form.value = { ...props.lastFormSnapshot };
    } else {
		// console.log("没有快照lastFormSnapshot.value：：",props.lastFormSnapshot )
      resetForm(); // 如果没有快照，初始化表单
    }
  }
}, { immediate: true });


const timeline = ref({
  create: '',
  approve: '',
  approver: ''
});
const activeStep = ref(1);

watch(() => props.modelValue, async (val) => {
  if (val && val.id && isView.value) {
			try {
			const res = await api.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
				timeline.value.create = data.create_datetime || '';
				timeline.value.approve = data.approve_time || '';
				timeline.value.approver = data.approver_info?.name || '审批人';

				activeStep.value = 1; // 创建
				if (data.status >= 1) activeStep.value = 2; // 待审批
				if (data.status >= 2) activeStep.value = 3; // 审批通过
				if (data.status >= 3) activeStep.value = 4; // 完成
			}
			} catch (e) {
			ElMessage.error('获取审批信息失败');
			}
	}else if(val&& isEdit.value){
		try {
			const res = await api.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
			}
			} catch (e) {
			ElMessage.error('获取审批信息失败');
			}
	}
}, { immediate: true });

function addItem() {
	showSelectDeviceDialog.value = true;
}
function onDeviceSelected(devices) {
	form.value.items.push(
		...devices.map((d) => ({
			device: d.id,
			remark: d.category_name,
			quantity: 1,
			location: d.warehouse,
		}))
	);
}
function removeItem(index) {
	form.value.items.splice(index, 1);
}
function onCancel() {
	emit('update:visible', false);
}

const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
function onSave() {
	formRef.value.validate((valid) => {
		if (valid) {
			form.value.items = form.value.items.map(item => ({
                ...item,
                quantity: Number(item.quantity) || 0  
            }));
			const firstLocation = form.value.items[0]?.location || '';
            form.value.return_location = firstLocation;
			// form.value.expected_start_time = now;
			form.value.expected_start_time = form.value.expected_start_time ? form.value.expected_start_time : now;
			form.value.expected_end_time = dayjs(form.value.expected_end_time).format('YYYY-MM-DD HH:mm:ss')|| now;
			form.value.team_members_count=Number(form.value.team_members_count)||2;
			emit('submit', { ...form.value });
			emit('update:visible', false);
			// ElMessage.success("添加成功!");	
			emit('update:lastFormSnapshot', cloneDeep(form.value));

		}
	});
}

</script>
