import { reactive } from 'vue'
import { AUTH_SESSION_STORAGE_KEY, readStorage, removeStorage } from '../utils/storage'
import { createLoginLog } from '../utils/data'

const API_BASE_URL = '/api'
const TOKEN_EXPIRING_SOON_MS = 10 * 60 * 1000

/**
 * 全局请求状态（响应式）
 * pendingCount > 0 表示有请求正在进行
 */
export const requestState = reactive({ pendingCount: 0 })

function getAuthSession() {
  return readStorage(AUTH_SESSION_STORAGE_KEY, null)
}

function isSessionExpired(session) {
  if (!session?.token) return true
  if (!session?.expiresAt) return false
  return Date.now() >= session.expiresAt
}

function clearExpiredSession() {
  removeStorage(AUTH_SESSION_STORAGE_KEY)
}

function dispatchUnauthorized(reason = '登录状态已失效，请重新登录') {
  if (typeof window === 'undefined') return
  window.dispatchEvent(new CustomEvent('wangpan:unauthorized', { detail: { reason } }))
}

function dispatchForbidden(reason = '当前账号无权执行此操作') {
  if (typeof window === 'undefined') return
  window.dispatchEvent(new CustomEvent('wangpan:forbidden', { detail: { reason } }))
}

function dispatchSessionExpiring(reason = '登录状态将在 10 分钟内过期，请注意及时重新登录') {
  if (typeof window === 'undefined') return
  window.dispatchEvent(new CustomEvent('wangpan:session-expiring', { detail: { reason } }))
}

function notifySessionExpiring(session) {
  if (!session?.expiresAt || session?.expiringSoonNotified) return
  const remainingMs = session.expiresAt - Date.now()
  if (remainingMs > 0 && remainingMs <= TOKEN_EXPIRING_SOON_MS) {
    const nextSession = {
      ...session,
      expiringSoonNotified: true,
    }
    localStorage.setItem(AUTH_SESSION_STORAGE_KEY, JSON.stringify(nextSession))
    dispatchSessionExpiring()
  }
}

function buildAuthHeaders(extraHeaders = {}) {
  const session = getAuthSession()
  if (isSessionExpired(session)) {
    clearExpiredSession()
    return extraHeaders
  }

  const token = session?.token
  const tokenType = session?.tokenType || 'Bearer'

  if (!token) {
    return extraHeaders
  }

  return {
    Authorization: `${tokenType} ${token}`,
    ...extraHeaders,
  }
}

async function request(url, options = {}) {
  // 延迟显示：150ms内完成的请求不显示加载动画（避免闪烁）
  let showTimer = null
  let incremented = false
  if (!options.silent) {
    showTimer = setTimeout(() => { requestState.pendingCount++; incremented = true }, 150)
  }

  const session = getAuthSession()
  const requiresAuth = options.requiresAuth !== false

  if (requiresAuth && isSessionExpired(session)) {
    clearTimeout(showTimer)
    clearExpiredSession()
    dispatchUnauthorized('登录已过期，请重新登录')
    const error = new Error('登录已过期，请重新登录')
    error.status = 401
    error.code = 401
    throw error
  }

  if (requiresAuth) {
    notifySessionExpiring(session)
  }

  try {
    console.log(`[API Request] ${options.method || 'GET'} ${url}`)
    
    const isFormData = options.body instanceof FormData
    const response = await fetch(url, {
      headers: {
        ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
        ...buildAuthHeaders(options.headers || {}),
      },
      ...options,
    })

    const contentType = response.headers.get('content-type') || ''
    const data = contentType.includes('application/json') ? await response.json() : null

    console.log(`[API Response] ${response.status}`, data)

    if (!response.ok) {
      if (response.status === 401) {
        clearExpiredSession()
        dispatchUnauthorized(data?.message || '登录状态已失效，请重新登录')
      }

      if (response.status === 403) {
        dispatchForbidden(data?.message || '当前账号无权执行此操作')
      }

      const error = new Error(data?.message || `请求失败：${response.status}`)
      error.status = response.status
      error.code = data?.code ?? response.status
      error.payload = data
      throw error
    }

    return data
  } catch (err) {
    // 网络错误（如 Failed to fetch）
    if (err.name === 'TypeError' && err.message === 'Failed to fetch') {
      console.error('[Network Error] 无法连接到后端服务，请检查：')
      console.error('1. 后端服务是否启动在 http://localhost:8888')
      console.error('2. 是否有 CORS 跨域问题')
      console.error('3. 网络连接是否正常')
      
      const networkError = new Error('无法连接到后端服务，请检查后端是否启动')
      networkError.isNetworkError = true
      throw networkError
    }
    
    // 其他错误直接抛出
    throw err
  } finally {
    clearTimeout(showTimer)
    if (incremented) {
      requestState.pendingCount--
    }
  }
}

