<template>
	<div class="container">
		<div class="svg-timeline">
			<svg :viewBox="`0 0 ${svgWidth} ${svgHeight}`" width="100%" height="100%">
				<!-- <line
          :x1="lines[0].x1 - 100"
          :y1="lines[0].y1"
          :x2="lines[0].x1"
          :y2="lines[0].y1"
          stroke="#e8f2ff"
          stroke-width="2"
          marker-end="url(#arrow)"
        /> -->
				<!-- <line
          v-for="(line, idx) in lines"
          :key="'line' + idx"
          :x1="line.x1"
          :y1="line.y1"
          :x2="line.x2"
          :y2="line.y2"
          stroke="#e8f2ff"
          stroke-width="2"
          marker-end="url(#arrow)"
        /> -->
				<!-- <path
          v-for="(arc, idx) in arcPaths"
          :key="'arc' + idx"
          :d="arc.d"
          fill="none"
          stroke="red"
          stroke-width="2"
        /> -->
				<line
					v-if="nodes.length > 0"
					:x1="nodes[0].x - 100"
					:y1="nodes[0].y"
					:x2="nodes[0].x"
					:y2="nodes[0].y"
					stroke="#e8f2ff"
					stroke-width="2"
					marker-end="url(#arrow)"
				/>
				<path :d="arcPaths" fill="none" stroke="#e8f2ff" stroke-width="2" marker-end="url(#arrow)" />
				<!-- <defs>
          <marker
            id="arrow"
            markerWidth="6"
            markerHeight="6"
            refX="6"
            refY="3"
            orient="auto"
            markerUnits="strokeWidth"
          >
            <path d="M0,0 L6,3 L0,6" fill="#333" />
          </marker>
        </defs> -->
				<!-- 节点 -->
				<circle
					v-for="(node, idx) in nodes.slice(0, nodes.length)"
					:key="'circle' + idx"
					:cx="node.x"
					:cy="node.y"
					r="4"
					fill="#fff"
					stroke="#1677ff"
					stroke-width="3"
				/>
				<line
					v-for="(node, idx) in nodes.slice(0, nodes.length)"
					:key="'line' + idx"
					:x1="node.x"
					:y1="node.y + 4"
					:x2="node.x"
					:y2="node.y + verticalLineLength"
					stroke="#1677ff"
					:stroke-width="verticalLineWidth"
				/>

				<foreignObject
					v-for="(node, idx) in nodes"
					:key="'fo-' + idx"
					:x="node.x + 15"
					:y="node.y + 5"
					:width="nodeGapX - 30"
					height="100"
					style="overflow: visible;"
				>
					<div class="node-content" xmlns="http://www.w3.org/1999/xhtml">
						<div class="date">{{ node.formattedDate }}</div>
						<div class="title">{{ node.actionTitle }}</div>
						<div class="votes" v-if="node.voteString">{{ node.voteString }}</div>
					</div>
				</foreignObject>
				<text
					v-if="startMonth && nodes.length > 0"
					:x="nodes[0].x - 110"
					:y="nodes[0].y + 5"
					text-anchor="end"
					fill="rgb(5, 95, 194)"
					font-size="16"
					font-weight="700"
				>
					{{ startMonth }}
				</text>

				<line
					v-if="nodes.length > 0"
					:x1="nodes[nodes.length - 1].x"
					:y1="nodes[nodes.length - 1].y"
					:x2="nodes[nodes.length - 1].row % 2 === 0 ? nodes[nodes.length - 1].x + 100 : nodes[nodes.length - 1].x - 100"
					:y2="nodes[nodes.length - 1].y"
					stroke="#e8f2ff"
					stroke-width="2"
					marker-end="url(#arrow)"
				/>
				<text
					v-if="endMonth && nodes.length > 0"
					:x="nodes[nodes.length - 1].row % 2 === 0 ? nodes[nodes.length - 1].x + 110 : nodes[nodes.length - 1].x - 110"
					:y="nodes[nodes.length - 1].y + 5"
					:text-anchor="nodes[nodes.length - 1].row % 2 === 0 ? 'start' : 'end'"
					fill="rgb(5, 95, 194)"
					font-size="16"
					font-weight="700"
				>
					{{ endMonth }}
				</text>
			</svg>
		</div>
	</div>
</template>

