<template>
	<el-drawer v-model="visible" title="任务详情" size="500px" @close="handleClose">
		<el-form v-if="form" :model="form" label-width="80px">
			<el-form-item label="任务名称" required>
				<el-input v-model="form.name" />
			</el-form-item>
			<el-form-item v-if="parentName" label="上级任务">
				<el-link type="primary" @click="openParentTask">{{ parentName }}</el-link>
			</el-form-item>
			<el-form-item label="描述">
				<el-input v-model="form.description" type="textarea" :rows="3" />
			</el-form-item>
			<el-form-item label="阶段">
				<el-select v-model="form.phaseId" placeholder="选择阶段" clearable style="width: 100%">
					<el-option
						v-for="p in store.phases"
						:key="p.id"
						:label="p.text"
						:value="parseInt(String(p.id).replace('p_', ''))"
					/>
				</el-select>
			</el-form-item>
			<el-form-item label="状态">
				<el-select v-model="form.status" style="width: 100%">
					<el-option label="待办" :value="0" />
					<el-option label="进行中" :value="1" />
					<el-option label="已完成" :value="2" />
					<el-option label="已关闭" :value="3" />
				</el-select>
			</el-form-item>
			<el-form-item label="优先级">
				<el-select v-model="form.priority" style="width: 100%">
					<el-option label="P0 紧急" :value="0" />
					<el-option label="P1 高" :value="1" />
					<el-option label="P2 中" :value="2" />
					<el-option label="P3 低" :value="3" />
				</el-select>
			</el-form-item>
			<el-form-item label="分类">
				<el-input v-model="form.category" placeholder="如：前端、后端、运营" />
			</el-form-item>
			<el-form-item label="负责人">
				<el-input v-model="form.assigneeName" placeholder="负责人姓名" />
			</el-form-item>
			<el-form-item label="日期范围">
				<el-date-picker
					v-model="dateRange"
					type="daterange"
					value-format="YYYY-MM-DD"
					start-placeholder="开始"
					end-placeholder="结束"
					style="width: 100%"
				/>
			</el-form-item>
			<el-form-item label="预估工时">
				<el-input-number v-model="form.estimatedHours" :min="0" :step="0.5" />
				<span style="margin-left: 8px; color: #909399">
					实际: {{ form.actualHours || 0 }}h
				</span>
			</el-form-item>
			<el-form-item label="进度">
				<el-slider v-model="form.progress" :max="100" show-input />
			</el-form-item>
		</el-form>

		<!-- 工时记录 -->
		<div v-if="taskId" style="padding: 0 20px">
			<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px">
				<span style="font-weight: 600">工时记录</span>
				<el-button size="small" type="primary" @click="timeLogVisible = true">
					添加工时
				</el-button>
			</div>
			<el-table :data="timeLogs" size="small" max-height="200">
				<el-table-column prop="logDate" label="日期" width="100" />
				<el-table-column prop="hours" label="工时(h)" width="70" align="center" />
				<el-table-column prop="userName" label="记录人" width="70" />
				<el-table-column prop="description" label="内容" />
			</el-table>
		</div>

		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
		</template>

		<time-log-dialog
			v-model="timeLogVisible"
			:task-id="taskId!"
			@saved="loadTimeLogs"
		/>
	</el-drawer>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { useCool } from '/@/cool';
import { useProjectStore } from '../../store/project';
import { ElMessage, ElMessageBox } from 'element-plus';
import TimeLogDialog from './time-log-dialog.vue';

const props = defineProps<{
	modelValue: boolean;
	taskId: number | null;
	projectId: number;
}>();

const emit = defineEmits<{
	(e: 'update:modelValue', v: boolean): void;
	(e: 'saved'): void;
	(e: 'open-task', id: number): void;
}>();

const { service } = useCool();
const store = useProjectStore();

// 用 computed 替代双向 watch，避免无限递归
const visible = computed({
	get: () => props.modelValue,
	set: (v) => emit('update:modelValue', v),
});
const saving = ref(false);
const timeLogVisible = ref(false);
const timeLogs = ref<any[]>([]);
const dateRange = ref<string[]>([]);
const form = ref<any>({});
const parentName = ref('');
const originalFields = ref<Record<string, any>>({});

function toNumber(value: unknown) {
	const n = Number(value);
	return Number.isFinite(n) ? n : 0;
}

