<script setup>
import {
  ref,
  toRefs,
  onActivated,
  watch,
  onMounted,
  nextTick,
  defineAsyncComponent,
  onDeactivated,
  onUnmounted,
} from "vue";
import { searchResult } from "../network/search";
import { useStore } from "vuex";
import { c, NPagination } from "naive-ui";
import pubsub from "pubsub-js";
import Artistlist from "../components/Artistlist.vue";
import { get } from "lodash";
import { useRoute } from "vue-router";

//使用useBackSnaps恢复滚动条位置
import {
  useBackSnaps,
  getScrollTop,
  saveSnap,
  getSnap,
} from "@/lib/useBackSnaps";
useBackSnaps();
const snap = {
  ...{
    type: 1,
    page: 1,
    pageSize: 50,
  },
  ...getSnap(),
};

const Songlist = defineAsyncComponent(() =>
  import("@/components/Songlist.vue")
);

const props = defineProps({
  keywords: String,
});

const store = useStore();
const route = useRoute();

// const type = ref(getSnap('type', 1));
const type = ref(snap.type);
const page = ref(snap.page);
const pageSize = ref(snap.pageSize);
// const keywords = ref(props.keywords);
const keywords = ref('');

// type.value=snap.type
// page.value=snap.page
// pageSize.value=snap.pageSize

const count = ref(0);
const things = ref("单曲");
const elWp = ref(null);
const songs = ref([]);
const artists = ref([]);
const albums = ref([]);
const playlists = ref([]);
const djRadios = ref([]);
const mvs = ref([]);
const videos = ref([]);

// watch(
//   () => [keywords.value, type.value, page.value, pageSize.value],
//   ([k, t]) => {
//     // keywords.value = k;
//     console.log('watch Searching...', keywords.value, type.value, page.value, pageSize.value);
//     search();
//   }
//   // { immediate: true }
// );

const token = pubsub.subscribe("zp", (msg, data) => {
  switch (msg) {
    case "zp.search":
      keywords.value = data;
      page.value = 1
      search();
      break;
  }
});

onMounted(() => {
  search();
});

//卸载组件
onUnmounted(() => {
  pubsub.unsubscribe(token);
});

// let firstTime = true;
// onActivated(()=>{
//   console.log('actived---------');
//   firstTime = true
// })

const search = () => {
  // console.log('Searching...', keywords.value, type.value, page.value, pageSize.value);
  switch (type.value) {
    case 10:
      things.value = "专辑";
      break;
    case 100:
      things.value = "歌手";
      break;
    case 1000:
      things.value = "歌单";
      break;
    case 1009:
      things.value = "电台";
      break;
    case 1004:
      things.value = "MV";
      break;
    case 1014:
      things.value = "视频";
      break;
    case 1:
    default:
      things.value = "单曲";
      break;
  }

  if (keywords.value.length > 0) {
    searchResult(
      keywords.value,
      pageSize.value,
      (page.value - 1) * pageSize.value,
      type.value
    )
      .then((res) => {
        if (res.data.code == 200) {
          if (type.value == 1) {
            // console.log("单曲", res.data.result.songCount, res.data.result.songs.length)
            count.value = res.data.result.songCount;
            // console.log(count.value)
            songs.value = res.data.result.songs;
          } else if (type.value == 100) {
            count.value = res.data.result.artistCount;
            artists.value = res.data.result.artists;
          } else if (type.value == 10) {
            count.value = res.data.result.albumCount;
            albums.value = res.data.result.albums;
          } else if (type.value == 1000) {
            count.value = res.data.result.playlistCount;
            playlists.value = res.data.result.playlists;
          } else if (type.value == 1009) {
            count.value = res.data.result.djRadiosCount;
            djRadios.value = res.data.result.djRadios;
          } else if (type.value == 1004) {
            count.value = res.data.result.mvCount;
            mvs.value = res.data.result.mvs;
          } else if (type.value == 1014) {
            count.value = res.data.result.videoCount;
            videos.value = res.data.result.videos;
          }

          //判断分页情况
          const maxPage = Math.ceil(count.value / pageSize.value);
          // console.log('maxPage:' ,count.value, maxPage);
          if (page.value > maxPage) page.value = maxPage;
          if (page.value < 1) page.value = 1;

          setTimeout(() => {
            console.log(getScrollTop());
            elWp.value.scrollTop = getScrollTop();
          }, 50);

          saveSnap({
            type: type.value,
            page: page.value,
            pageSize: pageSize.value,
          });
        }
      })
      .catch((err) => {
        console.log("searchResult err ", err);
      });
  }
};

