import { defineComponent, reactive, computed, toRef, ref } from "vue";
import styles from "./index.module.less"
import { headImg } from "../image";
import { headTopData } from "../index"
import { Switch, showToast, Field, Popup, Slider } from "vant";
import state, { refreshMusicSvg, IPlatform, checkMoveNoSave, handleGuide, resetCursorPosition } from "/src/state"
import { api_closeCamera, api_openCamera, api_savePicture } from "/src/helpers/communication";
import { smoothAnimationState} from "/src/page-instrument/view-detail/smoothAnimation"
import Recommendation from "../../custom-plugins/helper-model/recommendation";
import { resetRenderMusicScore } from "/src/view/music-score";
import ScreenModel from "../../custom-plugins/helper-model/screen-model";
import { getQuery } from "/src/utils/queryString";
import { reCheckDelay } from "/src/page-instrument/evaluat-model"
import { audioData, changeMingSongType } from "/src/view/audio-list"
import useDrag from "/src/view/plugins/useDrag/index";
import Dragbom from "/src/view/plugins/useDrag/dragbom";
import { storeData } from "/src/store";
import { getGuidance, setGuidance } from "../../custom-plugins/guide-page/api";
import { metronomeData } from "/src/helpers/metronome";

export default defineComponent({
	name: "settting",
	setup() {
        const query = getQuery();
        const helperData = reactive({
			screenModelShow: false, // 投屏帮助
			recommendationShow: false, // 建议
		});
        const zoomList = [{name:'默认',value: 0.8},{name:'1.25x',value: 1.25},{name:'1.5x',value: 1.5},{name:'1.75x',value: 1.75}] 
		const parentClassName = "recommenBoxClass_drag";
		const userId = storeData.user?.id ? String(storeData.user?.id) : "";
		const positionInfo =
		  state.platform !== IPlatform.PC
			? {
				styleDrag: { value: null },
			  }
			: useDrag([`${parentClassName} .top_draging`, `${parentClassName} .bom_drag`], parentClassName, toRef(helperData, "recommendationShow"), userId);


        // 加减评测频率
		const operateHz = (type: number) => {
			const minFrequency = state.baseFrequency - 10, maxFrequency = state.baseFrequency + 10
			let currentFrequency = state.setting.frequency
			if (type === 1) {
				if (currentFrequency - 1 < minFrequency) return showToast({ message: `最低标准音高${minFrequency}HZ` })
				currentFrequency = currentFrequency - 1
			} else {
				if (currentFrequency + 1 > maxFrequency) return showToast({ message: `最高标准音高${maxFrequency}HZ` })
				currentFrequency = currentFrequency + 1
			}
			state.setting.frequency = currentFrequency >= 0 ? currentFrequency : 0
		}
        const formatterTimeMs = (value: any) => value = String(Math.min(3000, value));

        const notationList = computed(() => {
            const list = state.enableNotation ? [{name:'五线谱',value:'staff'},{name:'首调',value:'firstTone'},{name:'固定调',value:'fixedTone'}] : [{name:'首调',value:'firstTone'},{name:'固定调',value:'fixedTone'}];
            return list;
        });

        const metronomeList = computed(() => {
            const list =  state.modeType === 'follow' ? [{name:'音符',value:1},{name:'关闭',value:3}] : [{name:'音符',value:1},{name:'节拍',value:2},{name:'关闭',value:3}];
            return list;
        });
       

		return () => (
			<div class={[styles.settting]}>
                <div class={[styles.head, "top_draging"]}>
					<img class={styles.headTit} src={headImg("settingName.png")} />
					<img class={styles.closeImg} src={headImg("closeImg.png")} onClick={()=>{ headTopData.settingMode = false }} />
				</div>
                <div class={styles.content}>
                    <div class={styles.conBox}>
                        {
                            state.isShowFingering && state.fingeringInfo.name && ["practise", "follow", "evaluating"].includes(state.modeType) && state.playType === "play" &&
                                <div class={styles.cellBox}>
                                <div class={styles.tit}>指法</div>
                                    <Switch v-model={state.setting.displayFingering}></Switch>
                                </div>
                        }
                        {
                            ["practise", "follow"].includes(state.modeType) &&                         
                                <div class={styles.cellBox}>
                                    <div class={styles.tit}>循环播放</div>
                                    <Switch v-model={state.setting.repeatAutoPlay}></Switch>
                                </div>
                        }                        
                        {/* {
                            state.isSingleLine && state.modeType === "practise" && !state.isCombineRender && !state.isPercussion && 
                                <div class={styles.cellBox}>
                                <div class={styles.tit}>旋律线</div>
                                    <Switch 
                                        v-model={smoothAnimationState.isShow.value}
                                        onChange={(value) => {
                                            state.melodyLine = value
                                        }}                                        
                                    ></Switch>
                                </div>   
                        } */}
                        <div class={styles.cellBox} style={{border:"none"}}>
                                <div class={styles.tit}>指针模式</div>
                                <div class={styles.radioBox}>
                                    {
                                        metronomeList.value.map(item=>{
                                            return <div class={ metronomeData.cursorMode===item.value && styles.active } onClick={ ()=>{
                                                if (metronomeData.cursorMode === item.value) {
                                                    return
                                                }
                                                 // 切换光标模式
                                                metronomeData.cursorMode = item.value
                                                resetCursorPosition()
                                            }}>{item.name}</div>
                                        })
                                    }
                                </div>
                        </div>
                        <div class={styles.pointerCon}>
                            <div class={styles.pointerBox}>
                                <div>音符：指针跟随音符播放</div>
                                {
                                    state.modeType !== 'follow' && <div>节拍：指针跟随节拍播放</div>
                                }
                                <div>关闭：不显示指针</div>
                            </div>
                        </div>
                        {
                            state.modeType === 'practise' && state.playType === "sing" && state.mingSong && state.mingSongGirl &&
                            <div class={styles.cellBox}>
                                <div class={styles.tit}>唱名类型</div>
                                <div class={styles.radioBox}>
                                    {
                                        [{name:'男声',value:1}, {name:'女声',value:0}].map(item=>{
                                            return <div class={ audioData.mingSongType===item.value && styles.active } onClick={ ()=>{ 
                                                if(audioData.mingSongType === item.value){
                                                    return
                                                }
                                                audioData.mingSongType = item.value as 0|1
                                                changeMingSongType()
                                            } }>{item.name}</div>
                                        })
                                    }
                                </div>
                            </div>                     
                        }                        
                        {
                            state.modeType === "evaluating" && 
                            <>                       
                                {
                                    (!query.workRecord && !query.evaluatingRecord) &&                                 
                                    <div class={styles.cellBox}>
                                        <div class={styles.tit}>评测难度</div>
                                        <div class={styles.radioBox}>
                                            {
                                                [{name:'入门',value:"BEGINNER"},{name:'进阶',value:"ADVANCED"},{name:'大师',value:"PERFORMER"}].map(item=>{
                                                    return <div class={ state.setting.evaluationDifficulty===item.value && styles.active } onClick={ ()=>{
                                                        state.setting.evaluationDifficulty = item.value as any
                                                    } }>{item.name}</div>
                                                })
                                            }
                                        </div>
                                    </div>   
                                }                     
                                <div class={styles.cellBox}>
                                    <div class={styles.tit}>延迟检测</div>
                                    {/* <Switch v-model={state.setting.soundEffect}></Switch> */}
                                    <div class={styles.titbtn} onClick={() => {
                                        reCheckDelay();
                                    }}>重新检测</div>
                                </div> 
                                <div class={[styles.cellBox, state.setting.camera && styles.isCamera]}>
                                    <div class={styles.tit}>摄像头</div>
                                    <Switch 
                                        // v-model={state.setting.camera}
                                        modelValue={state.setting.camera}
                                        onChange={ async (value) => {
                                            if (value) {
                                                const res = await api_openCamera();
                                                // 没有授权
                                                if (res?.content?.reson) {
                                                    state.setting.camera = false
                                                } else {
                                                    state.setting.camera = true
                                                }
                                            } else {
                                                api_closeCamera();
                                                state.setting.camera = false;
                                            }
                                        }}                                
                                    ></Switch>
                                </div>   
                                <div class={styles.cellBox} style={{ display: state.setting.camera ? "" : "none" }}>
                                    <div class={styles.tit}>不透明度</div>
                                    <div class={styles.spendCon}>
                                        <div class={styles.sliderCon}>
                                            <Slider class={styles.slider} max={100} min={0} v-model={state.setting.cameraOpacity}>
                                                {{
                                                    button: () => 
                                                    <div class={styles.customButton}>
                                                        <div class={styles.speedVal}>{ state.setting.cameraOpacity }</div>
                                                        <div class={styles.speedBtn}></div>
                                                    </div>
                                                }}
                                            </Slider>
                                        </div>
                                    </div>
                                </div>                                                                     
                                <div class={styles.cellBox}>
                                    <div class={styles.tit}>标准音高</div>
                                    <div class={styles.frequency}>
                                        <img src={headImg("cutImg.png")} class={[styles.btn]} onClick={() => operateHz(1)} />
                                        <div class={styles.frequencyNum}>{state.setting.frequency}HZ</div>
                                        <img src={headImg("addImg.png")} class={[styles.btn]} onClick={() => operateHz(2)} />
                                    </div>
                                </div>                        
                                <div class={styles.cellBox}>
                                    <div class={styles.tit}>反应时间</div>
                                    <div class={styles.reactionTimeBox}>
                                        <Field class={styles.reactionTime} type="digit" 
                                            placeholder="最大可输入3000毫秒"
                                            formatter={formatterTimeMs}
                                            input-align={'center'}
                                            v-model:modelValue={state.setting.reactionTimeMs} />
                                        <div class={styles.timeName}>毫秒</div>    
                                    </div>
                                </div>
                            </>
                        }
                        {/** 练习模式才有单行/多行谱切换功能，跟练、评测只有单行谱模式 */}
                        {
                            ["practise", "evaluating"].includes(state.modeType) ? 
                            <div class={styles.cellBox}>
                                <div class={styles.tit}>切换谱面</div>
                                <div class={styles.radioBox}>
                                    {
                                        [{name:'单行谱',value:true},{name:'多行谱',value:false}].map(item=>{
                                            return <div class={ state.isSingleLine===item.value && styles.active } onClick={ async ()=>{ 
                                                if(state.isSingleLine === item.value){
                                                    return
                                                }
                                                await checkMoveNoSave();
                                                headTopData.settingMode = false
                                                // resetRenderMusicScore(state.musicRenderType)
                                                const _time = setTimeout(() => {
                                                    state.isSingleLine = item.value 
                                                    clearTimeout(_time)
                                                    refreshMusicSvg();
                                                }, 100);
                                                // musicScoreRef.value?.refreshMusicScore()
                                            } }>{item.name}</div>
                                        })
                                    }
                                </div>
                            </div> : null                        
                        }
                        {
                            state.enableNotation || state.specialShowNotation ? 
                            <div class={styles.cellBox}>
                                <div class={styles.tit}>转谱</div>
                                <div class={styles.radioBox}>
                                    {
                                        notationList.value.map(item=>{
                                            return <div class={ state.musicRenderType===item.value && styles.active } onClick={ async ()=>{ 
                                                if(state.musicRenderType === item.value){
                                                    return
                                                }
                                                await checkMoveNoSave();
                                                headTopData.settingMode = false
                                                // resetRenderMusicScore(state.musicRenderType)
                                                const _time = setTimeout(() => {
                                                    state.musicRenderType = item.value as any
                                                    clearTimeout(_time)
                                                    refreshMusicSvg();
                                                }, 100);
                                            } }>{item.name}</div>
                                        })
                                    }
                                </div>
                            </div> : null
                        }
                        {
                            <div class={styles.cellBox}>
                                <div class={styles.tit}>谱面大小</div>
                                <div class={[styles.radioBox, styles.speBox]}>
                                    {
                                        zoomList.map(item=>{
                                            return <div class={ state.zoom===item.value && styles.active } onClick={ async ()=>{ 
                                                if(state.zoom === item.value){
                                                    return
                                                }
                                                await checkMoveNoSave();
                                                headTopData.settingMode = false
                                                // resetRenderMusicScore(state.musicRenderType)
                                                const _time = setTimeout(() => {
                                                    state.zoom = item.value as any
                                                    localStorage.setItem('scoreZoom',String(state.zoom))
                                                    clearTimeout(_time)
                                                    refreshMusicSvg();
                                                }, 100);
                                            } }>{item.name}</div>
                                        })
                                    }
                                </div>
                            </div>
                        }
                        <div class={styles.cellBtnBox}>
                            <img  src={headImg("tpbz.png")} onClick={() => (helperData.screenModelShow = true)} />
                            {
                                !query.isCbs && <img  src={headImg("yjfk.png")} onClick={() => (helperData.recommendationShow = true)} />
                            }
                        </div>
                    </div>  
                </div>
                <Popup
					v-model:show={helperData.recommendationShow}
					class="popup-custom van-scale center-closeBtn recommenBoxClass_drag"
					transition="van-scale"
					teleport="body"
                    overlay-style={{background:'rgba(0, 0, 0, 0.7)'}}
                    style={positionInfo.styleDrag.value}
				>
                    <Recommendation
                        onClose={() => {
                            helperData.recommendationShow = false;
                        }}
                    />
                    {state.platform === IPlatform.PC && <Dragbom showGuide={!state.guideInfo?.teacherDrag} onGuideDone={handleGuide} />}
				</Popup>
                <Popup
					class={["popup-custom"]}
					v-model:show={helperData.screenModelShow}
					onClose={() => {
						helperData.screenModelShow = false;
					}}
					position="right"
					teleport="body"
				>
					<ScreenModel
						onClose={(open: Boolean) => {
							helperData.screenModelShow = false;
						}}
					/>
				</Popup>
			</div>
		);
	},
});