function toDateString(value: unknown) {
	if (!value) return '';
	if (value instanceof Date) return value.toISOString().slice(0, 10);
	return String(value).slice(0, 10);
}

watch(() => props.modelValue, (v) => {
	if (v) loadTaskData();
});

async function loadTaskData() {
	const id = props.taskId;
	if (id && id > 0) {
		const res = await service.project.task.info({ id });
		form.value = { ...res };
		// MySQL decimal 类型返回字符串，转为数字供 el-input-number 使用
		form.value.estimatedHours = toNumber(res.estimatedHours);
		form.value.actualHours = toNumber(res.actualHours);
		form.value.progress = toNumber(res.progress);
		const startDate = toDateString(res.startDate);
		const endDate = toDateString(res.endDate);
		form.value.startDate = startDate || null;
		form.value.endDate = endDate || null;
		originalFields.value = {
			status: res.status,
			priority: res.priority,
			category: res.category,
			assigneeName: res.assigneeName,
			startDate,
			endDate,
			estimatedHours: toNumber(res.estimatedHours),
		};
		dateRange.value = startDate ? [startDate, endDate] : [];
		if (res.parentId) {
			const parent = await service.project.task.info({ id: res.parentId });
			parentName.value = parent?.name || '';
		} else {
			parentName.value = '';
		}
		await loadTimeLogs();
	} else if (id === 0) {
		form.value = {
			projectId: props.projectId,
			name: '',
			description: '',
			status: 0,
			priority: 2,
			category: '',
			assigneeName: '',
			estimatedHours: 0,
			progress: 0,
		};
		dateRange.value = [];
		timeLogs.value = [];
		parentName.value = '';
		originalFields.value = {};
	}
}

async function loadTimeLogs() {
	if (!props.taskId) return;
	const res = await service.project.time_log.page({
		page: 1,
		size: 50,
		taskId: props.taskId,
	});
	timeLogs.value = res.list || [];
}

async function handleSave() {
	if (!form.value.name) { ElMessage.warning('请输入任务名称'); return; }
	saving.value = true;
	form.value.startDate = dateRange.value?.[0] || null;
	form.value.endDate = dateRange.value?.[1] || null;
	try {
		if (form.value.id) {
			await service.project.task.update(form.value);

			// 检测哪些可级联字段发生了变化
			const cascadeKeys: { key: string; label: string }[] = [
				{ key: 'status', label: '状态' },
				{ key: 'priority', label: '优先级' },
				{ key: 'category', label: '分类' },
				{ key: 'assigneeName', label: '负责人' },
				{ key: 'startDate', label: '开始日期' },
				{ key: 'endDate', label: '结束日期' },
				{ key: 'estimatedHours', label: '预估工时' },
			];
			const changedFields: Record<string, any> = {};
			const changedLabels: string[] = [];
			for (const { key, label } of cascadeKeys) {
				const oldVal = originalFields.value[key] ?? null;
				const newVal = form.value[key] ?? null;
				if (String(oldVal) !== String(newVal)) {
					changedFields[key] = newVal;
					changedLabels.push(label);
				}
			}

			if (changedLabels.length > 0) {
				try {
					const has = await service.request({
						url: '/admin/project/task/hasChildren',
						params: { id: form.value.id },
					});
					if (has) {
						await ElMessageBox.confirm(
							`「${changedLabels.join('、')}」已修改，是否将所有子任务也同步修改？`,
							'同步子任务',
							{ confirmButtonText: '是，同步修改', cancelButtonText: '否，仅修改当前', type: 'info' }
						);
						await service.request({
							url: '/admin/project/task/cascadeStatus',
							method: 'POST',
							data: { id: form.value.id, fields: changedFields },
						});
					}
				} catch (_) {
					// 用户点击"否"，不做级联
				}
			}
		} else {
			await service.project.task.add(form.value);
		}
		ElMessage.success('保存成功');
		emit('saved');
		visible.value = false;
	} finally {
		saving.value = false;
	}
}

function handleClose() {
	form.value = {};
	parentName.value = '';
}

function openParentTask() {
	const pid = form.value.parentId;
	if (pid) {
		visible.value = false;
		setTimeout(() => {
			emit('open-task', pid);
		}, 300);
	}
}
</script>
