import Taro from '@tarojs/taro'; import { STORE_RATING_MAX_IMAGES } from '@dukang/shared-types'; export async function chooseAndUploadRatingImages(already: number): Promise { const remain = STORE_RATING_MAX_IMAGES - already; if (remain <= 0) { throw new Error(`最多上传${STORE_RATING_MAX_IMAGES}张图片`); } const picked = await Taro.chooseImage({ count: remain, sizeType: ['compressed'], sourceType: ['album', 'camera'], }); const paths = picked.tempFilePaths || []; if (!paths.length) return []; const urls: string[] = []; for (const path of paths) { urls.push(await uploadRatingImage(path)); } return urls; } export async function uploadRatingImage(tempFilePath: string): Promise { const { API_BASE, CLIENT_APP, getToken } = await import('./api'); const { compressWeappImageIfNeeded } = await import('./compress-image'); const token = getToken(); if (!token) throw new Error('请先登录'); const filePath = await compressWeappImageIfNeeded(tempFilePath); const res = await Taro.uploadFile({ url: `${API_BASE}/common/resources/upload`, filePath, name: 'file', formData: { bizType: 'STORE_RATING', mediaType: 'IMAGE', }, header: { Authorization: `Bearer ${token}`, 'X-Client-App': CLIENT_APP, }, }); let body: { code?: number; message?: string; data?: { url?: string } } = {}; try { body = JSON.parse(String(res.data || '{}')) as typeof body; } catch { throw new Error('图片上传响应异常'); } if (res.statusCode === 401 || body.code === 401) { throw new Error(body.message || '登录已过期,请重新登录'); } if (res.statusCode >= 400 || body.code !== 0 || !body.data?.url) { throw new Error(body.message || '图片上传失败'); } return body.data.url; }