/**
 * 图片处理模块
 * 负责图片选择、上传、删除等操作
 */

import oss from '../../../utils/oss.js';

/**
 * 选择图片
 * @param {Number} maxCount - 最大数量
 * @param {Number} currentCount - 当前数量
 * @returns {Promise} 选择的图片路径数组
 */
export function chooseImage(maxCount = 6, currentCount = 0) {
	const remainCount = maxCount - currentCount;

	if (remainCount <= 0) {
		wx.showToast({
			title: `最多只能上传${maxCount}张图片`,
			icon: 'none'
		});
		return Promise.resolve([]);
	}

	return new Promise((resolve, reject) => {
		wx.chooseMedia({
			count: remainCount,
			mediaType: ['image'],
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: function(res) {
				const newImages = res.tempFiles.map(function(file) {
					return file.tempFilePath;
				});
				resolve(newImages);
			},
			fail: function(err) {
				reject(err);
			}
		});
	});
}

/**
 * 上传图片到 OSS
 * @param {String} tempFilePath - 临时文件路径
 * @param {String} taskId - 任务ID
 * @param {String} subDir - 子目录（如 'subjective', 'essay'）
 * @returns {Promise} 上传后的图片URL
 */
export function uploadImage(tempFilePath, taskId, subDir = 'subjective') {
	return new Promise(function(resolve, reject) {
		(async function(){
			try {
				var cfg = await oss.getOssConfig('camp');
				if (!cfg) return reject(new Error('无法获取上传凭证'));

				var ext = 'jpg';
				if (/(\.png)$/i.test(tempFilePath)) ext = 'png';
				else if (/(\.jpeg)$/i.test(tempFilePath)) ext = 'jpeg';
				else if (/(\.webp)$/i.test(tempFilePath)) ext = 'webp';

				var key = oss.buildOssKey({
					baseDir: cfg.dir || 'camp',
					subDir: subDir,
					userId: wx.getStorageSync('wxuserid') || 'anonymous',
					taskId: taskId || 'unknown',
					ext: ext
				});

				wx.uploadFile({
					url: cfg.host,
					filePath: tempFilePath,
					name: 'file',
					formData: {
						key: key,
						policy: cfg.policy,
						'x-oss-signature': cfg.signature,
						'x-oss-signature-version': cfg.signatureVersion,
						'x-oss-credential': cfg.credential,
						'x-oss-date': cfg.date,
						'x-oss-security-token': cfg.securityToken,
						success_action_status: '200'
					},
					success: function(res){
						if (res.statusCode === 204 || res.statusCode === 200) {
							var url = cfg.host.replace(/\/$/, '') + '/' + key;
							resolve(url);
						} else {
							reject(new Error('oss_upload_failed'));
						}
					},
					fail: function(err){ reject(err); }
				});
			} catch (e) { reject(e); }
		})();
	});
}

/**
 * 预览图片
 * @param {String} current - 当前图片URL
 * @param {Array} urls - 所有图片URL数组
 */
export function previewImage(current, urls) {
	if (!current || !urls || urls.length === 0) {
		return;
	}
	wx.previewImage({
		current: current,
		urls: urls
	});
}

