import { defineComponent, onMounted, ref, shallowRef } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NScrollbar,
  NSpace,
  NTabPane,
  NTabs,
  useMessage
} from 'naive-ui';
import { useCatchStore } from '/src/store/modules/catchData';
import iconSelect from '../../images/icon-select.png';
export default defineComponent({
  name: 'subject-sync',
  props: {
    subjectId: {
      type: [String, Number],
      default: ''
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const tabId = ref('' as any);
    const message = useMessage();
    const selectSubjectIds = ref([] as any);
    const subjectAllList = shallowRef<any[]>([]); // 所有乐器列表
    const subjectList = ref([] as any);

    const subjectImgs = {
      Panpipes: 'https://oss.dayaedu.com/ktqy/17103860536976fd4a751.png',
      // Ocarina: 'https://oss.dayaedu.com/ktqy/171038605369851874b22.png',

      Ocarina: 'https://oss.dayaedu.com/ktqy/17143623857205dba41a5.png',
      'Alto Ocarina': 'https://oss.dayaedu.com/ktqy/17143623857205dba41a5.png',

      Whistling: 'https://oss.dayaedu.com/ktqy/1714362351692fcf8c0b8.png',
      'Soprano Ocarina':
        'https://oss.dayaedu.com/ktqy/1714362351692fcf8c0b8.png',

      Woodwind: 'https://oss.dayaedu.com/ktqy/17103860536966826c50d.png',
      Hulusi: 'https://oss.dayaedu.com/ktqy/17103860536966826c50d.png',

      'Tenor Recorder':
        'https://oss.dayaedu.com/ktqy/17103860536950592e357.png',
      'German Recorder':
        'https://oss.dayaedu.com/ktqy/17103860536950592e357.png',

      Nai: 'https://oss.dayaedu.com/ktqy/1710386053697af4aa985.png',
      Melodica: 'https://oss.dayaedu.com/ktqy/1710386053697af4aa985.png',

      'Baroque Recorder':
        'https://oss.dayaedu.com/ktqy/1710386053698031e847a.png'
    } as any;
    const onSubmit = () => {
      if (selectSubjectIds.value.length <= 0) {
        message.error('至少选择一个声部进行同步');
        return;
      }

      const subjectCode: any[] = [];
      selectSubjectIds.value.forEach((id: any) => {
        const item = subjectAllList.value.find(
          (subject: any) => subject.id === id
        );

        if (item) {
          const tempCode = item.code ? item.code.split(',')[0] : '';
          subjectCode.push({
            materialId: item.id,
            instrumentIds: item.id,
            coverImg: subjectImgs[tempCode] || subjectImgs.Panpipes,
            dataJson: null,
            title: item.name,
            isCollect: false,
            isSelected: false,
            content: item.code
          });
        }
      });
      emit('confirm', { subjectIds: selectSubjectIds.value, subjectCode });
    };

    const formatSubjectList = () => {
      const subjects = catchStore.getEnableSubjects;
      const temp: any = [];
      subjects.forEach((subject: any) => {
        if (tabId.value === '' && subject.instruments) {
          temp.push(...subject.instruments);
        } else if (
          tabId.value &&
          subject.instruments &&
          Number(tabId.value) === subject.id
        ) {
          temp.push(...subject.instruments);
        }
      });

      subjectList.value = temp;
    };

    const formatSubjectAll = () => {
      const subjects: any[] = catchStore.getEnableSubjects;
      const temp: any = [];
      subjects.forEach((subject: any) => {
        if (tabId.value === '' && subject.instruments) {
          temp.push(...subject.instruments);
        }
      });
      subjectAllList.value = temp;
    };
    onMounted(async () => {
      // 获取教材分类列表
      await catchStore.getSubjects();
      formatSubjectAll();
      formatSubjectList();
      if (props.subjectId) {
        selectSubjectIds.value = [Number(props.subjectId)];
      }
    });
    return () => (
      <div class={styles.subjectSync}>
        {/* <div class={styles.tips}>
          请选择当前课件可使用的乐器
          <span>（勾选后则对应乐器下的课件内容将被当前课件内容全部替换）</span>
        </div> */}

        <NTabs
          defaultValue=""
          paneClass={styles.paneTitle}
          justifyContent="start"
          paneWrapperClass={styles.paneWrapperContainer}
          value={tabId.value}
          onUpdate:value={(val: any) => {
            tabId.value = val;
            formatSubjectList();
          }}>
          {[{ name: '全部声部', id: '' }, ...catchStore.getEnableSubjects].map(
            (item: any) => (
              <NTabPane
                name={`${item.id}`}
                tab={item.name}
                displayDirective="if"></NTabPane>
            )
          )}
        </NTabs>
        <NScrollbar style={{ maxHeight: '50vh', minHeight: '50vh' }}>
          <div class={styles.subjectList}>
            {subjectList.value.map((subject: any) => (
              <div
                class={[
                  styles.subjectItem,
                  selectSubjectIds.value.includes(subject.id)
                    ? styles.subjectSelect
                    : ''
                ]}
                onClick={() => {
                  if (selectSubjectIds.value.includes(subject.id)) {
                    const index = selectSubjectIds.value.indexOf(subject.id);
                    selectSubjectIds.value.splice(index, 1);
                  } else {
                    selectSubjectIds.value.push(subject.id);
                  }
                }}>
                <div class={styles.imgSection}>
                  <img src={subject.img} />

                  {selectSubjectIds.value.includes(subject.id) && (
                    <img src={iconSelect} class={styles.iconSelect} />
                  )}
                </div>

                <p class={styles.subjectName}>{subject.name}</p>
              </div>
            ))}
          </div>
        </NScrollbar>

        <NSpace class={styles.btnGroupModal} justify="center">
          <NButton round onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            round
            type="primary"
            onClick={onSubmit}
            disabled={selectSubjectIds.value.length <= 0}>
            确定
          </NButton>
        </NSpace>
      </div>
    );
  }
});
