import api from './index'
import { processMusicUrl } from './music'
import { processImageUrl } from '../utils/imageUtils'

/**
 * 获取歌单列表
 * @param {number} page 页码
 * @param {number} size 每页大小
 * @param {string} keyword 关键字
 * @param {number} typeId 类型ID
 * @returns {Promise<any>}
 */
export function getPlaylistList(page = 1, size = 10, keyword = '', typeId = null) {
  return api.get('/playlist/list', {
    params: {
      page,
      size,
      keyword,
      typeId
    }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理数据结构
      const records = res.data.records || res.data.list || []

      // 处理封面URL
      const processedRecords = records.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))

      if (res.data.records) {
        res.data.records = processedRecords
      } else if (res.data.list) {
        res.data.list = processedRecords
      } else {
        res.data = processedRecords
      }
    }
    return res
  })
}

/**
 * 根据ID获取歌单
 * @param {number} id 歌单ID
 * @returns {Promise<any>}
 */
export function getPlaylistById(id) {
  return api.get(`/playlist/${id}`).then(res => {
    if (res.code === 200 && res.data) {
      // 处理封面URL
      res.data.cover = processImageUrl(res.data.cover)

      // 处理音乐列表
      if (res.data.musics && res.data.musics.length > 0) {
        res.data.musics = res.data.musics.map(music => ({
          ...music,
          cover: processMusicUrl(music.cover),
          url: processMusicUrl(music.url)
        }))
      }
    }
    return res
  })
}

/**
 * 获取热门歌单
 * @param {number} limit 限制数量
 * @returns {Promise<any>}
 */
export function getHotPlaylist(limit = 10) {
  return api.get('/playlist/hot', {
    params: { limit }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理封面URL
      res.data = res.data.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))
    }
    return res
  })
}

/**
 * 获取最新歌单
 * @param {number} limit 限制数量
 * @returns {Promise<any>}
 */
export function getLatestPlaylist(limit = 10) {
  return api.get('/playlist/latest', {
    params: { limit }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理封面URL
      res.data = res.data.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))
    }
    return res
  })
}

/**
 * 获取官方歌单
 * @param {number} page 页码
 * @param {number} size 每页大小
 * @returns {Promise<any>}
 */
export function getOfficialPlaylist(page = 1, size = 10) {
  return api.get('/playlist/official', {
    params: {
      page,
      size
    }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理数据结构
      const records = res.data.records || res.data.list || []

      // 处理封面URL
      const processedRecords = records.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))

      if (res.data.records) {
        res.data.records = processedRecords
      } else if (res.data.list) {
        res.data.list = processedRecords
      } else {
        res.data = processedRecords
      }
    }
    return res
  })
}

/**
 * 获取用户创建的歌单
 * @param {number} page 页码
 * @param {number} size 每页大小
 * @returns {Promise<any>}
 */
export function getUserPlaylist(page = 1, size = 10) {
  return api.get('/playlist/user', {
    params: {
      page,
      size
    }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理数据结构
      const records = res.data.records || res.data.list || []

      // 处理封面URL
      const processedRecords = records.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))

      if (res.data.records) {
        res.data.records = processedRecords
      } else if (res.data.list) {
        res.data.list = processedRecords
      } else {
        res.data = processedRecords
      }
    }
    return res
  })
}

/**
 * 获取用户收藏的歌单
 * @param {number} page 页码
 * @param {number} size 每页大小
 * @returns {Promise<any>}
 */
export function getCollectedPlaylist(page = 1, size = 10) {
  return api.get('/playlist/collect', {
    params: {
      page,
      size
    }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理数据结构
      const records = res.data.records || res.data.list || []

      // 处理封面URL
      const processedRecords = records.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))

      if (res.data.records) {
        res.data.records = processedRecords
      } else if (res.data.list) {
        res.data.list = processedRecords
      } else {
        res.data = processedRecords
      }
    }
    return res
  })
}

/**
 * 添加歌单
 * @param {Object} data 歌单数据
 * @param {File} cover 封面文件
 * @returns {Promise<any>}
 */
