import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useCool } from '/@/cool';

export const useProjectStore = defineStore('project', () => {
	const { service } = useCool();

	// 当前项目信息
	const currentProject = ref<any>(null);

	// 甘特图数据
	const ganttData = ref<{ data: any[]; links: any[] }>({ data: [], links: [] });

	// 任务列表（平铺）
	const tasks = computed(() =>
		ganttData.value.data.filter((d: any) => String(d.id).startsWith('t_'))
	);

	// 阶段列表
	const phases = computed(() =>
		ganttData.value.data.filter((d: any) => String(d.id).startsWith('p_'))
	);

	/**
	 * 加载项目详情
	 */
	async function loadProject(projectId: number) {
		const res = await service.project.info.info({ id: projectId });
		currentProject.value = res;
		return res;
	}

	/**
	 * 加载甘特图数据（所有视图共享）
	 */
	async function loadGanttData(projectId: number) {
		const res = await service.project.task.ganttData({ projectId });
		ganttData.value = res;
		return res;
	}

	/**
	 * 刷新数据
	 */
	async function refresh() {
		if (currentProject.value?.id) {
			await loadGanttData(currentProject.value.id);
		}
	}

	/**
	 * 甘特图拖拽更新
	 */
	async function ganttUpdate(items: any[]) {
		await service.project.task.ganttUpdate({ items });
		await refresh();
	}

	/**
	 * 看板排序
	 */
	async function kanbanSort(items: any[]) {
		await service.project.task.kanbanSort({ items });
		await refresh();
	}

	/**
	 * 添加任务
	 */
	async function addTask(data: any) {
		await service.project.task.add(data);
		await refresh();
	}

	/**
	 * 更新任务
	 */
	async function updateTask(data: any) {
		await service.project.task.update(data);
		await refresh();
	}

	/**
	 * 删除任务
	 */
	async function deleteTask(ids: number[]) {
		await service.project.task.delete({ ids });
		await refresh();
	}

	/**
	 * 重置
	 */
	function reset() {
		currentProject.value = null;
		ganttData.value = { data: [], links: [] };
	}

	return {
		currentProject,
		ganttData,
		tasks,
		phases,
		loadProject,
		loadGanttData,
		refresh,
		ganttUpdate,
		kanbanSort,
		addTask,
		updateTask,
		deleteTask,
		reset,
	};
});