export function login(payload) {
  return request(`${API_BASE_URL}/login`, {
    method: 'POST',
    requiresAuth: false,
    body: JSON.stringify({
      username: payload.username,
      password: payload.password,
    }),
  })
}

export function register(payload) {
  const body = { username: payload.username, password: payload.password }
  if (payload.email) body.email = payload.email
  if (payload.phone) body.phone = payload.phone
  return request(`${API_BASE_URL}/register`, {
    method: 'POST',
    requiresAuth: false,
    body: JSON.stringify(body),
  })
}

export function fetchDashboardData() {
  return Promise.resolve({
    code: 200,
    data: [],
  })
}

export function saveRecord(payload) {
  return Promise.resolve({
    code: 200,
    data: payload,
  })
}

export function deleteRecord(id) {
  return Promise.resolve({
    code: 200,
    data: { id },
  })
}

export function exportData() {
  return Promise.resolve({
    code: 200,
    data: {},
  })
}

export function resetData() {
  return Promise.resolve({
    code: 200,
    data: [],
  })
}

export function fetchLoginLogs(params = {}) {
  const searchParams = new URLSearchParams()
  if (params.userId) searchParams.set('userId', String(params.userId))
  if (params.username) searchParams.set('username', params.username)
  if (params.result) searchParams.set('result', params.result)
  if (params.startDate) searchParams.set('startDate', params.startDate)
  if (params.endDate) searchParams.set('endDate', params.endDate)
  if (params.pageNo) searchParams.set('pageNo', String(params.pageNo))
  if (params.pageSize) searchParams.set('pageSize', String(params.pageSize))

  const query = searchParams.toString()
  return request(`${API_BASE_URL}/login-logs${query ? `?${query}` : ''}`, {
    method: 'GET',
  }).then((res) => ({
    ...res,
    data: {
      ...(res?.data || {}),
      list: Array.isArray(res?.data?.list)
        ? res.data.list.map((item) =>
            createLoginLog(
              item?.userAgent || '未知设备',
              item?.loginIp || '127.0.0.1',
              {
                id: item?.id,
                time: item?.loginTime,
                hashSeed: `${item?.userId || ''}-${item?.loginUsername || ''}-${item?.loginTime || ''}`,
                username: item?.loginUsername,
                result: item?.loginResult,
                userId: item?.userId,
                rawUserAgent: item?.userAgent,
                failReason: item?.failReason,
              },
            ),
          )
        : [],
      total: res?.data?.total || 0, // 返回总记录数
    },
  }))
}

export function fetchTmdbConfig() {
  return request(`${API_BASE_URL}/tmdb/key`, {
    method: 'GET',
  })
}

export function saveTmdbConfig(payload) {
  return request(`${API_BASE_URL}/tmdb/key`, {
    method: 'POST',
    body: JSON.stringify({
      tmdbApiKey: payload.tmdbApiKey,
    }),
  })
}

// ==================== 网盘管理 API ====================

/**
 * 创建网盘
 * @param {Object} payload - { name, description, logoData }
 * @returns {Promise}
 */
export function createDrive(payload) {
  return request(`${API_BASE_URL}/drive`, {
    method: 'POST',
    body: JSON.stringify({
      name: payload.name,
      description: payload.description || '',
      logoData: payload.logoData || '',
    }),
  })
}

/**
 * 查询网盘列表
 * @param {Object} params - { pageNo, pageSize }
 * @returns {Promise}
 */
export function fetchDriveList(params = {}) {
  const searchParams = new URLSearchParams()
  if (params.pageNo) searchParams.set('pageNo', String(params.pageNo))
  if (params.pageSize) searchParams.set('pageSize', String(params.pageSize))
  
  const query = searchParams.toString()
  return request(`${API_BASE_URL}/drive${query ? `?${query}` : ''}`, {
    method: 'GET',
  })
}

