import { Button, Icon, Search } from "vant";
import { defineComponent, onMounted, ref, watch } from "vue";
import styles from "./index.module.less";
import IconLogo1 from "../../assets/logo-1.png";
import TheSearch from "../../components/TheSearch";
import HotAlbum from "../components/hot-album";
import HotMusic from "../components/hot-music";
import request from "@/helpers/request";
import SearchList from "./components/search-list";
import { useRoute, useRouter } from "vue-router";
import TheDown from "@/components/TheDown";

export default defineComponent({
  name: "Search",
  setup() {
    const route = useRoute();
    const router = useRouter();
    const keyword = ref((route.query.search as string) || "");
    watch(route, () => {
      keyword.value = (route.query.search as string) || "";
    });
    const hotTags = ref<any[]>([]);
    const getTags = async () => {
      try {
        const { data } = await request.get(
          "/api-website/open/music/sheet/hotTag/MUSIC"
        );
        if (Array.isArray(data)) hotTags.value = data;
      } catch (error) {}
    };
    onMounted(() => {
      getTags();
    });

    const onSearch = (val: string) => {
      if (!val) {
        keyword.value = val || "";
        return;
      }
      router.replace({
        path: "/search",
        query: {
          search: val,
        },
      });
    };
    const downRef = ref()
    return () => (
      <div class={styles.search}>
        <div class={styles.fixed}>
          <div class={styles.top}>
            <img class={styles.img} src={IconLogo1} />
            <span>打开APP看海量热门乐谱</span>
            <Button round class={styles.topBtn} onClick={() => downRef.value?.downLoadApp()}>
              打开
            </Button>
          </div>

          <TheSearch
            keyword={keyword.value}
            onSearch={(val: string) => onSearch(val)}
            onBlur={(val: string) => onSearch(val)}
            onBack={() => {
              router.push('/')
            }}
          />
        </div>

        <div class={styles.tagContent}>
          <div class={styles.tagLeft}>热门搜索：</div>
          <div class={styles.tags}>
            {hotTags.value.map((n) => (
              <span onClick={() => onSearch(n.key)}>{n.key}</span>
            ))}
          </div>
        </div>

        {keyword.value && <SearchList />}
        <div style={{ display: keyword.value ? "none" : "block" }}>
          <div class={styles.searchContianer}>
            <HotAlbum />
          </div>
          <HotMusic />
        </div>
        <TheDown ref={downRef}/>
      </div>
    );
  },
});
