import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import TheSearch from '@/components/TheSearch';
import { NButton, NImage, NPopselect, NSpace, NSpin } from 'naive-ui';
import { useRouter } from 'vue-router';
import { api_musicSheetCategoriesPage, api_musicTagTree } from './api';
import TheEmpty from '/src/components/TheEmpty';
import { useCatchStore } from '/src/store/modules/catchData';

export default defineComponent({
  name: 'XiaokuAi',
  setup() {
    const catchStore = useCatchStore();
    const router = useRouter();

    const xiaokuAiSearch = localStorage.getItem('xiaoku-ai-search');
    const xiaokuAi = xiaokuAiSearch ? JSON.parse(xiaokuAiSearch) : {};
    const forms = reactive({
      musicTagIds: xiaokuAi.musicTagIds ? xiaokuAi.musicTagIds : ([] as any[]),
      enable: true,
      instrumentId: xiaokuAi.instrumentId || null,
      keyword: '',
      page: 1,
      rows: 9999
    });
    const data = reactive({
      tags: [] as any[],
      tagChildren: [] as any[],
      tagActiveId: xiaokuAi.tagActiveId || '',
      tagActive: {} as any,
      tagIndex: xiaokuAi.instrumentId || 0,
      list: [] as any,
      loading: false
    });
    const getTags = async () => {
      const res = await api_musicTagTree();
      if (Array.isArray(res?.data) && res.data.length) {
        data.tags = res.data || [];
        const index = data.tags.findIndex(
          (item: any) => item.id == data.tagActiveId
        );
        if (index > -1) {
          data.tagActiveId = res.data[index].id;
          const list: any[] = [];
          renderTag(res.data[index].children, list);
          data.tagChildren = list;
        } else {
          data.tagActiveId = res.data[0].id;
          const list: any[] = [];
          renderTag(res.data[0].children, list);
          data.tagChildren = list;
        }
      }
    };

    const getList = async () => {
      data.loading = true;
      try {
        const res = await api_musicSheetCategoriesPage({
          ...forms,
          musicTagIds: [data.tagActiveId, ...forms.musicTagIds].filter(Boolean)
        });
        if (Array.isArray(res?.data?.rows)) {
          data.list = res.data.rows;
        }
      } catch {
        //
      }
      data.loading = false;
    };

    // 递归渲染标签
    const renderTag = (_data: any[], _list: any[]): any => {
      if (!_data?.length) return;
      const item = {
        columnName: _data[0].columnName,
        list: [] as any[]
      };
      const childrens = [];
      for (let i = 0; i < _data.length; i++) {
        item.list.push({
          name: _data[i].name,
          id: _data[i].id,
          activeIndex: -1
        });
        if (_data[i].children) {
          childrens.push(..._data[i].children);
        }
      }
      _list.push(item);
      if (childrens.length) {
        renderTag(childrens, _list);
      }
    };
    onMounted(async () => {
      data.loading = true;
      try {
        await getTags();
        await getList();
        // 获取教材分类列表
        await catchStore.getSubjects();

        localStorage.setItem(
          'xiaoku-ai-search',
          JSON.stringify({
            tagActiveId: data.tagActiveId,
            instrumentId: forms.instrumentId,
            musicTagIds: forms.musicTagIds
          })
        );
        console.log(forms.instrumentId, 'forms.instrumentId');
        if (forms.instrumentId) {
          let childInstruments: any[] = [];
          catchStore.getSubjectInstruments.forEach((item: any) => {
            if (Array.isArray(item.instruments)) {
              item.instruments.forEach((child: any) => {
                if (forms.instrumentId === child.value) {
                  childInstruments = item.instruments || [];
                }
              });
            }
          });

          console.log(childInstruments, 'childInstruments');
          if (childInstruments.length > 0) {
            selectChildObj(childInstruments);
          }
          //  else {
          //   forms.instrumentId = '';
          // }
        }
      } catch {
        //
      }
      data.loading = false;
    });

    /** 改变顶级分类 */
    const changeTag = (item: any, index: number) => {
      data.tagActiveId = item.id;
      forms.musicTagIds = [];

      localStorage.setItem(
        'xiaoku-ai-search',
        JSON.stringify({
          tagActiveId: item.id,
          instrumentId: forms.instrumentId,
          musicTagIds: forms.musicTagIds
        })
      );

      const list: any[] = [];
      renderTag(data.tags[index].children, list);
      data.tagChildren = list;
      getList();
    };

    /** 选中子选项 */
    const selectChildTag = (columnIndex: number, index: number) => {
      const oldActiveItem =
        data.tagChildren[columnIndex].list[
          data.tagChildren[columnIndex].activeIndex
        ];
      const activeItem = data.tagChildren[columnIndex].list[index];
      if (oldActiveItem && oldActiveItem.id !== activeItem.id) {
        forms.musicTagIds = forms.musicTagIds.filter(
          (item: any) => item !== oldActiveItem.id
        );
      }
      if (forms.musicTagIds.includes(activeItem.id)) {
        forms.musicTagIds = forms.musicTagIds.filter(
          (item: any) => item !== activeItem.id
        );
        data.tagChildren[columnIndex].activeIndex = -1;
      } else {
        forms.musicTagIds.push(activeItem.id);
        data.tagChildren[columnIndex].activeIndex = index;
      }

      localStorage.setItem(
        'xiaoku-ai-search',
        JSON.stringify({
          tagActiveId: data.tagActiveId,
          instrumentId: forms.instrumentId,
          musicTagIds: forms.musicTagIds
        })
      );
      getList();
    };
    const selectChildObj = (item: any) => {
      const obj: any = {};

      item?.forEach((child: any) => {
        if (child.id === data.tagIndex) {
          obj.selected = true;
          obj.name = child.name;
        }
      });
      return obj;
    };
    return () => (
      <div class={styles.container}>
        <div class={styles.tools}>
          <div class={styles.tagWrap}>
            <div class={styles.tags}>
              <NSpace size={[20, 12]}>
                <span class={styles.firstButton}>
                  {data.tags?.[0]?.columnName}
                </span>

                {data.tags.map((item: any, index: number) => {
                  return (
                    <>
                      <NButton
                        round
                        secondary={data.tagActiveId === item.id ? false : true}
                        type={
                          data.tagActiveId === item.id ? 'primary' : 'default'
                        }
                        onClick={() => changeTag(item, index)}>
                        {item.name}
                      </NButton>
                    </>
                  );
                })}
              </NSpace>
            </div>

            {data.tagChildren.map((column: any, columnIndex: number) => {
              return (
                <div class={styles.tags}>
                  <NSpace size={[20, 12]}>
                    <span class={styles.firstButton}>{column.columnName}</span>

                    {column.list.map((item: any, index: number) => {
                      return (
                        <>
                          <NButton
                            round
                            secondary={
                              column.activeIndex === index ? false : true
                            }
                            type={
                              column.activeIndex === index
                                ? 'primary'
                                : 'default'
                            }
                            onClick={() => selectChildTag(columnIndex, index)}>
                            {item.name}
                          </NButton>
                        </>
                      );
                    })}
                  </NSpace>
                </div>
              );
            })}
            <div class={styles.tags}>
              <NSpace size={[20, 12]}>
                <span class={styles.firstButton}>乐器</span>

                {catchStore.getSubjectInstruments.map((item: any) =>
                  item.instruments && item.instruments.length > 1 ? (
                    <NPopselect
                      options={item.instruments}
                      trigger="hover"
                      v-model:value={data.tagIndex}
                      scrollable
                      onUpdate:value={() => {
                        forms.instrumentId = data.tagIndex;
                        localStorage.setItem(
                          'xiaoku-ai-search',
                          JSON.stringify({
                            tagActiveId: data.tagActiveId,
                            instrumentId: data.tagIndex,
                            musicTagIds: forms.musicTagIds
                          })
                        );
                        getList();
                      }}
                      key={item.value}
                      class={[styles.popSelect1]}>
                      <NButton
                        round
                        textColor={
                          selectChildObj(item.instruments).selected
                            ? '#fff'
                            : '#000'
                        }
                        color={
                          selectChildObj(item.instruments).selected
                            ? '#198CFE'
                            : 'rgba(46, 51, 56, .05)'
                        }
                        type={
                          selectChildObj(item.instruments).selected
                            ? 'primary'
                            : 'default'
                        }
                        class={[
                          styles.textBtn,
                          selectChildObj(item.instruments).selected &&
                            styles.textBtnActive
                        ]}>
                        {selectChildObj(item.instruments).name || item.name}
                        <i class={styles.iconArrow}></i>
                      </NButton>
                    </NPopselect>
                  ) : (
                    <NButton
                      round
                      textColor={
                        data.tagIndex === (item.value || 0) ? '#fff' : '#000'
                      }
                      color={
                        data.tagIndex === (item.value || 0)
                          ? '#198CFE'
                          : 'rgba(46, 51, 56, .05)'
                      }
                      type={
                        data.tagIndex === (item.value || 0)
                          ? 'primary'
                          : 'default'
                      }
                      onClick={() => {
                        data.tagIndex = item.value || 0;
                        forms.instrumentId = item.value;
                        localStorage.setItem(
                          'xiaoku-ai-search',
                          JSON.stringify({
                            tagActiveId: data.tagActiveId,
                            instrumentId: item.value,
                            musicTagIds: forms.musicTagIds
                          })
                        );
                        getList();
                      }}>
                      {item.name}
                    </NButton>
                  )
                )}
                {/* // {
                //   return (
                //     <>
                //       <NButton
                //         round
                //         secondary={item.id === forms.instrumentId ? false : true}
                //         type={
                //           item.id === forms.instrumentId ? 'primary' : 'default'
                //         }
                //         onClick={() => {
                //           forms.instrumentId = item.id;

                //           localStorage.setItem(
                //             'xiaoku-ai-search',
                //             JSON.stringify({
                //               tagActiveId: data.tagActiveId,
                //               instrumentId: item.id,
                //               musicTagIds: forms.musicTagIds
                //             })
                //           );
                //           getList();
                //         }}>
                //         {item.name}
                //       </NButton>
                //     </>
                //   );
                // })} */}
              </NSpace>
            </div>
          </div>
          <TheSearch
            round
            onSearch={val => {
              forms.keyword = val;
              getList();
            }}
          />
        </div>
        <NSpin show={data.loading}>
          <div
            class={[styles.content, data.loading ? styles.loadingContent : '']}>
            {data.list.length > 0
              ? data.list.map((item: any, index: number) => {
                  return (
                    <div class={styles.itemWrap}>
                      <div class={styles.itemWrapBox}>
                        <div
                          class={styles.item}
                          key={`item-${index}`}
                          onClick={() => {
                            sessionStorage.setItem(
                              'musicSubjectList',
                              JSON.stringify(item.subjects)
                            );
                            router.push({
                              path: '/xiaoku-music',
                              query: {
                                id: item.id,
                                name: item.name
                              }
                            });
                          }}>
                          <div class={styles.cover}>
                            <div class={styles.itemImg}>
                              <div class={styles.itemBg}></div>
                              <NImage
                                objectFit="cover"
                                src={item.coverImg}
                                lazy
                                previewDisabled={true}
                                onLoad={e => {
                                  (e.target as any).dataset.loaded = 'true';
                                }}
                              />
                            </div>
                          </div>
                          <div class={styles.itemName}>{item.name}</div>
                        </div>
                      </div>
                    </div>
                  );
                })
              : ''}
            {!data.loading && data.list.length <= 0 && <TheEmpty></TheEmpty>}
          </div>
        </NSpin>
      </div>
    );
  }
});