/**
 * 删除网盘
 * @param {string} driveId - 网盘ID
 * @returns {Promise}
 */
export function deleteDrive(driveId) {
  return request(`${API_BASE_URL}/drive/${driveId}`, {
    method: 'DELETE',
  })
}

/**
 * 更新网盘
 * @param {string} driveId - 网盘ID
 * @param {Object} payload - { name, description, logoData }
 * @returns {Promise}
 */
export function updateDrive(driveId, payload) {
  return request(`${API_BASE_URL}/drive/${driveId}`, {
    method: 'PUT',
    body: JSON.stringify({
      name: payload.name,
      description: payload.description,
      logoData: payload.logoData,
    }),
  })
}

// ==================== 文件夹管理 API ====================

/**
 * 查询文件夹列表
 * @param {string|number} driveId - 网盘ID
 * @param {Object} params - { parentId }
 * @returns {Promise}
 */
export function fetchFolders(driveId, params = {}) {
  const searchParams = new URLSearchParams()
  if (params.parentId !== undefined) searchParams.set('parentId', String(params.parentId))
  const query = searchParams.toString()
  return request(`${API_BASE_URL}/drive/${driveId}/folders${query ? `?${query}` : ''}`, {
    method: 'GET',
  })
}

/**
 * 查询文件夹详情
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} folderId - 文件夹ID
 * @returns {Promise}
 */
export function fetchFolderDetail(driveId, folderId) {
  return request(`${API_BASE_URL}/drive/${driveId}/folders/${folderId}`, {
    method: 'GET',
  })
}

/**
 * 创建文件夹
 * @param {string|number} driveId - 网盘ID
 * @param {Object} payload - { name, parentId, description, sortWeight }
 * @returns {Promise}
 */
export function createFolderInDrive(driveId, payload) {
  return request(`${API_BASE_URL}/drive/${driveId}/folders`, {
    method: 'POST',
    body: JSON.stringify({
      name: payload.name,
      parentId: payload.parentId ?? 0,
      description: payload.description || '',
      sortWeight: payload.sortWeight ?? 0,
    }),
  })
}

/**
 * 更新文件夹
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} folderId - 文件夹ID
 * @param {Object} payload - { name, description, sortWeight }
 * @returns {Promise}
 */
export function updateFolderInDrive(driveId, folderId, payload) {
  const body = {}
  if (payload.name !== undefined) body.name = payload.name
  if (payload.description !== undefined) body.description = payload.description
  if (payload.sortWeight !== undefined) body.sortWeight = payload.sortWeight
  return request(`${API_BASE_URL}/drive/${driveId}/folders/${folderId}`, {
    method: 'PUT',
    body: JSON.stringify(body),
  })
}

/**
 * 删除文件夹
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} folderId - 文件夹ID
 * @returns {Promise}
 */
export function deleteFolderInDrive(driveId, folderId) {
  return request(`${API_BASE_URL}/drive/${driveId}/folders/${folderId}`, {
    method: 'DELETE',
  })
}

// ==================== 电影文件管理 API ====================

/**
 * 查询指定文件夹下的电影列表
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} folderId - 文件夹ID，0表示根目录
 * @param {Object} params - { pageNo, pageSize }
 * @returns {Promise}
 */
export function fetchFolderMovies(driveId, folderId, params = {}) {
  const searchParams = new URLSearchParams()
  if (params.pageNo) searchParams.set('pageNo', String(params.pageNo))
  if (params.pageSize) searchParams.set('pageSize', String(params.pageSize))
  const query = searchParams.toString()
  return request(`${API_BASE_URL}/drive/${driveId}/folders/${folderId}/movies${query ? `?${query}` : ''}`, {
    method: 'GET',
  })
}

/**
 * 查询电影列表
 * @param {string|number} driveId - 网盘ID
 * @param {Object} params - { folderId, pageNo, pageSize }
 * @returns {Promise}
 */
