import { defineComponent, ref, reactive, onMounted } from 'vue';
import styles from './index.module.less';
import popBox from './select_courseware_box.png';
import popClose from './selce_courseware_close.png';

export default defineComponent({
  name: 'SelectCoursewarePop',
  props: {
    list: {
      type: Array,
      default: () => []
    },
    kjId: {
      type: String,
      default: '',
    }
  },
  emits: ['close', 'select'],
  setup(props, { emit }) {
    const data = reactive({
      actIdx: null as any,
    });
    const selectItem = (item: any, index: any) => {
      data.actIdx = index
      if (props.kjId) {
        emit('select', item)
        data.actIdx = null
      } else {
        setTimeout(() => {
          emit('select', item)
          data.actIdx = null
        }, 300);
      }
    }
    const initScroll = () => {
      const listDom = document.getElementById('list')
      let idx = props.list.findIndex((item: any) => item.id === props?.kjId) || 0
      listDom?.scrollTo({
        top: idx * 40,
        behavior: "smooth",
      }); 
    }
    onMounted(() => {
      initScroll()
    });
    return () => (
      <div class={styles.popBox} 
      onClick={(e: Event) => e.stopPropagation()}
      onTouchmove={(e: TouchEvent) => e.stopPropagation() }
      >
        <div class={styles.popBody}>
          <img class={styles.popBg} src={popBox} />
          <img class={styles.popClose} src={popClose} onClick={(e: Event) => {
            emit('close');
        }} />
          <ul class={styles.list} id="list">
            {props.list.map((item: any, index: number) => {
              return (
                <li class={(data.actIdx === index || props.kjId === item.id) ? styles.active : ''} onClick={() => selectItem(item, index)}>{item.name}</li>
              );
            })}
          </ul>
        </div>
      </div>
    );
  }
});
