import {
  PropType,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef
} from 'vue';
import styles from './index.module.less';
import { NTabs, NTabPane, NModal } from 'naive-ui';
import SelectMusicModal from '../../model/select-music';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import SelectResources from '../../model/select-resources';
import SelectMusic, { typeFormat } from './components/select-music';
import ResourceItem from './components/resource-item';
import TrainUpdate from '/src/views/attend-class/model/train-update';
import requestOrigin from 'umi-request';
import { eventGlobal } from '/src/utils';
import useDrag from '@/hooks/useDrag';
import Dragbom from '@/hooks/useDrag/dragbom';
import { useUserStore } from '@/store/modules/users';
import { useCatchStore } from '/src/store/modules/catchData';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'resource-main',
  props: {
    /** 类型 */
    cardType: {
      type: String as PropType<'' | 'homerowk-record' | 'prepare'>,
      default: ''
    },
    from: {
      // 来自哪里
      type: String,
      default: ''
    }
  },
  setup(props, { expose }) {
    const prepareStore = usePrepareStore();
    const catchStore = useCatchStore();
    const forms = reactive({
      tabType: 'relateResources',
      tabWorkType: 'myMusic',
      selectMusicStatus: false,
      selectResourceStatus: false,
      editStatus: false,
      editItem: {} as any,
      searchGroup: {} as any
    });
    const relateResourcesRef = ref();
    const shareResourcesRef = ref();
    const myResourcesRef = ref();
    const myCollectRef = ref();

    const tabRef = ref();
    const workRef = ref();

    const onAdd = async (item: any) => {
      let xmlStatus = 'init';
      // 第一个声部小节
      let firstMeasures: any = null;
      try {
        // 获取文件
        const res = await requestOrigin.get(item.xmlFileUrl, {
          mode: 'cors'
        });
        const xmlParse = new DOMParser().parseFromString(res, 'text/xml');
        /**
         * 妙极客的曲子，systems中含有part标签，需过滤掉systems标签，xmlParse.querySelectorAll('systems')
         */
        const systems = Array.from(xmlParse?.querySelectorAll('systems')) || [];
        systems.forEach((system: any) => {
          const childs = Array.from(system?.querySelectorAll('system')) || [];
          childs.forEach((child: any) => {
            system?.removeChild(child);
          })
        });
        const parts = xmlParse.getElementsByTagName('part');
        firstMeasures = parts[0]?.getElementsByTagName('measure');
        xmlStatus = 'success';
      } catch (error) {
        xmlStatus = 'error';
      }

      // 判断读取小节数
      if (xmlStatus == 'success') {
        // 标记xml是否是从0小节开始
        item.firstMeasureIsZero = firstMeasures?.[0]?.getAttribute('number') === '0';
        item.practiceChapterMax = item.firstMeasureIsZero ? firstMeasures.length - 1 : firstMeasures.length;
      } else {
        item.practiceChapterMax = 0;
      }
      item.coursewareKnowledgeDetailId = prepareStore.getSelectKey;
      item.subjectId = prepareStore.getSubjectId;

      forms.editItem = item;
      forms.editStatus = true;
    };

    const resetTabPosition = () => {
      nextTick(() => {
        tabRef.value?.syncBarPosition();
        workRef.value?.syncBarPosition();
      });
    };

    onMounted(async () => {
      resetTabPosition();

      // 获取教材分类列表
      await catchStore.getMusicSheetCategory(true);
    });
    // 弹窗拖动
    // 曲目资源
    let selectResourceStatusAddBoxDragData: any;
    let selectResourceStatusAddBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      selectResourceStatusAddBoxClass = 'selectResourceStatusAddBoxClass_drag';
      selectResourceStatusAddBoxDragData = useDrag(
        [
          `${selectResourceStatusAddBoxClass} .select-resource>.n-tabs>.n-tabs-nav--top.n-tabs-nav`,
          `${selectResourceStatusAddBoxClass} .bom_drag`
        ],
        selectResourceStatusAddBoxClass,
        toRef(forms, 'selectMusicStatus'),
        users.info.id
      );
    }
    // 曲目资源 作业设置
    let workSetingBoxDragData: any;
    let workSetingBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      workSetingBoxClass = 'workSetingBoxClass_drag';
      workSetingBoxDragData = useDrag(
        [
          `${workSetingBoxClass}>.n-card-header`,
          `${workSetingBoxClass} .bom_drag`
        ],
        workSetingBoxClass,
        toRef(forms, 'editStatus'),
        users.info.id
      );
    }
    //
    expose({
      resetTabPosition
    });
    return () => (
      <div
        class={[
          styles['resource-main'],
          forms.selectMusicStatus || forms.selectResourceStatus
            ? styles.resourceClose
            : ''
        ]}>
        {prepareStore.getTabType === 'courseware' &&
        !['homerowk-record', 'prepare'].includes(props.cardType) ? (
          <NTabs
            id="lessonsIn-0"
            ref={tabRef}
            animated
            class={styles.homerowkTabs}
            value={forms.tabType}
            paneClass={styles.paneTitle}
            paneWrapperClass={styles.paneWrapperContainer}
            onUpdate:value={(val: string) => {
              forms.tabType = val;
            }}>
            {{
              suffix: () => (
                <div
                  class={styles.iconScreen}
                  onClick={() => {
                    let searchGroup: any = {};
                    if (forms.tabType === 'relateResources') {
                      searchGroup = relateResourcesRef.value?.getParams();
                    } else if (forms.tabType === 'shareResources') {
                      searchGroup = shareResourcesRef.value?.getParams();
                    } else if (forms.tabType === 'myResources') {
                      searchGroup = myResourcesRef.value?.getParams();
                    } else if (forms.tabType === 'myCollect') {
                      searchGroup = myCollectRef.value?.getParams();
                    }
                    forms.searchGroup = searchGroup;
                    forms.selectResourceStatus = true;
                    prepareStore.setSelectResourceStatus(true);
                  }}>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <g fill="none">
                      <path
                        d="M5 6a1 1 0 0 1 1-1h2a1 1 0 0 0 0-2H6a3 3 0 0 0-3 3v2a1 1 0 0 0 2 0V6zm0 12a1 1 0 0 0 1 1h2a1 1 0 1 1 0 2H6a3 3 0 0 1-3-3v-2a1 1 0 1 1 2 0v2zM18 5a1 1 0 0 1 1 1v2a1 1 0 1 0 2 0V6a3 3 0 0 0-3-3h-2a1 1 0 1 0 0 2h2zm1 13a1 1 0 0 1-1 1h-2a1 1 0 1 0 0 2h2a3 3 0 0 0 3-3v-2a1 1 0 1 0-2 0v2z"
                        fill="#198CFE"></path>
                    </g>
                  </svg>
                </div>
              ),
              default: () => (
                <>
                  <NTabPane name="relateResources" tab="相关资源">
                    <ResourceItem
                      type="relateResources"
                      ref={relateResourcesRef}
                    />
                  </NTabPane>
                  <NTabPane
                    name="shareResources"
                    tab="共享资源"
                    // displayDirective="show:lazy"
                  >
                    <ResourceItem
                      type="shareResources"
                      ref={shareResourcesRef}
                    />
                  </NTabPane>
                  <NTabPane
                    name="myResources"
                    tab="我的资源"
                    // displayDirective="show:lazy"
                  >
                    <ResourceItem type="myResources" ref={myResourcesRef} />
                  </NTabPane>

                  <NTabPane
                    name="myCollect"
                    tab="我的收藏"
                    // displayDirective="show:lazy"
                  >
                    <ResourceItem type="myCollect" ref={myCollectRef} />
                  </NTabPane>
                </>
              )
            }}
          </NTabs>
        ) : (
          <NTabs
            ref={workRef}
            animated
            value={forms.tabWorkType}
            paneClass={styles.paneTitle}
            paneWrapperClass={styles.paneWrapperContainer}
            onUpdate:value={(val: string) => {
              forms.tabWorkType = val;
            }}>
            {{
              suffix: () => (
                <div
                  class={styles.iconScreen}
                  onClick={() => {
                    forms.selectMusicStatus = true;
                    prepareStore.setSelectMusicStatus(true);
                  }}>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <g fill="none">
                      <path
                        d="M5 6a1 1 0 0 1 1-1h2a1 1 0 0 0 0-2H6a3 3 0 0 0-3 3v2a1 1 0 0 0 2 0V6zm0 12a1 1 0 0 0 1 1h2a1 1 0 1 1 0 2H6a3 3 0 0 1-3-3v-2a1 1 0 1 1 2 0v2zM18 5a1 1 0 0 1 1 1v2a1 1 0 1 0 2 0V6a3 3 0 0 0-3-3h-2a1 1 0 1 0 0 2h2zm1 13a1 1 0 0 1-1 1h-2a1 1 0 1 0 0 2h2a3 3 0 0 0 3-3v-2a1 1 0 1 0-2 0v2z"
                        fill="#198CFE"></path>
                    </g>
                  </svg>
                </div>
              ),
              default: () => (
                <>
                  <NTabPane name="myMusic" tab="我的曲目">
                    <SelectMusic
                      from={props.from}
                      cardType={props.cardType}
                      type="myMusic"
                    />
                  </NTabPane>
                  <NTabPane name="sahreMusic" tab="共享曲目">
                    <SelectMusic
                      from={props.from}
                      cardType={props.cardType}
                      type="sahreMusic"
                    />
                  </NTabPane>
                  <NTabPane name="collectMusic" tab="收藏曲目">
                    <SelectMusic
                      from={props.from}
                      cardType={props.cardType}
                      type="collectMusic"
                    />
                  </NTabPane>
                </>
              )
            }}
          </NTabs>
        )}
        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.selectResourceStatus}
          onUpdate:show={(val: any) => {
            if (!val) {
              prepareStore.setSelectResourceStatus(val);
            }
          }}
          class={['modalTitle', styles.selectMusicModal]}
          preset="card"
          title={'选择资源'}>
          <SelectResources
            type={forms.tabType}
            searchGroup={forms.searchGroup}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          style={
            props.from === 'class'
              ? selectResourceStatusAddBoxDragData.styleDrag.value
              : {}
          }
          v-model:show={forms.selectMusicStatus}
          onUpdate:show={(val: any) => {
            if (!val) {
              prepareStore.setSelectMusicStatus(val);
            }
          }}
          class={[
            'modalTitle',
            styles.selectMusicModal,
            selectResourceStatusAddBoxClass
          ]}
          preset="card"
          title={'选择曲目'}>
          <SelectMusicModal
            from={props.from}
            cardType={props.cardType}
            onAdd={(item: any) => onAdd(item)}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
        <NModal
          maskClosable={modalClickMask}
          style={
            props.from === 'class' ? workSetingBoxDragData.styleDrag.value : {}
          }
          v-model:show={forms.editStatus}
          class={[
            'modalTitle background',
            styles.trainEditModal,
            workSetingBoxClass
          ]}
          preset="card"
          title="作业设置">
          <TrainUpdate
            item={forms.editItem}
            onClose={() => (forms.editStatus = false)}
            onConfirm={(item: any) => {
              const tList = typeFormat(
                item.trainingType,
                item.trainingConfigJson
              );
              const train = {
                ...item,
                id: null,
                musicName: forms.editItem.title,
                typeList: tList
              };
              eventGlobal.emit('onTrainAddItem', train);
            }}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
      </div>
    );
  }
});
