import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch,
  toRefs,
  PropType,
  computed
} from 'vue';
import styles from './detail.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NImage,
  NPopselect,
  NSpace
} from 'naive-ui';
// import iconAdd from '../../images/icon-add.png';
// import TheSearch from '/src/components/TheSearch';
// import { resourceTypeArray } from '/src/utils/searchArray';
import { useCatchStore } from '/src/store/modules/catchData';
import { audioPlayType } from '/src/utils/contants';
import { api_musicSheetTagQueryList } from './api';
// import isCollaose from '../../images/isCollaose.png';

const ChildNodeSearch = defineComponent({
  name: 'ChildNodeSearch',
  props: {
    activeRow: {
      type: Object,
      default: () => ({})
    },
    list: {
      type: Array,
      default: () => []
    },
    isHide: {
      type: Boolean,
      default: false
    }
  },
  emits: ['selectChildTag'],
  setup(props, { emit }) {
    const { activeRow } = toRefs(props);
    const selectItem = ref({});

    watch(
      () => props.activeRow,
      () => {
        activeRow.value = props.activeRow;
        selectItem.value = {};
      }
    );
    return () => (
      <>
        {activeRow.value?.id && (
          <>
            <NFormItem
              label={activeRow.value.columnName + '：'}
              class={props.isHide && styles.hideItem}>
              <NSpace class={styles.spaceSection}>
                {activeRow.value?.children.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,
                      (activeRow.value.activeIndex || '') == subject.id &&
                        styles.textBtnActive
                    ]}
                    onClick={() => {
                      activeRow.value.activeIndex = subject.id;
                      let children: any;
                      let columnName = '';
                      if (subject.children) {
                        children = [
                          {
                            columnName: subject.children[0].columnName,
                            name: '全部',
                            id: ''
                          },
                          ...subject.children
                        ];
                        columnName = subject.children[0].columnName;

                        selectItem.value = {
                          ...subject,
                          columnName,
                          activeIndex: '',
                          children
                        };
                      } else {
                        selectItem.value = {};
                      }
                      emit('selectChildTag', activeRow.value.activeIndex);
                    }}>
                    {subject.name}
                  </span>
                ))}
              </NSpace>
            </NFormItem>

            <ChildNodeSearch
              isHide={props.isHide}
              activeRow={selectItem.value}
              onSelectChildTag={(item: any) => {
                emit('selectChildTag', item || activeRow.value.activeIndex);
              }}
            />
          </>
        )}
      </>
    );
  }
});