export function fetchMovieList(driveId, params = {}) {
  const searchParams = new URLSearchParams()
  if (params.folderId !== undefined) searchParams.set('folderId', String(params.folderId))
  if (params.pageNo) searchParams.set('pageNo', String(params.pageNo))
  if (params.pageSize) searchParams.set('pageSize', String(params.pageSize))
  const query = searchParams.toString()
  return request(`${API_BASE_URL}/drive/${driveId}/movies${query ? `?${query}` : ''}`, {
    method: 'GET',
  })
}

/**
 * 查询电影详情
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} movieId - 电影ID
 * @returns {Promise}
 */
export function fetchMovieDetail(driveId, movieId) {
  return request(`${API_BASE_URL}/drive/${driveId}/movies/${movieId}`, {
    method: 'GET',
  })
}

/**
 * 创建电影（仅登记文件名）
 * @param {string|number} driveId - 网盘ID
 * @param {Object} payload - { title, folderId }
 * @returns {Promise}
 */
export function createMovieInDrive(driveId, payload) {
  return request(`${API_BASE_URL}/drive/${driveId}/movies`, {
    method: 'POST',
    body: JSON.stringify({
      title: payload.title,
      folderId: payload.folderId ?? 0,
    }),
  })
}

/**
 * 更新电影信息
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} movieId - 电影ID
 * @param {Object} payload - 可选字段：title, originalName, subtitle, description, rating, tags, category
 * @returns {Promise}
 */
export function updateMovieInDrive(driveId, movieId, payload) {
  const body = {}
  if (payload.title !== undefined) body.title = payload.title
  if (payload.originalName !== undefined) body.originalName = payload.originalName
  if (payload.subtitle !== undefined) body.subtitle = payload.subtitle
  if (payload.description !== undefined) body.description = payload.description
  if (payload.rating !== undefined) body.rating = payload.rating
  if (payload.tags !== undefined) body.tags = payload.tags
  if (payload.category !== undefined) body.category = payload.category

  return request(`${API_BASE_URL}/drive/${driveId}/movies/${movieId}`, {
    method: 'PUT',
    body: JSON.stringify(body),
  })
}

/**
 * 删除电影
 * @param {string|number} driveId - 网盘ID
 * @param {string|number} movieId - 电影ID
 * @returns {Promise}
 */
export function deleteMovieInDrive(driveId, movieId) {
  return request(`${API_BASE_URL}/drive/${driveId}/movies/${movieId}`, {
    method: 'DELETE',
  })
}

/**
 * 查询重复电影
 * @returns {Promise}
 */
export function fetchMovieDuplicates() {
  return request(`${API_BASE_URL}/drive/movies/duplicates`, {
    method: 'GET',
  })
}

// ==================== 图标管理 API ====================

/**
 * 查询图标列表
 * @returns {Promise}
 */
export function fetchIconList() {
  return request(`${API_BASE_URL}/icon`, { method: 'GET' })
}

/**
 * 查询单个图标详情
 * @param {string|number} id - 图标ID
 * @returns {Promise}
 */
export function fetchIconDetail(id) {
  return request(`${API_BASE_URL}/icon/${id}`, { method: 'GET' })
}

/**
 * 创建图标
 * @param {Object} payload - { name, url?, internalUrl?, linkType?, description?, sortOrder? }
 * @returns {Promise}
 */
export function createIcon(payload) {
  return request(`${API_BASE_URL}/icon`, {
    method: 'POST',
    body: JSON.stringify({
      name: payload.name,
      url: payload.url || '',
      internalUrl: payload.internalUrl || '',
      linkType: payload.linkType || 'external',
      description: payload.description || '',
      sortOrder: payload.sortOrder ?? 0,
    }),
  })
}

/**
 * 更新图标
 * @param {string|number} id - 图标ID
 * @param {Object} payload - { name?, url?, internalUrl?, linkType?, description?, sortOrder? }
 * @returns {Promise}
 */
export function updateIcon(id, payload) {
  const body = {}
  if (payload.name !== undefined) body.name = payload.name
  if (payload.url !== undefined) body.url = payload.url
  if (payload.internalUrl !== undefined) body.internalUrl = payload.internalUrl
  if (payload.linkType !== undefined) body.linkType = payload.linkType
  if (payload.description !== undefined) body.description = payload.description
  if (payload.sortOrder !== undefined) body.sortOrder = payload.sortOrder
  return request(`${API_BASE_URL}/icon/${id}`, {
    method: 'PUT',
    body: JSON.stringify(body),
  })
}

