<template>
  <div class="lmt-width">
    <!-- 轮播 -->
    <n-carousel
      show-arrow
      trigger="hover"
      :autoplay="true"
      style="margin: 0 auto; max-width: 800px"
    >
      <div
        class="wp-carousel"
        v-for="(b, idx) in banners"
        :key="idx"
      >
        <img class="carousel-img" :src="b.imageUrl.replace('http://', 'https://')" @click="clickBanner(b.targetId, b.targetType)" />
        <span class="title">{{ b.typeTitle }}</span>
      </div>
    </n-carousel>
    <!-- 最新音乐 -->
    <div>
      <n-button
        text
        icon-placement="right"
        size="large"
        type="primary"
        style="font-size: 1.3em; margin-top: 6px"
      >
        <template #icon>
          <n-icon>
            <ChevronForward />
          </n-icon>
        </template>
        最新音乐
      </n-button>
      <n-grid
        :x-gap="18"
        :y-gap="8"
        :cols="2"
        style="margin: 6px 0"
      >
        <n-grid-item
          v-for="(song, idx) in topSongs"
          :key="song.id"
        >
          <div class="c2-list">
            <div v-if="idx<6" class="play-btn"  @click="play(song.id)">
              <img v-lazy="song.album.blurPicUrl.replace('http://', 'https://')" />
              <!-- <img :src="song.album.blurPicUrl.replace('http://', 'https://')" /> -->
              <!-- <div class="w-[60px] h-[60px]">
                
              </div> -->
              <n-button
                text
                class="start-play-bg"
                type="info"
                
              >
                <n-icon>
                  <PlayCircle />
                </n-icon>
              </n-button>
              <n-button
                text
                class="start-play"
                type="primary"
                
              >
                <!-- <n-icon>
                  <Play />
                </n-icon> -->
                <svg-icon name="Play_" />
              </n-button>
            </div>
            <div class="title">
              <span 
                class="name cursor-pointer hover:underline" 
                :class="[]"
                :style="{
                  color: store.state.theme.themeOverrides.common.primaryColor,
                }"
                @click="play(song.id)"
              >
                {{ song.name }}
                <span class="alias"
                  ><template
                    v-for="(al, idx) in song.alias"
                  >
                    {{ al }}
                  </template></span
                >
              </span>
              <span class="artist">
                <ArtistsSpan :artists="song.artists" />
              </span>
            </div>
            <span class="icon"></span>
          </div>
        </n-grid-item>
      </n-grid>
    </div>
    <!-- tailwind 推荐MV -->
    <div class="
      mt-4
      text-xl
      flex items-center"
      :style="{
        color: store.state.theme.themeOverrides.common.primaryColor,
      }"
    >
      推荐MV 
      <svg-icon name="ChevronForward" class="mx-1" />
    </div>
    <div class="mt-1 grid grid-cols-4 gap-4">
      <div 
        v-for="(mv, idx) in personalizedMV"
        :key="mv.id"
        class=" border border-gray-200 rounded-md
        "
      >
        <div class="relative group cursor-pointer">
          <img :src="mv.picUrl" class="rounded-t-md object-cover w-full aspect-video" />
          <div class="w-full aspect-video flex justify-center items-center  absolute top-0 pt-2 group-hover:visible invisible">
            <div class="rounded-full bg-white/75 w-7 h-7 md:w-9 md:h-9"></div>
          </div>
          <div class="w-full aspect-video flex justify-center items-center  absolute top-0 pt-2 pl-[3px] md:pl-[5px] group-hover:visible invisible">
            <svg-icon name="Play" class="text-xl md:text-3xl" :style="{
              color: store.state.theme.themeOverrides.common.primaryColor,
            }" />
          </div>
          <!-- <div class="m-1 h-7 w-7 bg-white bg-opacity-70 
          absolute bottom-0 right-0
          rounded-full
          group-hover:visible invisible"></div>
          <div class="group-hover:visible invisible
            text-xl
            absolute right-[6px] bottom-[8px]
            flex items-center"
            :style="{
              color: store.state.theme.themeOverrides.common.primaryColor,
              //bottom: 8 + 'px',
              //right: 2 + 'px',
            }"
          >
            <svg-icon name="Play" class="" />
          </div> -->
          
        </div>
        <div class="mx-1 mt-1 text-gray-800 text-sm truncate">
          {{ mv.name }}
        </div>
        <div class="mx-1 mb-1 text-gray-500 text-xs truncate">
          {{ mv.artistName }}
        </div>
      </div>
    </div>
    <!-- 推荐MV -->
    <!-- <div>
      <n-button
        text
        icon-placement="right"
        size="large"
        type="primary"
        style="font-size: 1.3em; margin-top: 6px"
      >
        <template #icon>
          <n-icon>
            <ChevronForward />
          </n-icon>
        </template>
        推荐MV
      </n-button>
      <n-grid
        :x-gap="18"
        :y-gap="8"
        :cols="4"
        style="margin: 6px 0"
      >
        <n-grid-item
          v-for="(mv, idx) in personalizedMV"
          :key="mv.id"
        >
          <div class="mv-c2-list">
            <div class="play-mv">
              <div>
                <img :src="mv.picUrl" />
              </div>
              <n-button
                text
                class="start-play-bg"
                type="info"
              >
                <n-icon>
                  <PlayCircle />
                </n-icon>
              </n-button>
              <n-button
                text
                class="start-play"
                type="primary"
              >
                <n-icon>
                  <Play />
                </n-icon>
              </n-button>
            </div>
            <div class="title">
              <span class="name">
                {{ mv.name }}
              </span>
              <span class="artist">{{
                mv.artistName
              }}</span>
            </div>
          </div>
        </n-grid-item>
      </n-grid>
    </div> -->
    <!-- tailwind 推荐MV -->
    <div class="
      mt-4
      text-xl
      flex items-center"
      :style="{
        color: store.state.theme.themeOverrides.common.primaryColor,
      }"
    >
      推荐歌单 
      <svg-icon name="ChevronForward" class="mx-1" />
    </div>
     <div class=" mt-1 grid grid-cols-4 gap-4">
       <div v-for="p in personalized" :key="p.id"
        class="rounded-md border border-gray-200"
       >
         <img :src="p.picUrl" class="rounded-t-md object-cover aspect-square" />
         <div class="m-1 text-sm text-gray-500 card-span">
           {{ p.name }}
         </div>
       </div>
     </div>
    <!-- 推荐歌单 -->
    <!-- <div>
      <n-button
        text
        icon-placement="right"
        size="large"
        type="primary"
        style="font-size: 1.3em; margin-top: 6px"
      >
        <template #icon>
          <n-icon>
            <ChevronForward />
          </n-icon>
        </template>
        推荐歌单
      </n-button>
      <n-grid
        :x-gap="18"
        :y-gap="8"
        :cols="4"
        style="margin: 6px 0"
      >
        <n-grid-item v-for="p in personalized" :key="p.id">
          <n-card
            title
            hoverable
            content-style="padding: 2px 6px;"
          >
            <template #cover>
              <img :src="p.picUrl" />
            </template>
            <span class="card-span">{{ p.name }}</span>
          </n-card>
        </n-grid-item>
      </n-grid>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useStore } from "vuex";
