import { computed, defineComponent, nextTick, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  // 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',
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const show = ref(false);
    const content = ref(false);
    const musicContentRef = ref();
    const speakMusicContent =
      'musicContent' + new Date().getTime() + Math.floor(Math.random() * 100);
    const speak = useSpeak(speakMusicContent);
    const state = reactive({
      fontSize: 18,
      tableList: [] as any,
      selectKey: null,
      details: {} as any,
      selectCheckboxs: [] as any
    });
 
    const isDisabled = computed(() => {
      const boxs = state.selectCheckboxs;
      let flag = false;
      for (const i in boxs) {
        if (boxs[i].length > 0) {
          flag = true;
          break;
        }
      }
      return !flag;
    });

    const getDetails = async () => {
      show.value = true;
      content.value = true;
      try {
        const { data } = await api_lessonCoursewareDetail_listKnowledge({
          type: 'COURSEWARE'
        });

        state.tableList = data || [];
        if (state.tableList.length > 0) {
          const item =
            state.tableList[0].lessonCoursewareDetailKnowledgeDetailList;
          state.tableList[0].selected = true;
          if (item && item.length) {
            const child = item[0];
            state.selectKey = child.id;
            await getDetail();
          }
          state.tableList.forEach((item: any) => {
            item.checked = false;
            item.indeterminate = false;
          });
        }
      } catch {
        //
      }
      content.value = false;
      show.value = false;
    };

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

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

          const hasChilds = document.querySelectorAll('.only-child-select');
          if (hasChilds.length > 0) {
            hasChilds.forEach(child => {
              child.remove();
            });
          }

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

          // 提取并分割 HTML 文档中的内容
          const result = document.createElement("div")
          result.classList.add("html-to-dom")
          result.appendChild(speak.processNode(doc.body))
          document
            .querySelector('#' + speakMusicContent)
            ?.appendChild(result);
        });
      } catch {
        //
      }
      content.value = false;
    };

    const onSubmit = () => {
      const items: any[] = [];
      for (const i in state.selectCheckboxs) {
        const ids = state.selectCheckboxs[i];
        const item = state.tableList[i];
        if (Array.isArray(item.lessonCoursewareDetailKnowledgeDetailList)) {
          item.lessonCoursewareDetailKnowledgeDetailList.forEach(
            (child: any) => {
              if (ids.includes(child.id)) {
                items.push(child);
              }
            }
          );
        }
      }
      const result: any[] = [];
      items.forEach(item => {
        result.push({
          coverImg: PageEnum.THEORY_DEFAULT_COVER,
          title: '乐理知识-' + item.name,
          materialId: item.id,
          content: item.id
        });
      });

      emit('confirm', result);
    };

    onMounted(() => {
      getDetails();
    });
    return () => (
      <div class={styles.container}>
        <div class={[styles.wrap]}>
          <div class={styles.content}>
            <div class={styles.contentWrap}>
              <div class={styles.directoryList}>
                <div
                  class={[
                    styles.scrollBar,
                    !show.value && state.tableList.length <= 0
                      ? styles.empty
                      : ''
                  ]}
                  style={{ height: '100%' }}>
                  <NSpin show={show.value} style={{ height: '100%' }}>
                    <div class={[styles.listSection]}>
                      {state.tableList.map((item: any, index: number) => (
                        <div
                          class={[
                            styles.treeParent,
                            item.selected && styles.treeParentSelected
                          ]}
                          key={'parent' + index}>
                          <div
                            class={[styles.treeItem, styles.parentItem]}
                            onClick={() => {
                              state.tableList.forEach((child: any) => {
                                if (item.id !== child.id) {
                                  child.selected = false;
                                }
                              });
                              item.selected = item.selected ? false : true;
                            }}>
                            {item.lessonCoursewareDetailKnowledgeDetailList &&
                              item.lessonCoursewareDetailKnowledgeDetailList
                                .length > 0 && (
                                <span
                                  class={[
                                    styles.arrow,
                                    item.selected ? styles.arrowSelect : ''
                                  ]}></span>
                              )}
                            <p
                              class={[
                                styles.title,
                                item.selected ? styles.titleSelect : ''
                              ]}>
                              <span
                                class={[
                                  styles.dir,
                                  item.selected ? styles.dirSelect : ''
                                ]}></span>
                              <p>{item.name}</p>
                            </p>
                            <div
                              class={styles.checkbox}
                              onClick={(e: any) => {
                                e.stopPropagation();
                              }}>
                              <NCheckbox
                                checked={item.checked}
                                indeterminate={item.indeterminate}
                                onUpdate:checked={(val: boolean) => {
                                  item.checked = val;

                                  const child =
                                    item.lessonCoursewareDetailKnowledgeDetailList ||
                                    [];
                                  if (val) {
                                    const ids: any = [];
                                    child.forEach((c: any) => {
                                      ids.push(c.id);
                                    });
                                    state.selectCheckboxs[index] = ids;
                                  } else {
                                    state.selectCheckboxs[index] = [];
                                  }
                                  item.indeterminate = false;
                                }}></NCheckbox>
                            </div>
                          </div>
                          <NCheckboxGroup
                            value={state.selectCheckboxs[index]}
                            onUpdate:value={val => {
                              state.selectCheckboxs[index] = val;

                              const child =
                                item.lessonCoursewareDetailKnowledgeDetailList ||
                                [];
                              if (val.length <= 0) {
                                item.checked = false;
                                item.indeterminate = false;
                              } else if (val.length === child.length) {
                                item.checked = true;
                                item.indeterminate = false;
                              } else {
                                item.checked = false;
                                item.indeterminate = true;
                              }
                            }}>
                            {item.selected &&
                              item.lessonCoursewareDetailKnowledgeDetailList &&
                              item.lessonCoursewareDetailKnowledgeDetailList.map(
                                (child: any, j: number) => (
                                  <div
                                    key={'child' + j}
                                    class={[
                                      styles.treeItem,
                                      styles.childItem,
                                      styles.animation,
                                      state.selectKey === child.id
                                        ? styles.childSelect
                                        : ''
                                    ]}
                                    onClick={() => {
                                      if (state.selectKey === child.id) return;
                                      state.selectKey = child.id;
                                      getDetail();
                                      speak.onCloseSpeak();
                                      musicContentRef.value.$el.scrollTo(0, 0);
                                    }}>
                                    <span class={styles.childArrow}></span>
                                    <p class={styles.title}>{child.name}</p>
                                    <div
                                      class={styles.checkbox}
                                      onClick={(e: any) => e.stopPropagation()}>
                                      <NCheckbox value={child.id}></NCheckbox>
                                    </div>
                                  </div>
                                )
                              )}
                          </NCheckboxGroup>
                        </div>
                      ))}
                    </div>
                  </NSpin>
                  {!show.value && state.tableList.length <= 0 && (
                    <TheEmpty style={{ height: '100%' }} />
                  )}
                </div>
              </div>

              <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}
                  max={32}
                />
                <img
                  src={iconPlusT}
                  class={styles.iconPlusT}
                  onClick={() => {
                    if (state.fontSize <= 12) return;
                    state.fontSize -= 1;
                  }}
                />
              </div>
            </div>
          </div>
        </div>

        <NSpace class={styles.btnGroup} justify="center">
          <NButton round onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton round type="primary" onClick={onSubmit} disabled={isDisabled.value}>
            确认添加
          </NButton>
        </NSpace>
      </div>
    );
  }
});