/**
 * 删除图标
 * @param {string|number} id - 图标ID
 * @returns {Promise}
 */
export function deleteIcon(id) {
  return request(`${API_BASE_URL}/icon/${id}`, { method: 'DELETE' })
}

/**
 * 上传图标 Logo 图片
 * @param {string|number} id - 图标ID
 * @param {File} file - 图片文件（png/jpg/gif/webp/ico，最大 1MB）
 * @returns {Promise} 返回 { code, data: { id, name, logoUrl, updateTime } }
 */
export function uploadIconLogo(id, file) {
  const formData = new FormData()
  formData.append('file', file)
  return request(`${API_BASE_URL}/icon/${id}/logo`, {
    method: 'POST',
    body: formData,
  })
}

// ==================== 每日推荐 API ====================

/**
 * 查询每日推荐电影
 * @returns {Promise} 返回 { code, data: { list: [...], count: N } }
 */
export function fetchRecommendMovies() {
  return request(`${API_BASE_URL}/movies/recommend`, {
    method: 'GET',
  })
}

// ==================== 用户管理 API（仅管理员） ====================

/**
 * 查询用户列表
 * @param {Object} params - 查询参数
 * @param {string} [params.username] - 用户名模糊搜索
 * @param {number} [params.status] - 状态：0=禁用, 1=正常, 2=锁定
 * @param {number} [params.userType] - 角色：0=普通, 1=VIP, 2=管理员
 * @param {number} [params.pageNo] - 页码，默认1
 * @param {number} [params.pageSize] - 每页条数，默认20
 * @returns {Promise} 返回格式：{ code: 200, data: { total, list: [{ id, username, userType, status, ... }], pageNo, pageSize } }
 */
export function fetchUserList(params = {}) {
  const searchParams = new URLSearchParams()
  if (params.username) searchParams.set('username', params.username)
  if (params.status !== undefined && params.status !== '') searchParams.set('status', String(params.status))
  if (params.userType !== undefined && params.userType !== '') searchParams.set('userType', String(params.userType))
  if (params.pageNo) searchParams.set('pageNo', String(params.pageNo))
  if (params.pageSize) searchParams.set('pageSize', String(params.pageSize))

  const query = searchParams.toString()
  return request(`${API_BASE_URL}/users${query ? `?${query}` : ''}`, {
    method: 'GET',
  })
}

/**
 * 新增用户
 * @param {Object} payload - 用户信息
 * @param {string} payload.username - 用户名（必填）
 * @param {string} payload.password - 密码（必填）
 * @param {string} [payload.email] - 邮箱（可选）
 * @param {string} [payload.phone] - 手机号（可选）
 * @param {string} [payload.realName] - 真实姓名（可选）
 * @param {number} [payload.status=1] - 状态：0=禁用, 1=正常
 * @param {number} [payload.userType=0] - 角色：0=普通, 1=VIP, 2=管理员
 * @returns {Promise}
 */
export function createUser(payload) {
  return request(`${API_BASE_URL}/users`, {
    method: 'POST',
    body: JSON.stringify({
      username: payload.username,
      password: payload.password,
      email: payload.email || '',
      phone: payload.phone || '',
      realName: payload.realName || '',
      status: payload.status !== undefined ? payload.status : 1,
      userType: payload.userType !== undefined ? payload.userType : 0,
    }),
  })
}

/**
 * 修改用户信息
 * @param {number} userId - 用户ID
 * @param {Object} payload - 需要修改的字段（部分更新）
 * @param {string} [payload.email] - 邮箱
 * @param {string} [payload.phone] - 手机号
 * @param {string} [payload.realName] - 真实姓名
 * @param {number} [payload.status] - 状态：0=禁用, 1=正常, 2=锁定
 * @param {number} [payload.userType] - 角色：0=普通, 1=VIP, 2=管理员
 * @returns {Promise}
 */
export function updateUser(userId, payload) {
  // 构建请求体，只包含需要更新的字段
  const body = {}
  if (payload.email !== undefined) body.email = payload.email
  if (payload.phone !== undefined) body.phone = payload.phone
  if (payload.realName !== undefined) body.realName = payload.realName
  if (payload.status !== undefined) body.status = payload.status
  if (payload.userType !== undefined) body.userType = payload.userType

  return request(`${API_BASE_URL}/users/${userId}`, {
    method: 'PUT',
    body: JSON.stringify(body),
  })
}