const selStyle = (t) => {
  if (t == type.value) {
    const { primaryColor } = store.state.theme.themeOverrides.common;
    return {
      color: primaryColor,
      borderBottom: "solid 2px " + primaryColor,
    };
  }
};

const songMenu = [
  {
    label: "播放",
    key: "play",
  },
  // {
  //   label: "下一首播放",
  //   key: "nextToPlay",
  // },
];

const click = () => {
  // console.log("ctxMenuClick");
  console.log(elWp.value.scrollTop);
  window.history.pushState(null, null);
};

const pageChange = (p) => {
  page.value = p;
  saveSnap({ scrollTop: 0 });
  search();
};
</script>

<template>
  <div id="mainContent" class="main-content" ref="elWp">
    <div class="lmt-width">
      <div class="title">
        {{ keywords }}
        <span class="result">找到 {{ count }} {{ things }}</span>
      </div>
      <!-- <button @click="click" style="z-index: 1000">btn</button> -->

      <div class="tabs">
        <div class="tab">
          <div class="btns">
            <span
              class="caption"
              :style="selStyle('1')"
              @click="
                type = 1;
                page = 1;
                search();
              "
            >
              单曲
            </span>
            <span
              class="caption"
              :style="selStyle('100')"
              @click="
                type = 100;
                page = 1;
                search();
              "
            >
              歌手
            </span>
            <span
              class="caption"
              :style="selStyle('10')"
              @click="
                type = 10;
                page = 1;
                search();
              "
            >
              专辑
            </span>
            <span
              class="caption"
              :style="selStyle('1000')"
              @click="
                type = 1000;
                page = 1;
                search();
              "
            >
              歌单
            </span>
            <span
              class="caption"
              :style="selStyle('1009')"
              @click="
                type = 1009;
                page = 1;
                search();
              "
            >
              电台
            </span>
            <span
              class="caption"
              :style="selStyle('1004')"
              @click="
                type = 1004;
                page = 1;
                search();
              "
            >
              MV
            </span>
            <span
              class="caption"
              :style="selStyle('1014')"
              @click="
                type = 1014;
                page = 1;
                search();
              "
            >
              视频
            </span>
          </div>
          <div class="bt"></div>
        </div>
        <div class="panel" v-show="type == 1">
          <Songlist
            :songs="songs"
            :ctxMenu="songMenu"
            @ctxMenuSelect="
              (key, id) => {
                switch (key) {
                  case 'play':
                    pubsub.publish('zp.play', {
                      id,
                      im: true,
                    });
                    break;
                  case 'nextToPlay':
                    break;
                }
              }
            "
            @itemDbclick="
              (id) => {
                pubsub.publish('zp.play', { id, im: true });
              }
            "
          ></Songlist>
        </div>
        <div class="panel" v-show="type == 10"></div>
        <div class="panel" v-show="type == 100">
          <Artistlist :artists="artists" />
        </div>
        <div class="panel" v-show="type == 1000"></div>
      </div>
      <div class="pager">
        <NPagination v-show="count>0"
          v-model:page="page"
          :page-count="Math.ceil(count / pageSize)"
          :on-update:page="pageChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "SearchResult",
};
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";

.lmt-width {
  padding: 0 12px;
  .title {
    font-size: 30px;
    .result {
      font-size: 13px;
      color: #999;
    }
  }

  .tabs {
    .tab {
      .btns {
        font-size: 16px;
        display: flex;
        .caption {
          padding: 6px 6px;
          margin-right: 16px;
          color: #666;
          border-bottom: solid 2px #f0f0f0;
          cursor: pointer;
        }
        // .sel {
        //   color: red;
        //   border-bottom: solid 2px red;
        // }
      }
      .bt {
        margin-top: -2px;
        height: 2px;
        background-color: #f0f0f0;
      }
    }
  }

  .pager {
    margin: 18px;
    display: flex;
    justify-content: center;
  }
}
</style>
