import { defineComponent, Directive, Ref, ref, Transition, Teleport, nextTick, computed, onMounted } from 'vue'
import { Button, Cell, CellGroup, Dialog, Divider, Popover, Slider, Switch } from 'vant'
import ButtonIcon from './icon'
import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
import Speed from '/src/pages/detail/speed'
import detailState from '/src/pages/detail/state'
import SettingState from '/src/pages/detail/setting-state'
import appState from '/src/state'
import FloatWraper from './float-wraper'
import Evaluating from './evaluating'
import iconTitle from '../popups/evaluating/icons/title.svg'
import iconCancel from '../popups/evaluating/icons/cancel.svg'
import iconConfirm from '../popups/evaluating/icons/confirm.svg'
import { useClientType, useMenu, useOriginSearch, useWiredHeadsetCheck, useReload } from '../uses'
import { permissionPopup } from '../popups/permission/permission'
import { open as openMusicList } from '../music-list'
import { postMessage } from '/src/helpers/native-message'
import Popups from '../popups'
import Setting from '../popups/setting'
import evastyles from '../popups/evaluating/index.module.less'
import ModelWraper from './model-wraper'
import Follow from '../popups/follow'
import { switchProps } from '../popups/setting/evaluat'
import iconFollowEndBtn from '../popups/follow/icons/icon-followEndBtn.png'
import iconEvaluatingEnd from './icons/icon-evaluatingEnd.png'
import store from 'store'
import { useRoute } from 'vue-router'
import styles from './index.module.less'
export const confirmShow: Ref<boolean> = ref(false)


export const startButtonShow = ref(true)

export const evaluatingRef: Ref<any> = ref({})
export const settingPopup: Ref<any> = ref(null)
export const suggestPopup: Ref<any> = ref(null)
export const followRef = ref<any>(null)

let openSuggestPopupFn = () => {}

export const openSuggestPopup = () => {
  openSuggestPopupFn()
}

export const animate: Directive = {
  mounted: (el: HTMLElement) => {
    el.addEventListener('click', (evt: Event) => {
      let element = evt.target as HTMLElement
      element.classList.add(...['animate__animated', 'animate__tada'])
    })
    el.addEventListener('animationend', (evt: Event) => {
      let element = evt.target as HTMLElement
      element.classList.remove(...['animate__animated', 'animate__tada'])
    })
  },
}

/**
 * 前置验证是否在APP中并且已经付费
 * @param cb 回调函数 {status} 验证状态
 * @returns
 */
const beforeCheck = (cb: (status: boolean) => void) => {
  const search = useOriginSearch()
  const setting = (search.setting || {}) as any
  const chargeType = detailState.activeDetail?.paymentType
  const orderStatus = detailState.activeDetail?.orderStatus
  const play = detailState.activeDetail?.play
  const membershipDays = appState.user?.membershipDays || 0
  if (useClientType() === 'web' || play || setting.feeType === 'FREE') {
    return cb(true)
  }
  if (
    chargeType?.includes('VIP') &&
    chargeType?.includes('CHARGE') &&
    !(membershipDays > 0) &&
    orderStatus !== 'PAID'
  ) {
    permissionPopup.active = 'memberAndDemand'
    permissionPopup.show = true
    return cb(false)
  }
  if (chargeType === 'VIP' && !(membershipDays > 0)) {
    permissionPopup.active = 'member'
    permissionPopup.show = true
    return cb(false)
  }
  if (chargeType === 'CHARGE' && orderStatus !== 'PAID') {
    permissionPopup.active = 'demand'
    permissionPopup.show = true
    return cb(false)
  }
  cb(true)
}

const back: () => void = () => {
  postMessage({
    api: 'back',
  })
}
const startEvaluat = () => {
  console.log('开始评测')
  runtime.evaluatingStatus = true
  RuntimeUtils.setCurrentTime(0)
  // beforeCheck((status) => {
  //   if (status) {
  //     RuntimeUtils.setCurrentTime(0)
  //     runtime.evaluatingStatus = true
  //   }
  // })
}
export type IModelType = 'practice' | 'evaluation' | 'follow' | 'init'
export const modelType = ref<IModelType>('init')
const modelWraperShow = ref(true)
export const onChangeModelType = (type: IModelType) => {
  modelWraperShow.value = false
  if (type === modelType.value) return
  if (type === 'evaluation') {
    RuntimeUtils.changeSpeed(detailState.activeDetail?.originalSpeed, false)
    // 评测模式
    startEvaluat()
  } else {
    const speeds = store.get('speeds') || {}
    const search = useOriginSearch()
    const speed = speeds[search.id as any]
    // 还原速度
    if (speed) {
      RuntimeUtils.changeSpeed(speeds[search.id as any])
    }
  }
  nextTick(() => {
    modelType.value = type
  })
}