/**
 * 删除用户（软删除，将is_deleted设为1）
 * @param {number} userId - 要删除的用户ID
 * @returns {Promise}
 */
export function deleteUser(userId) {
  return request(`${API_BASE_URL}/users/${userId}`, {
    method: 'DELETE',
  })
}

// ==================== 刮削日志 API ====================

/**
 * 查询刮削日志列表
 * @param {Object} params - 查询参数
 * @param {number} [params.pageNo] - 页码，默认1
 * @param {number} [params.pageSize] - 每页条数，默认20
 * @returns {Promise} 返回格式：{ code: 200, data: { total, list: [{ id, scanTime, totalMovies, successCount, failCount }], pageNo, pageSize } }
 */
export function fetchScraperLogs(params = {}) {
  const searchParams = new URLSearchParams()
  if (params.pageNo) searchParams.set('pageNo', String(params.pageNo))
  if (params.pageSize) searchParams.set('pageSize', String(params.pageSize))

  const query = searchParams.toString()
  return request(`${API_BASE_URL}/tmdb-scraper/scraper-logs${query ? `?${query}` : ''}`, {
    method: 'GET',
  })
}

// ==================== 批量刮削 API ====================

/**
 * 批量刮削电影
 * @param {number[]} movieIds - 电影ID数组
 * @returns {Promise} 返回格式：{ code: 200, message: "批量刮削完成", data: { successCount, failCount, total } }
 */
export function batchScrapeMovies(movieIds) {
  return request(`${API_BASE_URL}/tmdb-scraper/batch-scrape`, {
    method: 'POST',
    body: JSON.stringify({
      movieIds: movieIds,
    }),
  })
}

/**
 * 重新刮削所有电影（不指定ID，刮削全部）
 * @returns {Promise} 返回格式：{ code: 200, message: "批量刮削完成", data: { successCount, failCount, total } }
 */
export function batchScrapeAll() {
  return request(`${API_BASE_URL}/tmdb-scraper/batch-scrape`, {
    method: 'POST',
    body: JSON.stringify({}),
  })
}

// ==================== 单部影片刮削 API ====================

/**
 * 重新刮削单部电影
 * @param {number} movieId - 电影ID
 * @returns {Promise} 返回格式：{ code: 200, message: "刮削完成", data: { movieId, title, rating, posterUrl } }
 */
export function scrapeMovie(movieId) {
  return request(`${API_BASE_URL}/tmdb-scraper/scrape?movieId=${movieId}`, {
    method: 'POST',
  })
}

// ==================== 刮削状态 API ====================

/**
 * 查询/触发电影刮削状态
 * @param {string|number} movieId - 电影ID
 * @returns {Promise} 返回格式：{ code: 200, data: { movieId, title, status, message, posterUrl?, backdropUrl?, rating?, category?, tags? } }
 * status: scraping=刮削中, success=刮削成功, failed=刮削失败
 */
export function fetchScrapeStatus(movieId) {
  return request(`${API_BASE_URL}/movies/${movieId}/scrape-status`, {
    method: 'GET',
  })
}

/**
 * 批量查询电影刮削状态（逐个查询后合并结果）
 * @param {number[]} movieIds - 电影ID数组
 * @returns {Promise} 返回格式：{ code: 200, data: [{ movieId, title, status, message, posterUrl?, backdropUrl?, rating?, category?, tags? }] }
 */
export async function fetchBatchScrapeStatus(movieIds) {
  if (!movieIds || movieIds.length === 0) {
    return { code: 200, data: [] }
  }
  
  // 并发查询每个电影的刮削状态
  const promises = movieIds.map(async (movieId) => {
    try {
      const result = await fetchScrapeStatus(movieId)
      if (result?.code === 200 && result?.data) {
        return result.data
      }
      return null
    } catch (err) {
      console.warn(`查询电影[movieId=${movieId}]刮削状态失败`, err)
      return null
    }
  })
  
  const results = await Promise.all(promises)
  return {
    code: 200,
    data: results.filter(Boolean),
  }
}
