import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  // NBreadcrumb,
  // NBreadcrumbItem,
  // NScrollbar,
  NSlider,
  NSpace,
  NSpin
} from 'naive-ui';
import iconT from '/src/views/content-information/images/icon-t.png';
import iconAddT from '/src/views/content-information/images/icon-add-t.png';
import iconPlusT from '/src/views/content-information/images/icon-plus-t.png';
import {
  api_lessonCoursewareDetail_listKnowledge,
  api_lessonCoursewareKnowledgeDetail
} from '/src/views/content-information/api';
import TheEmpty from '/src/components/TheEmpty';
// import { PageEnum } from '/src/enums/pageEnum';
import { useSpeak } from '/src/views/content-information/useSpeak';

export default defineComponent({
  name: 'cotnent-knowledge',
  props: {
    id: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    activeStatus: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { expose }) {
    const content = ref(false);
    const musicContentRef = ref();
    const speakMusicContent =
      'musicContent' + new Date().getTime() + Math.floor(Math.random() * 100);
    const selectionCouser =
      'selectionCouser' +
      new Date().getTime() +
      Math.floor(Math.random() * 100);
    const speak = useSpeak(speakMusicContent, selectionCouser);
    const state = reactive({
      fontSize: 18,
      tableList: [] as any,
      selectKey: null,
      details: {} as any,
      domString: '',
      display: 'block'
    });

    const getDetail = async () => {
      content.value = true;
      try {
        const { data } = await api_lessonCoursewareKnowledgeDetail({
          id: props.id
        });

        state.details = data;
        content.value = false;
        nextTick(async () => {
          // 使用 DOMParser 解析 HTML 字符串
          // 获取 HTML 字符串
          // const htmlString = tempDiv.innerHTML;
          // console.log(htmlString);
          const parser = new DOMParser();
          const doc = parser.parseFromString(state.details.desc, 'text/html');

          const childNodes = doc.body.childNodes;
          childNodes?.forEach((node: any) => {
            node?.classList.add('only-child-select');
          });

          // 提取并分割 HTML 文档中的内容

          const node: any = speak.processNode(doc.body);
          const result = document.createElement("div")
          result.classList.add("html-to-dom")
          result.appendChild(node)
          document.querySelector('#' + speakMusicContent)?.appendChild(result);
        });
      } catch {
        //
      }
      content.value = false;
    };

    const onStopAll = (type: 'play' | 'pause' | 'pre' | 'next' | 'favitor') => {
      speak.onCloseSpeak();
    };

    onMounted(() => {
      getDetail();
    });

    watch(
      () => props.activeStatus,
      () => {
        if (!props.activeStatus) {
          onStopAll('pause');
        }
      }
    );

    expose({
      handleChangeAudio: onStopAll
    });
    return () => (
      <div
        class={[
          styles.containerDetail,
          props.type === 'preview' && styles.detailPreview
        ]}>
        {/* <div class={styles.detail2}> */}
        <div class={styles.contentWrap}>
          <div class={styles.musicStaff}>
            <div class={styles.musicTitleRight}>
              {speak.isSpeak.value ? (
                <span class={styles.textClose} onClick={speak.onCloseSpeak}>
                  <i class={styles.icon}></i>关闭朗读
                </span>
              ) : (
                <span class={styles.textRead} onClick={speak.onAllSpeak}>
                  <i class={styles.icon}></i>全文朗读
                </span>
              )}
            </div>
            <NSpin
              show={content.value}
              ref={musicContentRef}
              class={
                !content.value && !state.details?.desc ? styles.empty : ''
              }>
              {state.details?.desc ? (
                <div
                  class={styles.musicContent}
                  id={speakMusicContent}
                  style={{ fontSize: state.fontSize + 'px' }}>
                  {/* 选中的内容 */}
                  <div
                    id={selectionCouser}
                    class={[
                      styles.selectionCouser,
                      !speak.showDom.value && styles.hide
                    ]}>
                    <span class={styles.textStart} onClick={speak.onTextStart}>
                      开始朗读<i class={styles.icon}></i>
                    </span>
                    <span
                      class={styles.textReadOnly}
                      onClick={speak.onTextReadOnly}>
                      只读这段<i class={styles.icon}></i>
                    </span>
                  </div>
                </div>
              ) : (
                ''
              )}
              {!content.value && !state.details?.desc && <TheEmpty />}
            </NSpin>
          </div>

          <div class={styles.changeSizeSection}>
            <img src={iconT} class={styles.iconT} />
            <img
              src={iconAddT}
              class={styles.iconAddT}
              onClick={() => {
                if (state.fontSize >= 32) return;
                state.fontSize += 1;
              }}
            />
            <NSlider
              v-model:value={state.fontSize}
              vertical
              min={12}
              placement="left"
              max={32}
            />
            <img
              src={iconPlusT}
              class={styles.iconPlusT}
              onClick={() => {
                if (state.fontSize <= 12) return;
                state.fontSize -= 1;
              }}
            />
          </div>
        </div>
        {/* </div> */}
      </div>
    );
  }
});