import {
  NCarousel,
  NScrollbar,
  NGrid,
  NGridItem,
  NCard,
  NButton,
  NIcon,
  NImage,
} from "naive-ui";
// import {
//   ChevronForward,
//   PlayCircle,
//   Play,
// } from "@vicons/ionicons5";
import PlayCircle from "@/assets/svgs/PlayCircle.svg";
import Play from "@/assets/svgs/Play_.svg";
import ChevronForward from "@/assets/svgs/ChevronForward.svg";
import {
  getBanner,
  getPersonalized,
  getTopSong,
  getPersonalizedMV,
} from "@/network/discover";
import pubsub from "pubsub-js";
import ArtistsSpan from "@/components/ArtistsSpan.vue";
import { invoke } from '@tauri-apps/api/tauri'
import { emit, listen } from "@tauri-apps/api/event"
import { isTauri} from "@/env"

//使用useBackSnaps恢复滚动条位置
import { useBackSnaps } from "@/lib/useBackSnaps";
useBackSnaps()

// console.log("recommend 初始化");
// onUnmounted(() => {
//   console.log('recommend 卸载');
// })
const store = useStore();

onMounted(() => {
  console.log("Recomment onMounted.")
  if (isTauri && !store.firstShow)
    emit('dom-loaded', { 
      sender: 'discover/recommend', 
      data: {
        id: 12324112,
        success: true,
        message: "测试消息"
      }
    })
    store.firstShow = true
})

const play = (id) => {
  pubsub.publish("zp.play", { id, im: true });
};

//#region 轮播图片
let banners = ref([]);
banners.value = store.getters.cache('banners')
const loadBanners = () => {
  getBanner(0)
    .then((res) => {
      banners.value = res.data.banners;
      store.commit("saveCaches", {
        banners: { data: banners.value, time: Date.now() },
      });
      // console.log(banners.value);
      // console.log("recommend 轮播图片初始化");
    })
    .catch((err) => {
      console.log("getBanner err", err);
    });
}
loadBanners()

const clickBanner = (id, type) => {
  switch(type){
    case 1: //新歌首发...
      pubsub.publish('zp.play', {id, im: true})
      break;
  }
}
//#endregion

