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';
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
    });
    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');
        const parts = xmlParse.getElementsByTagName('part');
        firstMeasures = parts[0]?.getElementsByTagName('measure');
        xmlStatus = 'success';
      } catch (error) {
        xmlStatus = 'error';
      }

      // 判断读取小节数
      if (xmlStatus == 'success') {
        item.practiceChapterMax = 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={() => {
                    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" />
                  </NTabPane>
                  <NTabPane
                    name="shareResources"
                    tab="共享资源"
                    // displayDirective="show:lazy"
                  >
                    <ResourceItem type="shareResources" />
                  </NTabPane>
                  <NTabPane
                    name="myResources"
                    tab="我的资源"
                    // displayDirective="show:lazy"
                  >
                    <ResourceItem type="myResources" />
                  </NTabPane>

                  <NTabPane
                    name="myCollect"
                    tab="我的收藏"
                    // displayDirective="show:lazy"
                  >
                    <ResourceItem type="myCollect" />
                  </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
          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} />
        </NModal>

        <NModal
          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}
            onAdd={(item: any) => onAdd(item)}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
        <NModal
          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>
    );
  }
});
