import { defineStore } from 'pinia'
import { playMusic } from '../api/music'

export const usePlayerStore = defineStore('player', {
  state: () => ({
    currentMusic: null,
    playlist: [],
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    volume: 80,
    showPlaylist: false,
    loop: 'none', // none, single, list
    audio: null,
    currentIndex: -1 // 当前播放的索引
  }),

  getters: {
    getCurrentMusic: (state) => state.currentMusic,
    getPlaylist: (state) => state.playlist,
    getIsPlaying: (state) => state.isPlaying,
    getCurrentTime: (state) => state.currentTime,
    getDuration: (state) => state.duration,
    getVolume: (state) => state.volume,
    getShowPlaylist: (state) => state.showPlaylist,
    getLoop: (state) => state.loop,
    getCurrentIndex: (state) => state.currentIndex
  },

  actions: {
    // 初始化音频对象
    initAudio() {
      if (!this.audio) {
        this.audio = new Audio()

        // 监听事件
        this.audio.addEventListener('timeupdate', this.handleTimeUpdate)
        this.audio.addEventListener('ended', this.handleEnded)
        this.audio.addEventListener('loadedmetadata', this.handleLoadedMetadata)
        this.audio.addEventListener('error', this.handleError)
        this.audio.volume = this.volume / 100
      }
    },

    // 设置当前音乐
    async setCurrentMusic(music) {
      if (!music || (this.currentMusic && this.currentMusic.id === music.id && this.isPlaying)) {
        return;
      }

      this.initAudio();
      
      // 在加载新音乐之前暂停并重置当前音频
      if (this.audio) {
        this.pause();
        this.audio.src = ''; // 清空旧的音频源
      }

      this.currentMusic = { ...music };
      this.isPlaying = false;
      this.currentTime = 0;
      this.duration = 0;

      const index = this.playlist.findIndex(item => item.id === music.id);
      if (index !== -1) {
        this.currentIndex = index;
      } else {
        this.addToPlaylist(music);
        this.currentIndex = this.playlist.length - 1;
      }

      if (music.url) {
        this.audio.src = music.url;
        this.audio.load(); // 明确加载新音频
        this.play();

        try {
          await playMusic(music.id);
        } catch (error) {
          console.error('记录播放失败:', error);
        }
      } else {
        console.error('音乐URL不存在');
      }
    },

    // 播放
    play() {
      if (this.currentMusic) {
        this.initAudio()
        const playPromise = this.audio.play()

        if (playPromise !== undefined) {
          playPromise.then(() => {
            this.isPlaying = true
          }).catch(error => {
            console.error('播放失败:', error)
            this.isPlaying = false
          })
        }
      }
    },

    // 暂停
    pause() {
      if (this.audio) {
        this.audio.pause()
        this.isPlaying = false
      }
    },

    // 切换播放状态
    togglePlay() {
      if (this.isPlaying) {
        this.pause()
      } else {
        this.play()
      }
    },

    // 设置音量
    setVolume(volume) {
      this.volume = volume
      if (this.audio) {
        this.audio.volume = volume / 100
      }
    },

    // 设置当前播放时间
    setCurrentTime(time) {
      this.currentTime = time
      if (this.audio) {
        try {
          this.audio.currentTime = time
          // 如果当前是暂停状态，尝试播放一小段时间再暂停，以确保进度条变化生效
          if (!this.isPlaying) {
            const wasPlaying = false
            this.audio.play().then(() => {
              setTimeout(() => {
                if (!wasPlaying) {
                  this.audio.pause()
                }
              }, 100)
            }).catch(err => console.error('Temporary play failed:', err))
          }
        } catch (err) {
          console.error('Failed to set currentTime:', err)
        }
      }
    },

    // 添加到播放列表
    addToPlaylist(music) {
      // 检查是否已存在
      const exists = this.playlist.some(item => item.id === music.id)
      if (!exists) {
        this.playlist.push(music)
      }
    },

    // 从播放列表中移除
    removeFromPlaylist(musicId) {
      const index = this.playlist.findIndex(item => item.id === musicId)
      if (index !== -1) {
        this.playlist.splice(index, 1)

        // 如果移除的是当前播放的音乐，则播放下一首
        if (this.currentMusic && this.currentMusic.id === musicId) {
          this.playNext()
        }
      }
    },

    // 清空播放列表
    clearPlaylist() {
      this.playlist = []
      this.setCurrentMusic(null)
    },

    // 播放上一首
    playPrev() {
      if (this.playlist.length === 0) return

      const currentIndex = this.playlist.findIndex(item => this.currentMusic && item.id === this.currentMusic.id)
      let prevIndex = currentIndex - 1

      if (prevIndex < 0) {
        prevIndex = this.playlist.length - 1
      }

      this.setCurrentMusic(this.playlist[prevIndex])
    },

    // 播放下一首
    playNext() {
      if (this.playlist.length === 0) return

      const currentIndex = this.playlist.findIndex(item => this.currentMusic && item.id === this.currentMusic.id)
      let nextIndex = currentIndex + 1

      if (nextIndex >= this.playlist.length) {
        nextIndex = 0
      }

      this.setCurrentMusic(this.playlist[nextIndex])
    },

    // 切换播放列表显示状态
    togglePlaylist() {
      this.showPlaylist = !this.showPlaylist
    },

    // 设置循环模式
    setLoop(mode) {
      this.loop = mode
    },

    // 处理时间更新事件
    handleTimeUpdate() {
      this.currentTime = this.audio.currentTime
    },

    // 处理播放结束事件
    handleEnded() {
      if (this.loop === 'single') {
        // 单曲循环
        this.audio.currentTime = 0
        this.play()
      } else if (this.loop === 'list') {
        // 列表循环
        this.playNext()
      } else {
        // 不循环，播放下一首
        this.playNext()
      }
    },

    // 处理元数据加载事件
    handleLoadedMetadata() {
      this.duration = this.audio.duration
    },

    // 处理错误事件
    handleError(e) {
      console.error('音频加载错误:', e)
      // 如果当前音乐加载失败，尝试播放下一首
      if (this.playlist.length > 1) {
        this.playNext()
      }
    },

    // 设置播放列表显示状态
    setShowPlaylist(show) {
      this.showPlaylist = show
    },

    // 从播放列表中播放
    playFromPlaylist(index) {
      if (index >= 0 && index < this.playlist.length) {
        this.setCurrentMusic(this.playlist[index])
      }
    },

    // 更新音乐URL
    updateMusicUrl(id, url) {
      const musicInPlaylist = this.playlist.find(item => item.id === id);
      if (musicInPlaylist) {
        musicInPlaylist.url = url;
      }

      if (this.currentMusic && this.currentMusic.id === id) {
        this.currentMusic.url = url;
        // 如果是当前播放的音乐，则重新设置音频源并播放
        if (this.audio && this.audio.src !== url) {
           this.setCurrentMusic({ ...this.currentMusic, url });
        }
      }
    },

    // 更新音乐封面
    updateMusicCover(id, cover) {
      // 更新当前音乐的封面
      if (this.currentMusic && this.currentMusic.id === id) {
        this.currentMusic.cover = cover
      }

      // 更新播放列表中的封面
      const index = this.playlist.findIndex(item => item.id === id)
      if (index !== -1) {
        this.playlist[index].cover = cover
      }
    },

    // 更新当前音乐的状态（如收藏、点赞）
    updateCurrentMusicStatus(status) {
      if (this.currentMusic) {
        this.currentMusic = { ...this.currentMusic, ...status };
        
        const index = this.playlist.findIndex(item => item.id === this.currentMusic.id);
        if (index !== -1) {
          this.playlist[index] = { ...this.playlist[index], ...status };
        }
      }
    }
  }
})
