import { computed, defineComponent, ref, watch } from "vue";
import { Switch, Slider } from "vant";
import styles from "./index.module.less"
import { headData } from "../index" 
import { headImg } from "../image";
import state, { handleSetSpeed, resetBaseRate } from "../../../state";
import { metronomeData } from "../../../helpers/metronome"; 
import { getQuery } from "/src/utils/queryString";
import { api_createMusicPlayer, api_updateMusicPlayer, api_checkSocketStatus } from "/src/helpers/communication";
import { storeData } from "/src/store";
import { data as workData } from "/src/page-instrument/custom-plugins/work-index";

export default defineComponent({
	name: "speed",
	setup() {
		const speed = ref(state.speed);
		const switchLoading = ref(false);
		const query: any = getQuery();
		const minusSpeed = () => {
			let canSpeed = Math.max(speed.value - 1, 45);
			canSpeed = Math.min(canSpeed, 270);
			speed.value = canSpeed;
		};

		const plusSpeed = () => {
			let canSpeed = Math.min(speed.value + 1, 270);
			canSpeed = Math.max(canSpeed, 45);
			speed.value = canSpeed;
		};
		// 重置当前小节的速度
		const resetCurrentSpeed = () => {
			resetBaseRate(state.activeNoteIndex);
		};
		watch(
			() => speed.value,
			() => {
				// handleSetSpeed(speed.value);
				// state.speed = Math.floor(speed.value);
				state.speed = speed.value
				// handleSetSpeed(speed.value);
				if (state.playState === 'paused') {
					// const currentItem: any = (state.sectionStatus && state.section.length === 2) ? state.sectionFirst || state.section[0] : state.times[state.activeNoteIndex];
					const currentItem: any = state.times[state.activeNoteIndex];
					state.basePlayRate = currentItem?.measureSpeed ? state.speed / currentItem.measureSpeed : state.speed / state.originSpeed;
				}
			}
		);
		watch(
			() => state.speed,
			() => {
				if (speed.value !== state.speed) {
					speed.value = state.speed;
				}
			}
		);
		const metronomeDisable = computed({
			get(){
				return !metronomeData.disable
			},
			set(val){
				metronomeData.disable = !val
			}
		})
		// 切换节拍器
		const toggleSwitch = async (res: any) => {
			metronomeDisable.value = res;
			return
			switchLoading.value = true;
			try {
			  if (storeData.isApp && state.enableEvaluation) {
				// 加载弹窗的开始时间
				let startTime = +new Date();
				state.loadingText = res ? '节拍器准备中，请稍等…' : '节拍器关闭中，请稍等…';
				state.isLoading = true;
				const targetSrc = res ? state.beatSong.accompany || state.beatSong.music : state.accompany || state.music;
				const resData = await api_updateMusicPlayer({
					musicSrc: targetSrc || state.accompany || state.music, // 曲谱音频url，有可能含节拍器的音频不存在
					tuneSrc: "https://oss.dayaedu.com/MECMP/1722593665681.mp3", //效音音频url
					checkFrequence: 496,
				})
				// console.log('切换节拍器音频',resData)
				if (resData?.content) {
					// 返回结果的时间
					let intervalTime = +new Date() - startTime;
					// 超过1秒直接关闭加载弹窗，小于1秒则最短显示1秒加载弹窗
					if (intervalTime >= 1000) {
						state.isLoading = false;
						metronomeDisable.value = res;
						switchLoading.value = false;
					} else {
						const continueTime = 1000 - intervalTime;
						setTimeout(() => {
							state.isLoading = false;
							metronomeDisable.value = res;
							switchLoading.value = false;
						}, 1200);
					}
				}
				// api_checkSocketStatus();
			  } else {
				metronomeDisable.value = res;
				switchLoading.value = false;
			  }
			} catch (error) {
			  console.log(error)
			} finally {
				// state.isLoading = false;
				// switchLoading.value = false;
			}
		};
		return () => (
			<div class={[styles.speedContainer, !(state.isMixBeat && state.modeType !== "evaluating") && styles.isHideBeat]}>
				<div class={[styles.head, "top_draging"]}>
					<img class={styles.headTit} src={headImg("headTit.png")} />
					<img class={styles.closeImg} src={headImg("closeImg.png")} onClick={()=>{ headData.speedShow = false }} />
				</div>
				<div class={styles.content}>
					<div class={styles.conBox}>
						<div class={styles.tit}>速度</div>
						<div class={[styles.spendCon, (workData.trainingType === "PRACTICE" || workData.trainingType === "EVALUATION") && styles.disableSpend]}>
							<img src={headImg("cutImg.png")} class={[styles.btn]} onClick={minusSpeed} />
							<div class={styles.sliderCon}>
								<Slider class={styles.slider} max={270} min={speed.value < 45 ? speed.value : 45} v-model={speed.value}>
									{{
										button: () => 
										<div class={styles.customButton}>
											<div class={styles.speedVal}>{ Math.floor(speed.value) }</div>
											<div class={styles.speedBtn}></div>
										</div>
									}}
								</Slider>
							</div>
							<img src={headImg("addImg.png")} class={[styles.btn]} onClick={plusSpeed} />	
						</div>
						<div class={[styles.speedSel, (workData.trainingType === "PRACTICE" || workData.trainingType === "EVALUATION") && styles.disableSpend]}>
							<div onClick={resetCurrentSpeed}>原速</div>
							{[60,70,80,90,100,110,120,130,140,150,160].map((item) => (
								<div onClick={()=>{ speed.value = item }}>{item}</div>
							))}
						</div>
						{
							state.isMixBeat && state.modeType !== "evaluating" && !state.isAppPlay &&
							<div class={styles.metronome}>
								<div class={styles.tit}>节拍器</div>
								<Switch 
									class={switchLoading.value ? styles.switchLoading : ''}
									v-model:modelValue={metronomeDisable.value} 
									loading={switchLoading.value}
									onChange={toggleSwitch}
								></Switch>
							</div>
						}
					</div>
				</div>
			</div>
		);
	},
});
