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

export default defineComponent({
  name: 'XiaokuAi',
  setup() {
    const router = useRouter();
    const forms = reactive({
      musicTagIds: [] as any[],
      keyword: '',
      page: 1,
      rows: 9999
    });
    const data = reactive({
      tags: [] as any[],
      tagChildren: [] as any[],
      tagActiveId: '',
      tagActive: {} as any,
      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;
        data.tagActiveId = res.data[0].id;
        const list: any[] = [];
        renderTag(res.data[0].children, list);
        data.tagChildren = list;
      }
    };

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

    // 递归渲染标签
    const renderTag = (_data: any[], _list: any[]): any => {
      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 () => {
      await getTags();
      getList();
    });

    /** 改变顶级分类 */
    const changeTag = (item: any, index: number) => {
      data.tagActiveId = item.id;
      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 => item !== oldActiveItem.id
        );
      }
      if (forms.musicTagIds.includes(activeItem.id)) {
        forms.musicTagIds = forms.musicTagIds.filter(
          item => item !== activeItem.id
        );
        data.tagChildren[columnIndex].activeIndex = -1;
      } else {
        forms.musicTagIds.push(activeItem.id);
        data.tagChildren[columnIndex].activeIndex = index;
      }
      getList();
    };
    return () => (
      <div class={styles.container}>
        <div class={styles.tools}>
          <div class={styles.tagWrap}>
            <div class={styles.tags}>
              <NSpace size={[24, 12]}>
                <NButton quaternary disabled>
                  类型
                </NButton>

                {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={[24, 12]}>
                    <NButton quaternary disabled>
                      {column.columnName}
                    </NButton>

                    {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>
          <TheSearch
            round
            onSearch={val => {
              forms.keyword = val;
              getList();
            }}
          />
        </div>
        <NSpin show={data.loading}>
          <div class={styles.content}>
            {data.list.length > 0 ? <NSpace size={[50, 40]}>
              {data.list.map((item: any, index: number) => {
                return (
                  <div
                    class={styles.item}
                    key={`item-${index}`}
                    onClick={() =>
                      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>
                );
              })}
            </NSpace> : <TheEmpty></TheEmpty>}


          </div>
        </NSpin>
      </div>
    );
  }
});
