import { PropType, computed, defineComponent, ref, toRefs, onMounted, watch, nextTick } from 'vue'
import { Picker, Button, Icon } from 'vant'
import styles from './index.module.less'
import state, { IPlatform, checkMoveNoSave } from "/src/state";
import changeName from "./imgs/changeName.png"
import { headImg } from "/src/page-instrument/header-top/image";
import { toggleMusicSheet } from "../index"
import okBtn from "./imgs/okBtn.png"

export default defineComponent({
  name: 'choosePartName',
  props: {
    partListNames: {
      type: Array as PropType<any[]>,
      default: () => [],
    },
    partIndex: {
      type: Number,
      default: 0,
    },
  },
  emits: ['close'],
  setup(props, { emit }) {
    const selValues = ref([props.partIndex]);
    const myPicker = ref();
    watch(
      () => toggleMusicSheet.show,
      () => {
        if (toggleMusicSheet.show) {
          selValues.value = [props.partIndex]
        }
      }
    );
    watch(() => toggleMusicSheet.show, ()=>{
        // 支持滚轮事件
        if (toggleMusicSheet.show) {
          nextTick(() => {
            myPicker.value.$el.addEventListener('wheel', handleWheel)
          })
        } else {
            myPicker.value.$el.removeEventListener('wheel', handleWheel)
        }
      },{immediate:true}
    )
    function handleWheel(e: WheelEvent){
      e.preventDefault()
      // 先停止 惯性滚动
      myPicker.value.confirm()
      const direction = e.deltaY > 0 ? 1 : -1
      const targetObject = myPicker.value.getSelectedOptions(0)[0]
      const index = props.partListNames.findIndex(
          obj => obj == targetObject
      )
      const newIndex = index + direction
      if (newIndex >= 0 && newIndex < props.partListNames.length) {
        selValues.value = [props.partListNames[newIndex].value]
      }
    }
    return () => (
      <div class={[styles.container, state.platform === IPlatform.PC && styles.pcContainer, styles[state.modeType]]}>
        <div class={[styles.head, "top_draging"]}>
          <img class={styles.headTit} src={changeName} />
          <img class={styles.closeImg} src={headImg("closeImg.png")} onClick={() => emit("close")} />
        </div>
        <div class={styles.pickerCon}>
          <div class={styles.pickerBox}>
            <Picker
              ref={myPicker}
              class={[styles.picker, state.platform === IPlatform.PC && styles.pcPicker]}
              v-model={selValues.value}
              showToolbar={false}
              columns={props.partListNames}
              visible-option-num={5}
              option-height={"1.06666rem"}
            />
            <img src={ okBtn } class={styles.button} onClick={async () => {
                await checkMoveNoSave();
                myPicker.value.confirm()
                nextTick(()=>{
                  emit('close', selValues.value[0])
                })
              }
            }></img>
          </div>
        </div>
      </div>
    )
  },
})
