import { A4_EXPORT_SIZE_150DPI } from '../constants/colors';

/**
 * 导出为固定打印分辨率（A4 150 DPI），避免高 DPR 设备导出过大图导致打印慢、文件大
 */
const doSaveImage = (canvas: Canvas) => {
    const { width: destWidth, height: destHeight } = A4_EXPORT_SIZE_150DPI;
    wx.canvasToTempFilePath({
        canvas,
        fileType: 'jpg',
        quality: 0.9,
        destWidth,
        destHeight,
        success: (res) => {
            wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: () => {
                    // 下载成功提示（下载次数记录在 downloadPrint.ts 中处理）
                    wx.showToast({
                        title: '保存成功，请在相册中查看',
                        icon: 'success',
                        duration: 2000,
                    });
                },
                // fail: () => wx.showToast({
                //     title: '保存涂色卡失败，请重试！',
                //     icon: 'none',
                //     duration: 2000,
                // })
            });
        },
        fail: () => {
            wx.showToast({
                title: '生成涂色卡失败，请重试！',
                icon: 'none',
                duration: 2000,
            });
        },
    });
};

const requestPhotoPermission = (canvas: Canvas) => {
    wx.authorize({
        scope: 'scope.writePhotosAlbum',
        success: () => doSaveImage(canvas),
        fail: () =>
            wx.showToast({
                title: '请在“设置-添加到相册”中开启相册权限以保存涂色卡',
                icon: 'none',
                duration: 3000,
            }),
    });
};

export const checkAndSaveImage = (canvas: Canvas) => {
    wx.getSetting({
        success: (res) => {
            if (!res.authSetting['scope.writePhotosAlbum']) {
                requestPhotoPermission(canvas);
            } else {
                doSaveImage(canvas);
            }
        },
    });
};