export default defineComponent({
  name: 'search-group',
  props: {
    type: {
      type: String as PropType<'' | 'RECOMMEND' | 'HOT' | 'NEW'>,
      default: ''
    },
    musicalInstrumentId: {
      type: String,
      default: ''
    }
  },
  emits: ['search', 'add'],
  expose: ['init'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const forms = reactive({
      musicTagIds: '',
      audioPlayTypes: '',
      bookVersionId: null as any,
      subjectId: null as any
    });
    const state = reactive({
      showMore: false,
      tempSubjectId: null as any
    });
    const data = reactive({
      audioPlayTypeList: [] as any, // 场景
      selectParents: {}, // 选中的数据
      newTags: [] as any, // 最新标签
      tags: [] as any[],
      tagActiveId: '' as any,
      tagActive: {} as any,
      childSelectId: null as any
    });

    watch(
      () => props.musicalInstrumentId,
      () => {
        if (props.musicalInstrumentId) {
          backInstruments();
        } else {
          formatFirstSubject();
        }
      }
    );

    watch(
      () => props.type,
      () => {
        if (!props.musicalInstrumentId) {
          formatFirstSubject();
          onSearch();
        }
      }
    );

    // 是否显示声部
    const isShowInstrument = computed(() => {
      if (props.type) {
        return true;
      } else {
        return false;
      }
    });

    const onSearch = () => {
      emit('search', {
        ...forms,
        subjectId: forms.audioPlayTypes !== 'SING' ? forms.subjectId : null,
        audioPlayTypes: forms.audioPlayTypes
          ? forms.audioPlayTypes === 'PLAY_SING'
            ? ['PLAY', 'SING']
            : [forms.audioPlayTypes]
          : [],
        bookVersionId: data.childSelectId || data.tagActiveId
      });
    };

    const onShowMore = () => {
      state.showMore = !state.showMore;
    };

    const selectChildObj = (item: any) => {
      const obj: any = {};
      item?.forEach((child: any) => {
        if (child.id === forms.subjectId) {
          obj.selected = true;
          obj.name = child.name;
        }
      });
      return obj;
    };

    const _initTags = () => {
      const tags = catchStore.getMusicTagTree;
      // 去掉上下册
      tags.forEach((item: any) => {
        if (item.children && item.children.length > 0) {
          const child = item.children;
          child?.forEach((c: any) => {
            c.children = null;
          });
        }
      });
      data.tags = [
        {
          columnName: tags[0].columnName,
          name: '全部',
          id: ''
        },
        ...tags
      ];
      data.tagActiveId = data.tags[0].id;
    };

    const changeTag = (item: any) => {
      data.tagActiveId = item.id;
      data.childSelectId = null;
      let children: any;
      let columnName = '';
      if (item.children) {
        children = [
          {
            columnName: item.children[0].columnName,
            name: '全部',
            id: ''
          },
          ...item.children
        ];
        columnName = item.children[0].columnName;
        data.selectParents = {
          ...item,
          columnName,
          activeIndex: '',
          children
        };
      } else {
        data.selectParents = {};
      }

      onSearch();
    };

    /** 默认选中第一个声部 */
    const formatFirstSubject = () => {
      const tempSubjects = catchStore.getSubjectInstrumentOnly;
      if (tempSubjects.length > 0) {
        const firstSubject = tempSubjects[0];
        if (firstSubject.instruments && firstSubject.instruments.length > 1) {
          state.tempSubjectId = firstSubject.instruments[0]?.value;
          forms.subjectId = firstSubject.instruments[0]?.value;
        } else {
          forms.subjectId = firstSubject.value;
        }
      }
    };

    const backInstruments = () => {
      let childInstruments: any[] = [];
      catchStore.getSubjectInstrumentOnly.forEach((item: any) => {
        if (props.musicalInstrumentId === item.value) {
          childInstruments = item.instruments || [];

          forms.subjectId = props.musicalInstrumentId;
          state.tempSubjectId = props.musicalInstrumentId;
        } else {
          if (Array.isArray(item.instruments)) {
            item.instruments.forEach((child: any) => {
              if (props.musicalInstrumentId === child.value) {
                childInstruments = item.instruments || [];

                forms.subjectId = props.musicalInstrumentId;
                state.tempSubjectId = props.musicalInstrumentId;
              }
            });
          }
        }
      });
      if (childInstruments.length > 0) {
        selectChildObj(childInstruments);
      }
    };

    const getTags = async () => {
      try {
        const res = await api_musicSheetTagQueryList();
        const result = res.data || [];
        data.newTags = [
          {
            name: '全部',
            id: ''
          },
          ...result.map((item: any) => {
            return {
              name: item.name,
              id: item.id
            };
          })
        ];
      } catch {
        //
      }
    };

    onMounted(async () => {
      // 场景
      const tempAudio = Object.keys(audioPlayType).map(key => {
        return {
          value: key,
          name: audioPlayType[key]
        };
      });
      data.audioPlayTypeList = [{ name: '全部', value: '' }, ...tempAudio];

      await getTags();
      // 获取教材分类列表
      await catchStore.getMusicTagTreeApi();
      _initTags();
      // console.log(data, 'data');
      // 获取声部列表
      await catchStore.getSubjects();

      if (props.musicalInstrumentId) {
        backInstruments();
      } else {
        formatFirstSubject();
      }
      onSearch();
    });
    return () => (
      <div
        class={[
          styles.searchGroup,
          isShowInstrument.value && styles.searchGroupOnly
        ]}>
        <NForm labelAlign="left" labelPlacement="left">
          {data.newTags.length > 1 && (
            <NFormItem
              label={'标签：'}
              class={isShowInstrument.value && styles.hideItem}>
              <NSpace class={styles.spaceSection}>
                {data.newTags.map((subject: any) => (
                  <span
                    class={[
                      styles.textBtn,
                      forms.musicTagIds === subject.id && styles.textBtnActive
                    ]}
                    onClick={() => {
                      forms.musicTagIds = subject.id;
                      onSearch();
                    }}>
                    {subject.name}
                  </span>
                ))}
              </NSpace>
            </NFormItem>
          )}

          <div class={!state.showMore && styles.hideItem}>
            {data.tags.length > 0 && (
              <NFormItem
                label={data.tags[0]?.columnName + '：'}
                class={isShowInstrument.value && styles.hideItem}>
                <NSpace class={styles.spaceSection}>
                  {data.tags.map((subject: any) => (
                    <span
                      class={[
                        styles.textBtn,
                        data.tagActiveId === subject.id && styles.textBtnActive
                      ]}
                      onClick={() => {
                        changeTag(subject);
                      }}>
                      {subject.name}
                    </span>
                  ))}
                </NSpace>
              </NFormItem>
            )}

            <ChildNodeSearch
              isHide={isShowInstrument.value}
              activeRow={data.selectParents}
              onSelectChildTag={(val: any) => {
                data.childSelectId = val;
                onSearch();
              }}
            />
          </div>

          <NFormItem
            label="场景："
            class={[
              !state.showMore && styles.hideItem,
              isShowInstrument.value && styles.hideItem
            ]}>
            <NSpace class={styles.spaceSection}>
              {data.audioPlayTypeList.map((subject: any) => (
                <span
                  class={[
                    styles.textBtn,

                    forms.audioPlayTypes === subject.value &&
                      styles.textBtnActive
                  ]}
                  onClick={() => {
                    forms.audioPlayTypes = subject.value;
                    onSearch();
                  }}>
                  {subject.name}
                </span>
              ))}
            </NSpace>
          </NFormItem>

          {(forms.audioPlayTypes !== 'SING' || isShowInstrument.value) && (
            <NFormItem
              label="乐器："
              class={
                !state.showMore && !isShowInstrument.value && styles.hideItem
              }>
              <NSpace class={styles.spaceSection}>
                {catchStore.getSubjectInstrumentOnly.map((subject: any) =>
                  subject.instruments && subject.instruments.length > 1 ? (
                    <NPopselect
                      options={subject.instruments}
                      trigger="hover"
                      scrollable
                      v-model:value={state.tempSubjectId}
                      onUpdate:value={() => {
                        forms.subjectId = state.tempSubjectId;
                        onSearch();
                      }}
                      key={subject.value}
                      class={[styles.popSelect]}>
                      <span
                        class={[
                          styles.textBtn,
                          selectChildObj(subject.instruments).selected &&
                            styles.textBtnActive
                        ]}>
                        {selectChildObj(subject.instruments).name ||
                          subject.name}
                        <i class={styles.iconArrow}></i>
                      </span>
                    </NPopselect>
                  ) : (
                    <span
                      class={[
                        styles.textBtn,
                        forms.subjectId === subject.value &&
                          styles.textBtnActive
                      ]}
                      onClick={() => {
                        forms.subjectId = subject.value;

                        state.tempSubjectId = null;
                        onSearch();
                      }}>
                      {subject.name}
                    </span>
                  )
                )}
              </NSpace>
            </NFormItem>
          )}
        </NForm>
        {!isShowInstrument.value && (
          <div
            class={[
              styles.moreSearch,
              state.showMore ? styles.activeSearch : ''
            ]}
            onClick={onShowMore}>
            {state.showMore ? '收起' : '展开'}
          </div>
        )}
      </div>
    );
  }
});
