import { defineComponent, onMounted, reactive, ref, toRefs, watch } from 'vue';
import styles from './index.module.less';
import TheSearch from '@/components/TheSearch';
import {
  NButton,
  NForm,
  NFormItem,
  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';

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

    watch(
      () => props.activeRow,
      () => {
        activeRow.value = props.activeRow;
        initActiveRow();
      }
    );

    const initActiveRow = () => {
      if (activeRow.value.activeIndex) {
        const childList = activeRow.value.children || [];
        childList.forEach((subject: any) => {
          if (subject.id === activeRow.value.activeIndex) {
            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: subject.activeIndex,
                children
              };
            }
          }
        });
      } else {
        selectItem.value = {};
      }
    };

    onMounted(() => {
      initActiveRow();
    });
    return () => (
      <>
        {activeRow.value?.id && (
          <>
            <NFormItem
              label={activeRow.value.columnName + ''}
              class={styles.tags}>
              <NSpace size={[12, 8]}>
                {activeRow.value?.children.map((subject: any) => {
                  return (
                    <>
                      <NButton
                        round
                        secondary={
                          (activeRow.value.activeIndex || '') == subject.id
                            ? false
                            : true
                        }
                        type={
                          (activeRow.value.activeIndex || '') == subject.id
                            ? 'primary'
                            : 'default'
                        }
                        onClick={() => {
                          if (props.loading) return;
                          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}
                      </NButton>
                    </>
                  );
                })}
              </NSpace>
            </NFormItem>

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

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 id = xiaokuAi.childSelectId || xiaokuAi.tagActiveId;
    const forms = reactive({
      musicTagIds: id ? [id] : ([] 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,
      selectParents: {}, // 选中的数据
      // tags: [] as any[],
      // tagActiveId: '' as any,
      // tagActive: {} as any,
      childSelectId: xiaokuAi.childSelectId || (null as any)
    });

    // const mapList: any = new Map();
    const formatParentId = (id: any, list: any, ids = [] as any) => {
      for (const item of list) {
        if (item.children && item.children.length > 0) {
          const cIds: any = formatParentId(id, item.children, [
            ...ids,
            item.id
          ]);
          if (cIds.includes(id)) {
            return cIds;
          }
        }
        if (item.id === id) {
          return [...ids, id];
        }
        // mapList[item.id] = item.parentTagId;
        // mapList.push()
      }
      return ids;
    };

    const formatParentCurrentValue = (ids: any, list: any) => {
      for (const item of list) {
        if (ids.includes(item.id)) {
          if (item.children && item.children.length > 0) {
            let lastId: any;
            item.children.forEach((child: any) => {
              if (ids.includes(child.id)) {
                lastId = child.id;
              }
            });
            item.activeIndex = lastId;
          }
        }
        if (item.children && item.children.length > 0) {
          formatParentCurrentValue(ids, item.children);
        }
      }
    };

    const formatParentresetValue = (list: any) => {
      for (const item of list) {
        if (item.children && item.children.length > 0) {
          // item.children.forEach(() => {
          //   item.activeIndex = '';
          // });
        }
        item.activeIndex = '';

        if (item.children && item.children.length > 0) {
          formatParentresetValue(item.children);
        }
      }
    };

    const changeTag = (item: any) => {
      if (data.loading) return;
      data.tagActiveId = item.id;
      data.childSelectId = null;
      formatParentresetValue(data.tags);
      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 = {};
      }

      localStorage.setItem(
        'xiaoku-ai-search',
        JSON.stringify({
          tagActiveId: data.tagActiveId,
          instrumentId: forms.instrumentId,
          childSelectId: data.childSelectId
        })
      );
      getList();
    };
    const getTags = async () => {
      const res = await api_musicTagTree();
      if (Array.isArray(res?.data) && res.data.length) {
        // data.tags = res.data || [];
        const tags = res.data || [];
        data.tags = [
          {
            columnName: tags[0].columnName,
            name: '全部',
            id: ''
          },
          ...tags
        ];
        if (!data.tagActiveId) {
          data.tagActiveId = data.tags[0].id;
        } else {
          let ids = formatParentId(xiaokuAi.childSelectId, data.tags);
          // console.log(ids, 'ids', xiaokuAi.childSelectId);
          const index = ids.findIndex(
            (id: any) => id === xiaokuAi.childSelectId
          );
          // console.log(index, 'id');
          ids = ids.slice(0, index + 1);
          formatParentCurrentValue(ids, data.tags);
          data.tags.forEach((item: any) => {
            if (item.id === data.tagActiveId) {
              let children: any;
              let columnName = '';
              if (item.children) {
                children = [
                  {
                    columnName: item.children[0].columnName,
                    name: '全部',
                    id: ''
                  },
                  ...item.children
                ];
                columnName = item.children[0].columnName;

                let id: any;
                item.children.forEach((item: any) => {
                  if (ids.includes(item.id)) {
                    id = item.id;
                  }
                });

                data.selectParents = {
                  ...item,
                  columnName,
                  activeIndex: id || '',
                  children
                };
              } else {
                data.selectParents = {};
              }
            }
          });
        }
      }
    };

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

    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,
            childSelectId: data.childSelectId,
            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 || [];
                }
              });
            }
          });

          if (childInstruments.length > 0) {
            selectChildObj(childInstruments);
          }
        }
      } catch {
        //
      }
      data.loading = false;
    });

    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}>
            <NForm labelAlign="left" labelPlacement="left">
              <NFormItem
                label={data.tags?.[0]?.columnName || ''}
                class={styles.tags}>
                <NSpace size={[12, 8]}>
                  {data.tags.map((item: any) => {
                    return (
                      <>
                        <NButton
                          round
                          secondary={
                            data.tagActiveId === item.id ? false : true
                          }
                          type={
                            data.tagActiveId === item.id ? 'primary' : 'default'
                          }
                          onClick={() => changeTag(item)}>
                          {item.name}
                        </NButton>
                      </>
                    );
                  })}
                </NSpace>
              </NFormItem>
              <ChildNodeSearch
                activeRow={data.selectParents}
                loading={data.loading}
                onSelectChildTag={(val: any) => {
                  data.childSelectId = val;
                  localStorage.setItem(
                    'xiaoku-ai-search',
                    JSON.stringify({
                      tagActiveId: data.tagActiveId,
                      instrumentId: forms.instrumentId,
                      childSelectId: data.childSelectId,
                      musicTagIds: forms.musicTagIds
                    })
                  );
                  getList();
                }}
              />
              <NFormItem label="乐器" class={styles.tags}>
                <NSpace size={[12, 8]}>
                  {/* <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>
                    )
                  )}
                </NSpace>
              </NFormItem>
            </NForm>
          </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>
    );
  }
});