//#region 最新音乐
let topSongs = ref([]);
topSongs.value = store.getters.cache('topSongs')
// if(store.getters.cache('topSongs'))
// {
//   topSongs.value = store.getters.cache('topSongs')
//   console.log('载入Caches');
// }
//最新音乐
const loadTopSong = () => {
  getTopSong()
    .then((res) => {
      topSongs.value = res.data.data.filter((item, index) => {
        return index < 100;
      });
      store.commit("saveCaches", {
        topSongs: { data: topSongs.value, time: Date.now() },
      });
      // console.log(topSongs.value);
    })
    .catch((err) => {
      console.log("getTopSong err", err);
    });
}
loadTopSong()

//最新音乐华语
let topSongsCN = ref([]);
topSongsCN.value = store.getters.cache('topSongsCN')
const loadTopSongCN = () => {
  getTopSong(7)
    .then((res) => {
      topSongsCN.value = res.data.data.filter((item, index) => {
        return index < 10;
      });
      store.commit("saveCaches", {
        topSongsCN: { data: topSongsCN.value, time: Date.now() },
      });
      // console.log(topSongs.value);
    })
    .catch((err) => {
      console.log("getTopSong err", err);
    });
}
loadTopSong()

function songAlias(alias) {
  if (alias.length > 0) return "[" + alias.join(",") + "]";
}
function songArtists(artists) {
  if (artists.length > 0) {
    return artists
      .map((a) => {
        return a.name;
      })
      .join(" ");
  }
}
//#endregion

//#region 推荐歌单
let personalized = ref([]);
personalized.value = store.getters.cache('personalized')
getPersonalized(8)
  .then((res) => {
    personalized.value = res.data.result;
    store.commit("saveCaches", {
      personalized: { data: personalized.value, time: Date.now() },
    });
    // console.log(personalized.value);
  })
  .catch((err) => {
    console.log("getPersonalized err", err);
  });
//#endregion

//#region 推荐MV
let personalizedMV = ref([]);
personalizedMV.value = store.getters.cache('personalizedMV')
getPersonalizedMV()
  .then((res) => {
    personalizedMV.value = res.data.result;
    store.commit("saveCaches", {
      personalizedMV: { data: personalizedMV.value, time: Date.now() },
    });
    // console.log(personalized.value);
  })
  .catch((err) => {
    console.log("getPersonalizedMV err", err);
  });
//#endregion

setInterval(() => {
  console.log("定时刷新Recommend！")
  loadBanners()
  loadTopSong()
}, 1 * 60 * 60 * 1000);
</script>


<style lang="less" scoped>
@import "@/assets/css/common.less";
.wp-carousel {
  position: relative;
  // width: 20em;
  // font-size: 1vw;
  .carousel-img {
    width: 100%;
    border-radius: 6px;
    cursor: pointer;
  }
  .title {
    position: absolute;
    color: #fff;
    background-color: #5c18a0ff;
    bottom: 0px;
    right: 0;
    padding: 2px 6px;
    font-size: 0.9em;
    border-top-left-radius: 6px;
    border-bottom-right-radius: 6px;
  }
}

.card-span {
  .text-el-line2();
}

.mv-c2-list {
  display: flex;
  flex-direction: column;
  position: relative;
  border: 1px solid #eee;
  border-radius: 6px;

  .play-mv {
    cursor: pointer;

    img {
      width: 100%;
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
    }
    button {
      display: none;
    }

    .start-play-bg {
      font-size: 38px;
      position: absolute;
      right: 0px;
      bottom: 50px;
      color: rgba(255, 255, 255, 0.8);
    }
    .start-play {
      font-size: 25px;
      position: absolute;
      right: 5px;
      bottom: 56px;
    }

    &:hover {
      button {
        display: block;
      }
    }
  }

  .title {
    padding: 3px;
    .name {
      .text-el-line();
      .alias {
        font-size: 13px;
        color: #888;
      }
    }
    .artist {
      font-size: 13px;
      color: #666;
      .text-el-line();
    }
  }
}

.c2-list {
  display: flex;
  align-items: center;
  position: relative;
  border-radius: 4px;
  border: 1px solid #eee;


  .play-btn{
    cursor: pointer;
  }
  img {
    width: 60px;
    height: 60px;
    max-width: 60px;
    max-height: 60px;
    border-radius: 4px;
  }

  .start-play-bg {
    font-size: 30px;
    position: absolute;
    left: 16px;
    top: 16px;
    color: rgba(255, 255, 255, 0.8);
  }

  .start-play {
    font-size: 16px;
    position: absolute;
    left: 24px;
    top: 23px;
  }

  .title {
    padding-left: 8px;
    display: flex;
    flex-direction: column;

    .name {
      .text-el-line();
      .alias {
        font-size: 13px;
        color: #888;
      }
    }
    .artist {
      font-size: 13px;
      color: #666;
      .text-el-line();
    }
  }
  // .icon {
  // }
}
</style>