export function addPlaylist(data, cover) {
  // 确保数据中包含 type 对象
  const playlistData = {
    ...data,
    type: data.typeId ? { id: data.typeId } : null,
    // 确保 isOfficial 字段存在且为数字
    isOfficial: data.isOfficial !== undefined ? Number(data.isOfficial) : 0
  }

  console.log('添加歌单数据:', playlistData)

  const formData = new FormData()
  formData.append('playlist', new Blob([JSON.stringify(playlistData)], { type: 'application/json' }))

  if (cover) {
    formData.append('cover', cover)
  }

  return api.post('/playlist/add', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 更新歌单
 * @param {number} id 歌单ID
 * @param {Object} data 歌单数据
 * @param {File} cover 封面文件
 * @returns {Promise<any>}
 */
export function updatePlaylist(id, data, cover) {
  console.log('原始数据:', data)
  console.log('isOfficial类型:', typeof data.isOfficial, 'isOfficial值:', data.isOfficial)

  // 确保数据中包含 type 对象
  const playlistData = {
    ...data,
    type: data.typeId ? { id: data.typeId } : null,
    // 显式设置 isOfficial 字段，确保它是数字类型
    isOfficial: data.isOfficial === 1 ? 1 : 0
  }

  console.log('处理后的数据:', playlistData)
  console.log('处理后 isOfficial类型:', typeof playlistData.isOfficial, 'isOfficial值:', playlistData.isOfficial)

  const formData = new FormData()
  formData.append('playlist', new Blob([JSON.stringify(playlistData)], { type: 'application/json' }))

  if (cover) {
    formData.append('cover', cover)
  }

  return api.put(`/playlist/${id}`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除歌单
 * @param {number} id 歌单ID
 * @returns {Promise<any>}
 */
export function deletePlaylist(id) {
  return api.delete(`/playlist/${id}`)
}

/**
 * 收藏歌单
 * @param {number} id 歌单ID
 * @returns {Promise<any>}
 */
export function collectPlaylist(id) {
  return api.post(`/playlist/${id}/collect`)
}

/**
 * 取消收藏歌单
 * @param {number} id 歌单ID
 * @returns {Promise<any>}
 */
export function uncollectPlaylist(id) {
  return api.delete(`/playlist/${id}/collect`)
}

/**
 * 收藏/取消收藏歌单
 * @param {number} id 歌单ID
 * @param {boolean} isCollected 当前是否收藏
 * @returns {Promise<any>}
 */
export function toggleCollectPlaylist(id, isCollected) {
  if (isCollected) {
    return uncollectPlaylist(id)
  } else {
    return collectPlaylist(id)
  }
}

/**
 * 检查当前用户是否收藏了该歌单
 * @param {number} id 歌单ID
 * @returns {Promise<any>}
 */
export function isPlaylistCollected(id) {
  return api.get(`/playlist/${id}/is-collected`)
}

/**
 * 向歌单添加音乐
 * @param {number} id 歌单ID
 * @param {number} musicId 音乐ID
 * @returns {Promise<any>}
 */
export function addMusicToPlaylist(id, musicId) {
  return api.post(`/playlist/${id}/music/${musicId}`)
}

/**
 * 从歌单移除音乐
 * @param {number} id 歌单ID
 * @param {number} musicId 音乐ID
 * @returns {Promise<any>}
 */
export function removeMusicFromPlaylist(id, musicId) {
  return api.delete(`/playlist/${id}/music/${musicId}`)
}

/**
 * 播放歌单
 * @param {number} id 歌单ID
 * @returns {Promise<any>}
 */
export function playPlaylist(id) {
  return api.post(`/playlist/${id}/play`)
}

/**
 * 搜索歌单
 * @param {string} keyword 搜索关键词
 * @param {number} page 页码
 * @param {number} size 每页大小
 * @returns {Promise<any>}
 */
export function searchPlaylist(keyword, page = 1, size = 10) {
  return api.get('/playlist/search', {
    params: {
      keyword,
      page,
      size
    }
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 处理数据结构
      const records = res.data.records || res.data.list || []

      // 处理封面URL
      const processedRecords = records.map(item => ({
        ...item,
        cover: processImageUrl(item.cover)
      }))

      if (res.data.records) {
        res.data.records = processedRecords
      } else if (res.data.list) {
        res.data.list = processedRecords
      } else {
        res.data = processedRecords
      }
    }
    return res
  })
}
