import { Platform } from 'react-native';
import { CameraRoll } from "@react-native-camera-roll/camera-roll";
import RNFS from 'react-native-fs';

const ImageUtil = {
    saveImg: async (img: string) => {
        try {
            if (Platform.OS === 'ios') {
                const result = await CameraRoll.save(img, {
                    type: 'photo'
                });
                console.log('保存成功！地址：', result);
                return result;
            } else {
                // Android 处理
                const storeLocation = `${RNFS.CachesDirectoryPath}`;
                const pathName = `${new Date().getTime()}_${Math.floor(Math.random() * 9999)}.jpg`;
                const downloadPath = `${storeLocation}/${pathName}`;

                // 下载或复制文件
                const res = await RNFS.downloadFile({
                    fromUrl: img,
                    toFile: downloadPath,
                }).promise;

                if (res && res.statusCode === 200) {
                    const result = await CameraRoll.save(`file://${downloadPath}`, {
                        type: 'photo'
                    });
                    
                    // 清理临时文件
                    try {
                        await RNFS.unlink(downloadPath);
                    } catch (e) {
                        console.log('清理临时文件失败:', e);
                    }

                    console.log('保存成功！地址：', result);
                    return result;
                }
            }
        } catch (error) {
            console.error('保存失败！', error);
            throw error;
        }
    }
};

export default ImageUtil;