import image from "@ohos:multimedia.image";
import buffer from "@ohos:buffer";
import fileIo from "@ohos:file.fs";
import picker from "@ohos:file.picker";
export class CLImageManager {
    // 将resource转成base64编码
    static async resource2Base64(res: Resource): Promise<string> {
        try {
            const pixelMap = await CLImageManager.resource2PixelMap(res);
            // 将PixelMap转换成base64
            const base64 = await CLImageManager.pixelMap2Base64(pixelMap);
            return base64;
        }
        catch (error) {
            AlertDialog.show({
                message: 'createBase64ByResource —— base64编码生成失败：\n' + JSON.stringify(error, null, 2)
            });
            return '';
        }
    }
    static async pixelMapToUint8Array(pixelMap: PixelMap): Promise<Uint8Array> {
        try {
            let base64Str = '';
            // 转换成base64
            const imagePackerApi: image.ImagePacker = image.createImagePacker();
            let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
            const data = await imagePackerApi.packing(pixelMap, packOpts);
            return new Uint8Array(data);
        }
        catch (error) {
            return new Uint8Array();
        }
    }
    static async pixelMap2Base64(pixelMap: PixelMap): Promise<string> {
        try {
            let base64Str = '';
            // 转换成base64
            const imagePackerApi: image.ImagePacker = image.createImagePacker();
            let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
            const data = await imagePackerApi.packing(pixelMap, packOpts);
            let buf: buffer.Buffer = buffer.from(data);
            base64Str = 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);
            return base64Str;
        }
        catch (error) {
            return '';
        }
    }
    static async uri2Base64(uri: string): Promise<string> {
        const pixelMap = await CLImageManager.uri2PixelMap(uri);
        if (pixelMap) {
            const base64Str = await CLImageManager.pixelMap2Base64(pixelMap);
            return base64Str;
        }
        else {
            return '';
        }
    }
    static async resource2PixelMap(res: Resource): Promise<PixelMap> {
        // 资源管理器
        let resourceManager = getContext().resourceManager;
        // 通过resource创建Uint8Array
        let imageArray = await resourceManager.getMediaContent(res);
        let pixelBuffer = new Uint8Array(imageArray).buffer as Object as ArrayBuffer;
        let imageResource = image.createImageSource(pixelBuffer);
        let pixelMap = await imageResource.createPixelMap({ editable: true });
        return pixelMap;
    }
    static async getImageUrisFromAlbum(photoNum: number = 1): Promise<string> {
        try {
            const photo = new picker.PhotoViewPicker();
            const result = await photo.select({
                maxSelectNumber: photoNum,
                MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE
            });
            return result.photoUris[0];
        }
        catch (error) {
            AlertDialog.show({
                message: '选取相册图片uris失败：\n' + JSON.stringify(error, null, 2)
            });
            return '';
        }
    }
    static async createPixelMapByClone(pixelMap: PixelMap, desiredPixelFormat?: image.PixelMapFormat): Promise<PixelMap> {
        // 获取当前PixelMap的图片信息。
        const imageInfo = pixelMap.getImageInfoSync();
        // 读取当前PixelMap的图像像素数据，并按照当前PixelMap的像素格式写入缓冲区数组。
        const buffer = new ArrayBuffer(pixelMap.getPixelBytesNumber());
        pixelMap.readPixelsToBufferSync(buffer);
        // 根据当前PixelMap的图片信息，生成初始化选项。
        const options: image.InitializationOptions = {
            // 当前PixelMap的像素格式。
            srcPixelFormat: imageInfo.pixelFormat,
            // 新PixelMap的像素格式。
            pixelFormat: desiredPixelFormat ?? imageInfo.pixelFormat,
            // 当前PixelMap的尺寸大小。
            size: imageInfo.size
        };
        // 根据初始化选项和缓冲区数组，生成新PixelMap。
        return image.createPixelMapSync(buffer, options);
    }
    static async loadTempImageAndShow(path: string): Promise<PixelMap | undefined> {
        try {
            const source = await image.createImageSource(path);
            const pixelMap = await source.createPixelMap({});
            return pixelMap;
        }
        catch (err) {
            console.error("临时图片加载失败", err);
            return undefined;
        }
    }
    static async uri2PixelMap(uri: string): Promise<PixelMap> {
        const file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY);
        const imageSource = image.createImageSource(file.fd); // 通过文件描述符创建图片资源
        const imageInfo: image.ImageInfo = await imageSource.getImageInfo();
        const height = imageInfo.size.height;
        const width = imageInfo.size.width;
        const options: image.DecodingOptions = {
            editable: true,
            desiredSize: { height, width }
        };
        const pixelMap: PixelMap = await imageSource.createPixelMap(options);
        fileIo.closeSync(file);
        return pixelMap;
    }
    static async imageSource2PixelMap(imageSource: image.ImageSource): Promise<PixelMap> {
        const imageInfo: image.ImageInfo = await imageSource.getImageInfo();
        const height = imageInfo.size.height;
        const width = imageInfo.size.width;
        const options: image.DecodingOptions = {
            editable: true,
            desiredSize: { height, width }
        };
        const pixelMap: PixelMap = await imageSource.createPixelMap(options);
        return pixelMap;
    }
}
