import { PropType, computed, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import { NButton, NForm, NFormItem, NPopselect, NSpace } from 'naive-ui';
import TheSearch from '/src/components/TheSearch';
import deepClone from '/src/helpers/deep-clone';
export default defineComponent({
  name: 'search-group',
  props: {
    categoryChildList: {
      type: Array as PropType<any>,
      default: () => []
    },
    defaultWikiCategoryId: {
      type: String,
      default: ''
    },
    wikiCategoryId: {
      type: String,
      default: ''
    },
    searchValue: {
      type: String,
      default: ''
    }
  },
  emits: ['search', 'add', 'update:searchValue'],
  expose: ['init'],
  setup(props, { emit }) {
    // const catchStore = useCatchStore();
    const forms = reactive({
      keyword: props.searchValue || '',
      wikiCategoryId: props.wikiCategoryId || props.defaultWikiCategoryId || '',
      wikiCategoryIdChild: '',
      childIds: [] as any
    });

    const onSearch = () => {
      emit('search', forms);
    };

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

    const childList = computed(() => {
      const categoryChildList = props.categoryChildList || [];
      const child = categoryChildList.find(
        (item: any) => item.id === forms.wikiCategoryId
      );

      if (child && child.childrenList.length) {
        const temps: any = [];
        child.childrenList.forEach((c: any) => {
          const i = c.childrenList;
          const childTemp: any = [];
          // const i = c.childrenList;
          if (i && i.length > 0) {
            childTemp.push({
              label: '全部',
              value: c.id,
              name: c.name,
              id: c.id
            });
            i.forEach((j: any) => {
              // j.label = j.name;
              // j.value = j.id;
              childTemp.push({
                label: j.name,
                value: j.id,
                name: j.name,
                id: j.id
              });
            });
          }

          temps.push({
            ...c,
            childrenList: childTemp
          });
        });
        return (
          [
            {
              label: '全部',
              value: '',
              id: '',
              name: '全部',
              childrenList: []
            },
            ...temps
          ]
        );
      }
      return [];
    });

    const formatParentId = (id: any, list: any, ids = [] as any) => {
      for (const item of list) {
        if (item.childrenList && item.childrenList.length > 0) {
          const cIds: any = formatParentId(id, item.childrenList, [
            ...ids,
            item.id
          ]);
          if (cIds.includes(id)) {
            return cIds;
          }
        }
        if (item.id === id) {
          return [...ids, id];
        }
      }
      return ids;
    };

    onMounted(() => {
      // 处理缓存反显
      if(props.wikiCategoryId) {
        const ids = formatParentId(props.wikiCategoryId, props.categoryChildList)
        if(ids.length > 0) {
          forms.wikiCategoryId = ids[0]
          forms.wikiCategoryIdChild = ids[ids.length - 1]
        }
      } else {
        forms.wikiCategoryId = props.defaultWikiCategoryId
      }
      
    })

    return () => (
      <div class={styles.searchGroup}>
        <div
          class={[
            styles.searchCatatory,
            childList.value.length > 0 ? styles.border : ''
          ]}>
          <NSpace size="small" class={styles.btnType}>
            {props.categoryChildList.length > 0 ? (
              <NButton
                type={
                  forms.wikiCategoryId === props.defaultWikiCategoryId
                    ? 'primary'
                    : 'default'
                }
                secondary={
                  forms.wikiCategoryId === props.defaultWikiCategoryId ? false : true
                }
                round
                size="small"
                focusable={false}
                onClick={() => {
                  forms.wikiCategoryId = props.defaultWikiCategoryId;
                  forms.wikiCategoryIdChild = '';
                  onSearch();
                }}>
                全部
              </NButton>
            ) : (
              <span></span>
            )}

            {props.categoryChildList.map((item: any) => (
              <NButton
                type={forms.wikiCategoryId === item.id ? 'primary' : 'default'}
                secondary={forms.wikiCategoryId === item.id ? false : true}
                round
                size="small"
                focusable={false}
                onClick={() => {
                  forms.wikiCategoryId = item.id;
                  onSearch();
                }}>
                {item.name}
              </NButton>
            ))}
          </NSpace>
          <TheSearch
            class={styles.inputSearch}
            value={props.searchValue}
            onUpdate:value={(val:string) => {
              forms.keyword = val
              emit("update:searchValue", val)
            }}
            placeholder="请输入曲目名称"
            round
            onSearch={(val: string) => {
              forms.keyword = val;
              onSearch();
            }}
          />
        </div>

        {childList.value.length > 0 && (
          <div class={[styles.collapseWrap]}>
            <NSpace class={[styles.spaceSection]}>
              {childList.value.map((music: any, index: number) => (
                <>
                  {music.childrenList.length > 0 ? (
                    <NPopselect
                      options={music.childrenList}
                      trigger="hover"
                      v-model:value={forms.wikiCategoryIdChild}
                      onUpdate:value={() => {
                        onSearch();
                      }}
                      key={music.id}
                      class={styles.popSelect}>
                      <span
                        class={[
                          styles.textBtn,
                          selectChildObj(music.childrenList, index).selected &&
                            styles.textBtnActive
                        ]}>
                        {selectChildObj(music.childrenList, index).name ||
                          music.name}
                        <i class={styles.iconArrow}></i>
                      </span>
                    </NPopselect>
                  ) : (
                    <span
                      class={[
                        styles.textBtn,
                        forms.wikiCategoryIdChild === music.id &&
                          styles.textBtnActive
                      ]}
                      onClick={() => {
                        forms.wikiCategoryIdChild = music.id;
                        onSearch();
                      }}>
                      {music.name}
                    </span>
                  )}
                </>
              ))}
            </NSpace>
          </div>
        )}
      </div>
    );
  }
});
