import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { View, Canvas } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";

export default function MomentShare() {
    const user = useSelector((state: any) => state.user);

    const info = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync()
    const dpr = info.pixelRatio; // 获取设备的像素比


    useEffect(() => {
        if (user.isLogin) {
            // beginDraw()
            downCover()
        }
    }, [user])

    useDidShow(() => {
        if (user.isLogin) {
            // beginDraw()
            downCover()
        }
    })

    async function downCover() {
        const urls = ['https://background-pictures.oss-cn-beijing.aliyuncs.com/share_cover/invite.png', user.avatar]
        try {
            const imagePaths = await Promise.all(urls.map(downloadImage));
            beginDraw(imagePaths);
        } catch (error) {
            console.error('下载图片错误:', error);
        }
    }

    function downloadImage(url) {
        return new Promise((resolve, reject) => {
            Taro.downloadFile({
                url,
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.tempFilePath);
                    } else {
                        reject(new Error('图片下载失败'));
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }

    function beginDraw(imagePaths) {

        const query = Taro.createSelectorQuery();
        query.select(`#moment_share`).fields({ node: true, size: true });
        query.exec((res) => {
            const _canvas = res[0].node;
            _canvas.width = res[0].width * dpr;
            _canvas.height = res[0].height * dpr;
            const ctx = _canvas.getContext('2d');
            global.canvas2 = _canvas

            drawDetail(ctx, imagePaths, _canvas)
        });
    }

    function drawDetail(ctx, imagePaths, canvas) {
        const img = canvas.createImage(); // 创建图像对象
        img.src = imagePaths[0]
        img.onload = () => {
            ctx.drawImage(img, 0, 0, 420 * dpr, 336 * dpr);
            ctx.stroke();
            const img1 = canvas.createImage(); // 创建图像对象
            img1.src = imagePaths[1]
            img1.onload = () => {
                // ctx.fillStyle = '#ff0000'
                // ctx.fillRect(0, 0, 420 * dpr, 336 * dpr);

                const x = 64 * dpr; // 矩形左上角 x 坐标
                const y = 212 * dpr; // 矩形左上角 y 坐标
                const width = 292 * dpr; // 矩形宽度
                const height = 72 * dpr; // 矩形高度
                const radius = 18 * dpr; // 圆角半径

                // 绘制带圆角的矩形

                ctx.beginPath();
                ctx.moveTo(x + radius, y); // 移动到左上角的圆角位置
                ctx.arcTo(x + width, y, x + width, y + height, radius); // 右上角
                ctx.arcTo(x + width, y + height, x, y + height, radius); // 右下角
                ctx.arcTo(x, y + height, x, y, radius); // 左下角
                ctx.arcTo(x, y, x + width, y, radius); // 左上角
                ctx.closePath();
                ctx.fillStyle = '#ff0000'; // 设置填充颜色为红色
                ctx.fill(); // 填充矩形

                ctx.font = `bold ${26 * dpr}px sans-serif`
                ctx.fillStyle = '#ffffff'
                ctx.textAlign = 'center'
                ctx.fillText('立即跟卡', x + width / 2.0, y + height / 2.0+10*dpr);





                ctx.font = `bold ${24 * dpr}px sans-serif`
                ctx.fillStyle = '#E0B152'
                ctx.textAlign = 'center'
                var name = user.nickname.length > 8 ? user.nickname.substring(0, 8) + '...' : user.nickname
                ctx.fillText(name, 210 * dpr, 182 * dpr);

                ctx.beginPath()
                ctx.arc(210 * dpr, 82 * dpr, 70 * dpr, 0, Math.PI * 2)
                ctx.clip()
                ctx.drawImage(img1, 140 * dpr, 12 * dpr, 140 * dpr, 140 * dpr);
                ctx.restore()
                ctx.stroke();






                Taro.canvasToTempFilePath({
                    canvas: canvas,
                    success: (res) => {
                        console.log('图片保存成功:', res.tempFilePath);
                        global.moment_share_url = res.tempFilePath
                    },
                    fail: (err) => {
                        console.error('转为图片失败:', err);
                    }
                });
            }
        };

    }

    function drawDetail2(ctx, imagePaths, canvas) {
        const promises = imagePaths.map((path, index) => {
            return new Promise((resolve) => {
                const img = canvas.createImage(); // 创建图像对象
                img.src = path;
                if (index == 0) {
                    img.onload = () => {
                        ctx.drawImage(img, 0, 0, 420 * dpr, 336 * dpr);
                        ctx.stroke();
                        resolve(true);
                    };
                }
                else {
                    img.onload = () => {
                        ctx.font = `bold ${24 * dpr}px sans-serif`
                        ctx.fillStyle = '#E0B152'
                        ctx.textAlign = 'center'
                        var name = user.nickname.length > 8 ? user.nickname.substring(0, 8) + '...' : user.nickname
                        ctx.fillText(name, 210 * dpr, 182 * dpr);

                        ctx.beginPath()
                        ctx.arc(210 * dpr, 82 * dpr, 70 * dpr, 0, Math.PI * 2)
                        ctx.clip()
                        ctx.drawImage(img, 140 * dpr, 12 * dpr, 140 * dpr, 140 * dpr);
                        ctx.restore()
                        ctx.stroke();

                        resolve(true);
                    };
                }

            });
        });

        Promise.all(promises).then(() => {
            // ctx.draw();

            Taro.canvasToTempFilePath({
                canvas: canvas,
                success: (res) => {
                    console.log('图片保存成功:', res.tempFilePath);
                    global.moment_share_url = res.tempFilePath
                },
                fail: (err) => {
                    console.error('转为图片失败:', err);
                }
            });
            // 
            // const ctx = Taro.createCanvasContext(this.canvasId);

            // ctx.draw();
        });

        // ctx.drawImage(imagePaths[0], 0, 0, 420, 336) // 设置图片位置和大小
        // ctx.draw()
    }

    return <View style={{ position: 'absolute', left: 0, top: -500, width: 420, height: 336, zIndex: 10000 }}>
        <Canvas canvasId='moment_share' id='moment_share' className="canvas" type="2d" style={{ width: 420, height: 336, zIndex: 0 }} />
    </View>
}