import { defineComponent, onMounted, onUnmounted, reactive } from "vue";
import styles from "./index.module.less";

export default defineComponent({
	name: "Keys",
	emits: ["click"],
	props: {
		show: {
			type: Boolean,
			default: false,
		},
	},
	setup(props, { emit }) {
		const data = reactive({
			keys: [
				{ key: "C", singname: "do", type: "white" },
				{ key: "D", singname: "re", type: "white" },
				{ key: "E", singname: "mi", type: "white" },
				{ key: "F", singname: "fa", type: "white" },
				{ key: "G", singname: "so", type: "white" },
				{ key: "A", singname: "la", type: "white" },
				{ key: "B", singname: "si", type: "white" },
			],
			keyDown: "",
		});
		/** 赤橙黄露青蓝紫 */
		const colors = ["#F07C83", "#FF966C", "#FBB957", "#A7DCBF", "#CCCCD6", "#A5D2FF", "#B0A4F4"];
		const productKey = (total = 0) => {
			return new Array(Math.abs(total)).fill(total > 0 ? "'" : ",").join("");
		};

		const keyDown = (e: KeyboardEvent) => {
			data.keyDown = e.key.toLocaleUpperCase();
		};
		const keyUp = (e: KeyboardEvent) => {
			data.keyDown = "";
		};
		onMounted(() => {
			document.addEventListener("keydown", keyDown);
			document.addEventListener("keyup", keyUp);
		});
		onUnmounted(() => {
			document.removeEventListener("keydown", keyDown);
			document.removeEventListener("keyup", keyUp);
		});
		return () => (
			<div class={[styles.piano, props.show && styles.show]}>
				{new Array(7).fill(0).map((_, index) => (
					<div class={styles.pianoItemWrap}>
						{data.keys.map((item) => {
							return (
								<div
									class={[styles.item, index === 3 && data.keyDown === item.key && styles.keyDown]}
									key={index}
									onClick={() => {
										let key = index > 3 ? item.key.toLocaleLowerCase() : item.key;
										emit("click", {
											type: "note",
											value: key + productKey([3, 4].includes(index) ? 0 : index - 3),
										});
									}}
								>
									<div class={styles.keytip}>
										<div style={{ color: "#ff4a00" }}>
											{index === 3 && item.key === "C" ? "中央C" : ""}
										</div>
										<div class={styles.keyname}>
											{item.key}
											{index + 1}
										</div>
										<div class={styles.singname} style={{ background: colors[index] }}>
											{item.singname}
										</div>
									</div>
								</div>
							);
						})}
						<div class={styles.bkeyWrap}>
							{data.keys.map((item) => {
								if (item.key === "E" || item.key === "B") return null;
								return (
									<div
										class={styles.bkey}
										onClick={() => {
											let key = index > 3 ? item.key.toLocaleLowerCase() : item.key;
											emit("click", {
												type: "note",
												value: key + productKey([3, 4].includes(index) ? 0 : index - 3) + "-" + "^",
											});
										}}
									>
										<div class="keytip"></div>
									</div>
								);
							})}
						</div>
					</div>
				))}
			</div>
		);
	},
});