export default defineComponent({
  name: 'Colexiu-Buttons',
  directives: { animate },
  props: {
    onSetMusicScoreType: {
      type: Function,
      default: (n: any) => {},
    },
  },
  emits: ['setMusicScoreType'],
  setup(props, { emit }) {
    const search = useOriginSearch()
    const route = { query: search }
    const [wiredStatus] = useWiredHeadsetCheck()
    const speedRef = ref()
    const [show] = useMenu()
    const camera = ref(false)

    //根据路由传参设置模式
    const useRouteSetModelType = () => {
      if (route.query.modelType) {
        // onChangeModelType(route.query.modelType as IModelType)
      }
    }
    onMounted(() => {
      useRouteSetModelType()
    })

    // 固定调
    const musicTypeShow = ref(false)
    const musicAction = ref('')
    const onSelect = (action: any) => {
      musicAction.value = action.text
      confirmShow.value = true
    }
    const hanldeSelect = () => {
      if (musicAction.value === '五线谱') {
        // if (SettingState.sett.type == 'staff') return
        SettingState.sett.type = 'staff'
      } else if (musicAction.value === '简谱') {
        // if (SettingState.sett.type === 'jianpu' && !SettingState.sett.keySignature) return
        SettingState.sett.type = 'jianpu'
        SettingState.sett.keySignature = false
      } else if (musicAction.value === '固定调') {
        // if (SettingState.sett.type === 'jianpu' && SettingState.sett.keySignature) return
        SettingState.sett.type = 'jianpu'
        SettingState.sett.keySignature = true
      }
    }
    const musicType = (type: string) => {
      if (type === 'staff') {
        return SettingState.sett.type === type
      } else if (type === 'shoudiao') {
        return SettingState.sett.type === 'jianpu' && !SettingState.sett.keySignature
      } else if (type === 'guding') {
        return SettingState.sett.type === 'jianpu' && SettingState.sett.keySignature
      }
    }

    return () => {
      const changeModeIsDisabled =
        (detailState.activeDetail?.isAppPlay
          ? detailState.activeDetail?.midiUrl === ''
          : runtime.isFirstPlay || runtime.audiosInstance?.length == 1) ||
        runtime.evaluatingStatus ||
        (detailState.activeDetail?.isAppPlay && detailState.midiPlayIniting)
      return (
        <div
          class={[
            styles.container,
            show.value ? 'animate__animated animate__fadeInDown' : 'animate__animated animate__fadeOutUp',
          ]}
          style={
            route.query.headerHeight
              ? {
                  paddingTop: route.query.headerHeight + 'px',
                }
              : {}
          }
        >
          <div class={styles.leftButton}>
            {!route.query?.modelType && (
              <Button class={[styles.button, styles.backbtn]} onClick={back}>
                <ButtonIcon name="icon-back" />
              </Button>
            )}
            <div class={styles.titleWrap}>
              <div class={styles.title}>{detailState.activeDetail?.musicSheetName}</div>
              {search.albumName && <div class={styles.album}>{search.albumName}</div>}
            </div>
          </div>

          <div class={styles.centerButton}>
            <Transition name="finish">
              {wiredStatus.value && !evaluatingRef.value?.connentLoading && !startButtonShow.value && (
                <Button
                  style={{ backgroundImage: `url(${iconEvaluatingEnd})` }}
                  class={[styles.button, styles.finish]}
                  onClick={() => {
                    evaluatingRef.value?.playerStop?.()
                  }}
                ></Button>
              )}

              {followRef?.value?.data.start && (
                <Button
                  style={{ backgroundImage: `url(${iconFollowEndBtn})` }}
                  class={[styles.button, styles.finish, styles.followEndBtn]}
                  onClick={() => {
                    followRef.value?.handleEnd?.()
                  }}
                ></Button>
              )}
            </Transition>
          </div>
          <div class={[styles.moreButton]} style={{ opacity: detailState.initRendered ? 1 : 0 }}>
            {/* route.query?.modelType 就不显示模式按钮  */}
            {route.query?.modelType == 'practice' && modelType.value !== 'init' && !detailState.frozenMode && (
              <Button
                data-step="m1"
                class={[styles.button, styles.hasText]}
                disabled={(runtime.evaluatingStatus && !startButtonShow.value) || followRef.value?.data.start}
                onClick={() => {
                  if (modelType.value === 'practice') {
                    // 当前为练习模式,需要停止播放
                    RuntimeUtils.resetPlayStatus()
                    RuntimeUtils.setCurrentTime(0)
                  }
                  if (modelType.value === 'evaluation') {
                    runtime.evaluatingStatus = false
                    if (
                      evaluatingRef.value?.playStatus.value === 'play' ||
                      evaluatingRef.value?.playStatus.value === 'connecting'
                    ) {
                      evaluatingRef.value?.cancelTheEvaluation()
                    }
                  }
                  modelType.value = 'init'
                  modelWraperShow.value = true
                }}
              >
                <ButtonIcon
                  key="modelType"
                  name={
                    ['init', 'practice'].includes(modelType.value)
                      ? 'modelType'
                      : ['follow'].includes(modelType.value)
                      ? 'modelType1'
                      : 'modelType2'
                  }
                />
                <span>模式</span>
              </Button>
            )}
            {modelType.value === 'evaluation' && (
              <>
                <Popover
                  v-model:show={camera.value}
                  overlay={false}
                  placement="bottom-end"
                  class="cameraPopover"
                  show-arrow={false}
                  vSlots={{
                    reference: () => (
                      <div>
                        <Button class={[styles.button, styles.hasText]}>
                          <ButtonIcon key="camera" name="camera" />
                          <span>摄像头</span>
                        </Button>
                      </div>
                    ),
                  }}
                >
                  <CellGroup border={false}>
                    {
                      <Cell center title="摄像头">
                        <div style="display:flex;justify-content: flex-end;">
                          <Switch disabled={!startButtonShow.value} v-model={SettingState.sett.camera} {...switchProps}>
                            off
                          </Switch>
                        </div>
                      </Cell>
                    }
                    {SettingState.sett.camera && (
                      <Cell class="cameraOpacity" center title="透明度">
                        <Slider
                          min={0}
                          max={100}
                          v-model:modelValue={SettingState.sett.opacity}
                          v-slots={{
                            button: () => <div class={styles.slider}>{SettingState.sett.opacity}</div>,
                          }}
                        ></Slider>
                      </Cell>
                    )}
                  </CellGroup>
                </Popover>

                <div style={{ display: 'none' }}>
                  {!runtime.evaluatingStatus ? (
                    <Button class={[styles.button, styles.hasText]} onClick={startEvaluat}>
                      <ButtonIcon key="evaluating" name="evaluating" />
                      <span>评测</span>
                    </Button>
                  ) : (
                    <Evaluating ref={evaluatingRef} key="lianxi" />
                  )}
                </div>
              </>
            )}

            {modelType.value === 'practice' && (
              <>
                <Button
                  data-step="m2"
                  class={[styles.button, styles.hasText]}
                  onClick={() => RuntimeUtils.changeMode(runtime.mode === 'background' ? 'music' : 'background')}
                  disabled={changeModeIsDisabled}
                >
                  <ButtonIcon key="music" name={runtime.mode === 'music' ? 'music' : 'accompaniment'} />
                  <span>{runtime.mode === 'background' ? '伴奏' : '原声'}</span>
                </Button>
                <Button
                  data-step="m3"
                  class={[styles.button, styles.hasText]}
                  onClick={RuntimeUtils.sectionChange}
                  disabled={runtime.evaluatingStatus}
                >
                  <ButtonIcon
                    key="section"
                    name={
                      'section' +
                      (detailState.section.length && detailState.section.length <= 2 ? detailState.section.length : '')
                    }
                  />
                  <span>选段</span>
                </Button>
                <Button
                  data-step="m4"
                  class={[styles.button, styles.hasText]}
                  onClick={() => {
                    SettingState.sett.fingering = !SettingState.sett.fingering
                    RuntimeUtils.event.emit('settingFingeringChange')
                  }}
                >
                  <ButtonIcon key="music" name={SettingState.sett.fingering ? 'fingeringOn' : 'fingeringOff'} />
                  <span>指法</span>
                </Button>
              </>
            )}
            {['practice', 'evaluation'].includes(modelType.value) && (
              <Popover
                trigger="manual"
                overlay={false}
                placement="bottom"
                class={styles.popover}
                show={show.value && runtime.speedShow && !(runtime.evaluatingStatus || runtime.playState === 'play')}
                // @ts-ignore
                onUpdate:show={(show: boolean) => (runtime.speedShow = show)}
                vSlots={{
                  reference: () => (
                    <Button
                      data-step="m5"
                      class={[styles.button, styles.hasText, styles.speedButton]}
                      disabled={runtime.evaluatingStatus || runtime.playState === 'play'}
                      onClick={() => {
                        speedRef.value?.refUpdateSpeed(runtime.speed)
                        runtime.speedShow = !runtime.speedShow
                      }}
                    >
                      <ButtonIcon name="speed" />
                      <span>速度</span>
                      <span class={styles.label}>{runtime.speed}</span>
                    </Button>
                  ),
                }}
              >
                <Speed
                  ref={speedRef}
                  updateSpeed={(speed: number) => (runtime.speed = speed)}
                  changed={RuntimeUtils.changeSpeed}
                  mode={runtime.mode}
                  changeMode={RuntimeUtils.changeMode}
                  lib={{ speed: runtime.speed }}
                  class={styles.speed}
                />
              </Popover>
            )}
            {detailState.activeDetail?.notation ? (
              <Popover
                class={styles.toggleMusicType}
                placement="bottom-end"
                show={musicTypeShow.value}
                onUpdate:show={(val: boolean) => {
                  if (
                    runtime.playState === 'play' ||
                    (runtime.evaluatingStatus && !startButtonShow.value) ||
                    followRef.value?.data.start
                  ) {
                  } else {
                    musicTypeShow.value = val
                  }
                }}
              >
                {{
                  reference: () => (
                    <Button
                      disabled={
                        runtime.playState === 'play' ||
                        (runtime.evaluatingStatus && !startButtonShow.value) ||
                        followRef.value?.data.start
                      }
                      class={[styles.button, styles.hasText, styles.speedButton]}
                    >
                      <ButtonIcon name="icon-zhuanpu" />
                      <span>{musicType('staff') ? '转简谱' : '转五线谱'}</span>
                    </Button>
                  ),
                  default: () => (
                    <>
                      <div role="menuitem" class="van-popover__action" onClick={() => onSelect({ text: '五线谱' })}>
                        <ButtonIcon key="type" name={musicType('staff') ? 'icon-staff-active' : 'icon-staff'} />
                        <div class={['action-text', musicType('staff') && 'action-active']}>五线谱</div>
                      </div>
                      <div role="menuitem" class="van-popover__action" onClick={() => onSelect({ text: '简谱' })}>
                        <ButtonIcon key="type" name={musicType('shoudiao') ? 'shuodiao-active' : 'shuodiao'} />
                        <div class={['action-text', musicType('shoudiao') && 'action-active']}>首调</div>
                      </div>
                      <div role="menuitem" class="van-popover__action" onClick={() => onSelect({ text: '固定调' })}>
                        <ButtonIcon key="type" name={musicType('guding') ? 'guding-active' : 'guding'} />
                        <div class={['action-text', musicType('guding') && 'action-active']}>固定调</div>
                      </div>
                    </>
                  ),
                }}
              </Popover>
            ) : null}

            {detailState.initRendered && (
              <>
                <Button
                  class={[styles.button, styles.hasText]}
                  onClick={() => {
                    settingPopup.value?.onShow()
                  }}
                  disabled={runtime.evaluatingStatus && !startButtonShow.value}
                >
                  <ButtonIcon name="setting" />
                  <span>设置</span>
                </Button>
                <Popups
                  ref={settingPopup}
                  style={{
                    borderRadius: '8px',
                  }}
                >
                  <Setting active={modelType.value == 'practice' ? '2' : modelType.value == 'evaluation' ? '3' : '1'} />
                </Popups>
              </>
            )}

            {modelType.value === 'follow' && (
              <>
                <Follow ref={followRef} />
              </>
            )}
          </div>

          {/* <Teleport to="body">
            {!route.query?.modelType && modelType.value !== 'evaluation' && (
              <div class={styles.btnMusicList} onClick={openMusicList}>
                <ButtonIcon name="music-list1" />
              </div>
            )}
          </Teleport> */}

          {detailState.initRendered && !detailState.frozenMode && (
            <ModelWraper show={modelWraperShow.value} onChangeModelType={onChangeModelType} />
          )}
          <FloatWraper />
          <Dialog.Component
            teleport="body"
            class={evastyles.confirm}
            style={{
              overflow: 'initial',
            }}
            vSlots={{
              title: () => <img class={evastyles.iconTitle} src={iconTitle} />,
              footer: () => (
                <div class={evastyles.footer}>
                  <img src={iconCancel} onClick={() => (confirmShow.value = false)} />
                  <img
                    src={iconConfirm}
                    onClick={() => {
                      hanldeSelect()
                      useReload()
                    }}
                  />
                </div>
              ),
            }}
            v-model:show={confirmShow.value}
            message={'设置成功，是否立即重新加载？'}
          />
        </div>
      )
    }
  },
})