<script>
export default {
	props: ["dataList"],
	data() {
		return {
			// dataList: [
			//   { actionDate: "2025-07-08 14:20", actionTitle: "起飞", dyms: '16票赞成 : 21票反对​ ' },
			//   { actionDate: "2025-07-08 14:22", actionTitle: "转弯" },
			//   { actionDate: "2025-07-08 14:25", actionTitle: "发现问题",dyms: '16票赞成 : 21票反对​ ' },
			//   { actionDate: "2025-07-08 14:27", actionTitle: "飞行",dyms: '16票赞成 : 21票反对​ ' },
			//   { actionDate: "2025-07-08 14:33", actionTitle: "转弯" },
			//   { actionDate: "2025-07-08 14:35", actionTitle: "飞行" },
			// ],
			maxPerRow: 5,
			nodeGapX: 200,
			nodeGapY: 180,
			leftMargin: 150,
			verticalLineLength: 80,
			verticalLineWidth: 1
		};
	},
	computed: {
		startMonth() {
			if (this.sortedDataList.length === 0) return '';
			const date = new Date(this.sortedDataList[0].actionDate);
			return `${date.getFullYear()}年${date.getMonth() + 1}月`;
		},
		endMonth() {
			if (this.sortedDataList.length === 0) return '';
			const date = new Date(this.sortedDataList[this.sortedDataList.length - 1].actionDate);
			return `${date.getFullYear()}年${date.getMonth() + 1}月`;
		},
		sortedDataList() {
			if (!this.dataList) return [];
			// Clone and sort by date ascending (Old -> New)
			return [...this.dataList].sort((a, b) => new Date(a.actionDate) - new Date(b.actionDate));
		},
		nodes() {
			// 计算每个节点的坐标（蛇形）
			return this.sortedDataList.map((item, idx) => {
				const row = Math.floor(idx / this.maxPerRow);
				const col = idx % this.maxPerRow;
				let x, y;
				// const leftMargin = 150; // 你可以自定义这个值

				if (row % 2 === 0) {
					x = this.leftMargin + col * this.nodeGapX + 50;
				} else {
					x = this.leftMargin + (this.maxPerRow - 1 - col) * this.nodeGapX + 50;
				}
				// 节点纵坐标起始值
				y = 60 + row * this.nodeGapY;

				// Format Date: 2025-07-04 -> 7月4日
				const dateObj = new Date(item.actionDate);
				const formattedDate = `${dateObj.getMonth() + 1}月${dateObj.getDate()}日`;

				// Format Votes
				let voteString = '';
				if (item.agreeVote !== null && item.disagreeVote !== null) {
					voteString = `${item.agreeVote}票赞成 : ${item.disagreeVote}票反对`;
				}

				return { ...item, x, y, row, formattedDate, voteString };
			});
		},
		lines() {
			const arr = [];
			const gap = 0; // 间隔长度
			for (let i = 0; i < this.nodes.length - 1; i++) {
				const x1 = this.nodes[i].x;
				const y1 = this.nodes[i].y;
				const x2 = this.nodes[i + 1].x;
				const y2 = this.nodes[i + 1].y;
				const dx = x2 - x1;
				const dy = y2 - y1;
				const len = Math.sqrt(dx * dx + dy * dy);
				// 计算起点和终点都缩进 gap
				const ratioStart = gap / len;
				const ratioEnd = (len - gap) / len;
				const sx = x1 + dx * ratioStart;
				const sy = y1 + dy * ratioStart;
				const tx = x1 + dx * ratioEnd;
				const ty = y1 + dy * ratioEnd;
				arr.push({
					x1: sx,
					y1: sy,
					x2: tx,
					y2: ty
				});
			}
			return arr;
		},
		arcPaths() {
			if (this.nodes.length < 2) return "";

			let path = `M ${this.nodes[0].x} ${this.nodes[0].y}`;

			for (let i = 1; i < this.nodes.length; i++) {
				const prev = this.nodes[i - 1];
				const curr = this.nodes[i];
				console.log("prev", prev);

				// 判断是否是行尾转折点
				const isTurnPoint = i % this.maxPerRow === 0;

				if (isTurnPoint) {
					// 计算半圆路径
					const radius = 10 / 2;
					if (prev.row % 2 === 0) {
						// 偶数行向右凸半圆
						path += ` 
              L ${prev.x + radius} ${prev.y}
              A ${radius} ${radius} 0 0 1 ${curr.x - radius} ${curr.y}
              L ${curr.x} ${curr.y}`;
					} else {
						// 奇数行向左凸半圆
						path += ` 
              L ${prev.x - radius} ${prev.y}
              A ${radius} ${radius} 0 0 0 ${curr.x + radius} ${curr.y}
              L ${curr.x} ${curr.y}`;
					}
				} else {
					// 同行节点间用直线连接
					path += ` L ${curr.x} ${curr.y}`;
				}
			}

			return path;
		},
		svgWidth() {
			return this.leftMargin + this.maxPerRow * this.nodeGapX + 50;
		},
		svgHeight() {
			// SVG高度
			return Math.ceil(this.dataList.length / this.maxPerRow) * this.nodeGapY + 40;
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}
.svg-timeline {
	width: 100%;
	// background-size: 100% 100%;
	// position: relative;
	// .title {
	//   position: absolute;
	//   top: 0;
	//   left: 32px;
	//   width: 100%;
	//   height: 100%;
	//   font-family: YouSheBiaoTiHei;
	//   font-size: 16px;
	//   color: #ffffff;
	//   line-height: 24px;
	//   background: linear-gradient(90deg, #ffffff 0%, #79c2ff 100%);
	//   -webkit-background-clip: text;
	//   -webkit-text-fill-color: transparent;
	//   display: flex;
	//   align-items: center;
	//   height: 40px;
	//   img {
	//     width: 12px;
	//     height: 24px;
	//   }
	// }
	
	.node-content {
		font-family: Microsoft YaHei, sans-serif;
		text-align: left;
		padding-left: 4px; 

		.date {
			color: rgb(5, 95, 194);
			font-weight: 700;
			font-size: 14px;
			line-height: 22px;
			margin-bottom: 0px; 
			margin-top: 6px;
		}

		.title {
			color: rgb(59, 65, 75);
			font-weight: 700;
			font-size: 14px;
			line-height: 22px;
			margin-bottom: 0px;
            white-space: nowrap;      /* Keep text on one line */
            overflow: hidden;         /* Hide overflow */
            text-overflow: ellipsis;  /* Show ... for overflow */
            width: 100%;              /* Ensure it takes full width of container */
            display: block;           /* Block level for ellipsis to work */
		}

		.votes {
			color: rgb(95, 101, 108);
			font-size: 14px;
            font-weight: 400;
            line-height: 22px;
		}
	}
}
</style>
