import {
  defineComponent,
  toRefs,
  reactive,
  onMounted,
  ref,
  nextTick,
  getCurrentInstance
} from 'vue'
import { ElButton, ElTag } from 'element-plus'
import classes from './index.module.less'
import tagItem from '@/components/tagItem'
import hot from './images/hot.png'
import arrow from '@/views/home/images/moreArrow.png'
import search from '@/components/hotSearch/images/search.png'
import searchActive from '@/components/hotSearch/images/searchActive.png'

import request from '@/helpers/request'
import arrows from './images/selectArrow.png'
import clearIcon from './images/clearIcon.png'
import item from '@/views/user-info/components/item'
import { useRoute, useRouter } from 'vue-router'
import { spawn } from 'child_process'

export default defineComponent({
  name: 'hotSearch',
  components: { tagItem },
  emits: ['searchRust', 'hotTag'],
  props: {
    type: {
      type: String,
      default: 'more'
    },
    searchType: {
      type: String,
      default: 'MUSIC'
    },
    gotoPath: {
      type: String,
      default: '/searchdetail'
    },
    isChiose: {
      type: Boolean,
      default: false
    }
  },
  setup(props, conent) {
    const state = reactive({
      hotList: [],
      type: props.type,
      showDetail: true,
      tagTree: [] as any,
      chioseTagList: [] as any,
      chioseParentList: [] as any,
      searchTagList: [],
      searchType: props.searchType,
      searchHover: false
    })
    const router = useRouter()
    const route = useRoute()
    const getHotList = async () => {
      try {
        const res = await request.get(
          `/api-website/open/music/sheet/hotTag/${state.searchType}`
        )

        state.hotList = res.data
      } catch (e) {
        console.log(e)
      }
    }

    const getTagTree = async () => {
      try {
        const res = await request.get('/api-website/open/MusicTag/tree', {})
        state.tagTree = res.data

        state.tagTree.push({
          id: -1,
          name: '乐谱类型',
          children: [
            {
              id: -1,
              name: '全部',
              parentTagId: -1,
              isCheck: true
            },
            {
              id: -2,
              name: '精品',
              parentTagId: -1
            }
          ]
        })
        // 初始化选中
        state.chioseParentList.push(-1)
        state.chioseTagList.push(-1)
        state.searchTagList = []
        state.tagTree.forEach((tree: any) => {
          tree.children.forEach((item: any) => {
            if (state.chioseTagList.indexOf(item.id as never) != -1) {
              state.searchTagList.push(item as never)
            }
          })
        })
        if (route.params.tag && route.params.parentTagId) {
          const tag = findTag(route.params.tag)
          if (tag) {
            state.showDetail = false
            chioseTag(tag)
          }
        }

        // state.hotList = res.data
      } catch (e) {
        console.log(e)
      }
    }

    const chioseTag = (tag: any) => {
      // 选择判断

      const chioseParentIndex = state.chioseParentList.indexOf(
        tag.parentTagId as never
      )
      const chioseIndex = state.chioseTagList.indexOf(tag.id as never)

      if (chioseParentIndex !== -1 && chioseIndex !== -1) {
        // 这里就是反复点击这一个
        tag.isCheck = false
        state.chioseParentList.splice(chioseParentIndex, 1)
        state.chioseTagList.splice(chioseIndex, 1)
        setSearchTagList()
        return
      }

      if (chioseIndex == -1 && chioseParentIndex == -1) {
        state.chioseParentList.push(tag.parentTagId as never)
        state.chioseTagList.push(tag.id as never)
        tag.isCheck = true
        // 添加进去 并且设置其余的元素不可点击
        setSearchTagList()
        return
      }

      if (chioseIndex !== -1 || chioseParentIndex !== -1) {
        // 选的没有且父元素也没有选中
        state.tagTree.forEach((tree: any) => {
          if (tree.id == tag.parentTagId) {
            tree.children.forEach((item: any) => {
              item.isCheck = false
              let index = state.chioseTagList.indexOf(item.id as never)
              if (index !== -1) {
                state.chioseTagList.splice(index, 1)
              }
            })
          }
        })
        tag.isCheck = true
        state.chioseTagList.push(tag.id as never)
        setSearchTagList()
        return
      }
    }
    const setSearchTagList = () => {
      state.searchTagList = []
      state.tagTree.forEach((tree: any) => {
        tree.children.forEach((item: any) => {
          if (state.chioseTagList.indexOf(item.id as never) != -1) {
            state.searchTagList.push(item as never)
          }
        })
      })
      // console.log(state.searchTagList, 'searchTagList')
      searchSubmit()
    }
    const isChiose = (tag: any) => {
      if (tag.isCheck) {
        return 'dark'
      } else {
        return 'light'
      }
    }

    const closeChioseTag = (tag: any) => {
      chioseTag(tag)
    }
    const clearSearch = () => {
      state.chioseTagList = []
      state.chioseParentList = []
      state.searchTagList = []
      state.tagTree.forEach((tree: any) => {
        tree.children.forEach((item: any) => {
          item.isCheck = false
        })
      })
    }
    const searchSubmit = () => {
      // 请求
      conent.emit('searchRust', state.chioseTagList)
      // state.showDetail = true
    }

    const clickHotTag = (key: string) => {
      if (props.isChiose) {
        state.hotList.forEach((element: any) => {
          element.isCheck = false
        })
        state.hotList.forEach((element: any) => {
          if (element.key == key) {
            element.isCheck = true
          }
        })
      }

      conent.emit('hotTag', key)
    }
    const gotoSearch = () => {
      router.push({ path: props.gotoPath })
    }
    const findTag = (id: any) => {
      let tag = null as any
      state.tagTree.forEach((tree: any) => {
        tree.children.forEach((item: any) => {
          if (id == item.id) {
            tag = item
          }
        })
      })
      return tag
    }
    onMounted(() => {
      getHotList()
      getTagTree()
      // 判断有没有parment
    })
    return () => (
      <>
        {state.showDetail ? (
          <div class={classes.wrap}>
            <div class={classes.wrapLeft}>
              {/* <img src={hot} class={classes.hotIcon} alt="" /> */}
              <h5>热门搜索：</h5>
              <div class={classes.tagWrap}>
                {state.hotList.map((item: any) => {
                  //
                  console.log(item.isCheck, 'isCheck')
                  return (
                    <tagItem
                      isSmall={true}
                      title={item.key}
                      onSearchTag={key => clickHotTag(key)}
                      isChiose={true}
                      item={item}
                    >
                      {item.key}
                    </tagItem>
                  )
                })}
              </div>
            </div>
            {state.type == 'more' ? (
              <div class={classes.wrapRight} onClick={gotoSearch}>
                <span>更多</span>
                <img class={classes.arrow} src={arrow} alt="" />
              </div>
            ) : null}
            {state.type == 'search' ? (
              <div
                class={[classes.wrapRight, classes.searchWrap]}
                onClick={() => (state.showDetail = false)}
                onMouseover={() => {
                  state.searchHover = true
                }}
                onMouseout={() => {
                  state.searchHover = false
                }}
              >
                <span>筛选</span>
                <img
                  class={classes.search}
                  src={state.searchHover ? searchActive : search}
                  alt=""
                />
              </div>
            ) : null}
          </div>
        ) : (
          <div class={classes.searchDetail}>
            <div class={classes.searchResult}>
              <div class={classes.resultTitle}>
                <span>已选类型：</span>
                {/* <img src={arrow} alt="" /> */}
              </div>
              <div class={classes.tagList}>
                {state.searchTagList.map((item: any) => {
                  return (
                    <ElTag
                      size="large"
                      closable
                      onClose={() => closeChioseTag(item)}
                      class="chioseTag"
                    >
                      {item.name}
                    </ElTag>
                  )
                })}
              </div>
              <div class={classes.searchResultRight}>
                <div class={classes.clearBtn} onClick={clearSearch}>
                  <span class={classes.clearText}>清空</span>
                  <img src={clearIcon} class={classes.clearIcon} alt="" />
                </div>
                <div
                  class={classes.clearBtn}
                  onClick={() => {
                    state.showDetail = true
                  }}
                >
                  <span>收起</span>
                  <img src={arrows} class={classes.clearIcon} alt="" />
                </div>
              </div>
            </div>
            <div class={classes.searchChioseWrap}>
              <div class={classes.chioseLineWrap}>
                {state.tagTree.map((tree: any) => {
                  return (
                    <div class={classes.chioseRow}>
                      <p>{tree.name}：</p>
                      <div class={[classes.chioseTagWrap, 'chioseTagWrap']}>
                        {tree.children.map((tag: any) => {
                          return (
                            <div
                              class={[
                                classes.tags,
                                tag.isCheck ? classes.check : ''
                              ]}
                              onClick={() => {
                                chioseTag(tag)
                              }}
                            >
                              {tag.name}
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  )
                })}
              </div>
              {/* <div class={classes.submitBtn} onClick={searchSubmit}>
                搜索
              </div> */}
            </div>
          </div>
        )}
      </>
    )
  }
})
