<template>
    <view class="partner-home">
        <!-- 头部信息 -->
        <view class="header">
            <image class="avatar" src="https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/logo.png" mode="aspectFit">
            </image>
            <view class="header-text">
                <text class="title">您好，合伙人</text>
                <text class="subtitle">这里是合伙人数据中心</text>
            </view>
            <navigator url="/pages-mine/pages/partner/partner-rule" class="rule-btn">合伙人规则</navigator>
        </view>
        <view class="content" style="margin-top: -180rpx">
            <!-- 收入统计 -->
            <view class="income-section">
                <view class="section-header">
                    <text class="section-title">收入统计</text>
                    <text class="tip">每月20号到账上月结算收益</text>
                </view>
                <view class="income-grid">
                    <view class="income-item">
                        <text class="amount">¥{{ detail.totalIncome || "0.00" }}</text>
                        <text class="label">累计收入</text>
                    </view>
                    <view class="income-item">
                        <text class="amount">¥{{ detail.todayEstimateIncome || "0.00" }}</text>
                        <text class="label">今日预估</text>
                    </view>
                    <view class="income-item">
                        <text class="amount">¥{{ detail.lastMontyEstimateIncome || "0.00" }}</text>
                        <text class="label">上月预估</text>
                    </view>
                    <view class="income-item">
                        <text class="amount">¥{{ detail.thisMontyEstimateIncome || "0.00" }}</text>
                        <text class="label">本月预估</text>
                    </view>
                    <view class="income-item">
                        <text class="amount">¥{{ detail.lastMontySettlement || "0.00" }}</text>
                        <text class="label">上月结算</text>
                    </view>
                    <view class="income-item">
                        <text class="amount">¥{{ detail.waitAccount || "0.00" }}</text>
                        <text class="label">待到账</text>
                    </view>
                </view>
            </view>

            <!-- 实用工具 -->
            <view class="tools-section">
                <text class="section-title">实用工具</text>
                <view class="tools-grid">
                    <navigator url="/pages-mine/pages/partner/income-detail" class="tool-item">
                        <image src="/pages-mine/static/partner1.png" mode="aspectFit"></image>
                        <text>收入明细</text>
                    </navigator>
                    <navigator url="/pages-mine/pages/partner/order-detail" class="tool-item">
                        <image src="/pages-mine/static/partner2.png" mode="aspectFit"></image>
                        <text>订单明细</text>
                    </navigator>
                </view>
            </view>

            <!-- 生成海报按钮 -->
            <button class="generate-poster" @click="generatePoster" :loading="loading">生成专属二维码海报</button>

            <!-- 添加canvas元素 -->
            <canvas canvas-id="posterCanvas" id="posterCanvas"
                style="width: 750px; height: 1334px; position: fixed; left: -9999px"></canvas>

            <!-- 添加海报弹窗 -->
            <u-popup v-model="showPoster" mode="center" border-radius="16" :custom-style="posterStyle">
                <view class="poster-container">
                    <image class="poster-image" :src="posterInfo.tempFilePath || posterInfo.background" mode="aspectFit"
                        @longpress="saveImage"></image>
                    <view class="poster-tip">长按图片保存至相册分享</view>
                </view>
            </u-popup>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            detail: {
                totalIncome: 0,
                todayEstimateIncome: 0,
                lastMontyEstimateIncome: 0,
                thisMontyEstimateIncome: 0,
                lastMontySettlement: 0,
                waitAccount: 0,
            },
            showPoster: false,
            posterStyle: {
                backgroundColor: "transparent",
            },
            posterInfo: {},
            loading: false,
        };
    },
    onLoad() {
        this.getPartnerInfo();
    },
    methods: {
        getPartnerInfo() {
            uni.$u.get("/token/getUserPartnerInfo").then((res) => {
                if (res.code == 200) {
                    this.detail = res.data;
                }
            });
        },
        //生成海报
        generatePoster() {
            this.loading = true;
            this.getPosterInfo().then((data) => {
                console.log("海报数据:", data);
                let userInfo = uni.getStorageSync("userInfo");

                // 下载背景图片
                uni.downloadFile({
                    url: data.background,
                    success: (downloadRes) => {
                        const ctx = uni.createCanvasContext("posterCanvas");
                        const dpr = uni.getSystemInfoSync().pixelRatio || 1;

                        // 设置canvas尺寸为原图3倍，提高清晰度
                        const canvasWidth = 750;
                        const canvasHeight = 1334;

                        // 绘制背景图
                        ctx.drawImage(downloadRes.tempFilePath, 0, 0, canvasWidth, canvasHeight);

                        // 下载并绘制二维码
                        uni.downloadFile({
                            url: data.inviteUrl,
                            success: (qrRes) => {
                                // 根据比例调整坐标
                                const scale = canvasWidth / 250;
                                const adjustX = (x) => x * scale;
                                const adjustY = (y) => y * scale;
                                const adjustSize = (size) => size * scale;

                                let avatar =
                                    userInfo.imgPath || "https://shuhi.oss-cn-qingdao.aliyuncs.com/mini/t11.png";
                                uni.downloadFile({
                                    url: avatar,
                                    success: (avatarRes) => {
                                        console.log("头像下载成功:", avatarRes);
                                        // 绘制微信头像
                                        ctx.save();
                                        ctx.beginPath();
                                        // Adjust the position and size for the circular clipping path
                                        const avatarRadius = adjustSize(15);
                                        const avatarX = adjustX(data.headImgPosX);
                                        const avatarY = adjustY(data.headImgPosY);
                                        ctx.arc(
                                            avatarX + avatarRadius,
                                            avatarY + avatarRadius,
                                            avatarRadius,
                                            0,
                                            2 * Math.PI
                                        );
                                        ctx.clip();

                                        ctx.drawImage(
                                            avatarRes.tempFilePath,
                                            avatarX,
                                            avatarY,
                                            adjustSize(30), // Ensure the size matches the clipping path
                                            adjustSize(30)
                                        );
                                        ctx.restore();

                                        // 绘制微信昵称
                                        ctx.setFontSize(adjustSize(14));
                                        ctx.setFillStyle("#333333");

                                        let nickName = userInfo.nickName || "书嗨";
                                        let canvasStr = `${nickName}邀请你加入`;

                                        let firstLine = canvasStr.slice(0, 16);
                                        let secondLine = canvasStr.slice(16);

                                        ctx.fillText(firstLine, adjustX(data.nickNamePosX), adjustY(data.nickNamePosY + 12));
                                        ctx.fillText(secondLine, adjustX(data.nickNamePosX), adjustY(data.nickNamePosY + 30));

                                        // 绘制二维码
                                        ctx.save();
                                        ctx.beginPath();
                                        ctx.arc(
                                            adjustX(data.qrCodePosX + data.qrCodeWidth / 2),
                                            adjustY(data.qrCodePosY + data.qrCodeHeight / 2),
                                            adjustSize(data.qrCodeWidth / 2),
                                            0,
                                            2 * Math.PI
                                        );
                                        ctx.clip();
                                        ctx.drawImage(
                                            qrRes.tempFilePath,
                                            adjustX(data.qrCodePosX),
                                            adjustY(data.qrCodePosY),
                                            adjustSize(data.qrCodeWidth),
                                            adjustSize(data.qrCodeHeight)
                                        );
                                        ctx.restore();

                                        // 执行最终绘制
                                        ctx.draw(false, () => {
                                            setTimeout(() => {
                                                uni.canvasToTempFilePath({
                                                    canvasId: "posterCanvas",
                                                    width: canvasWidth,
                                                    height: canvasHeight,
                                                    destWidth: canvasWidth * dpr,
                                                    destHeight: canvasHeight * dpr,
                                                    quality: 1,
                                                    success: (res) => {
                                                        this.loading = false;
                                                        this.showPoster = true;
                                                        this.posterInfo.tempFilePath = res.tempFilePath;
                                                    },
                                                    fail: (err) => {
                                                        console.error("生成图片失败:", err);
                                                        uni.showToast({
                                                            title: "海报生成失败",
                                                            icon: "none"
                                                        });
                                                        this.loading = false;
                                                    }
                                                });
                                            }, 100);
                                        });
                                    },
                                    fail: (err) => {
                                        console.error("头像下载失败:", err);
                                        this.loading = false;
                                        uni.showToast({
                                            title: "头像加载失败",
                                            icon: "none"
                                        });
                                    }
                                });
                            },
                            fail: (err) => {
                                console.error("二维码下载失败:", err);
                                this.loading = false;
                                uni.showToast({
                                    title: "二维码加载失败",
                                    icon: "none"
                                });
                            }
                        });
                    },
                    fail: (err) => {
                        console.error("背景图下载失败:", err);
                        this.loading = false;
                        uni.showToast({
                            title: "背景图加载失败",
                            icon: "none"
                        });
                    }
                });
            });
        },
        //获取海报信息
        getPosterInfo() {
            return new Promise((resolve, reject) => {
                uni.$u.get("/token/getUserPartnerPic").then((res) => {
                    if (res.code == 200) {
                        this.posterInfo = res.data;
                        resolve(res.data);
                    } else {
                        reject(res.msg);
                    }
                });
            });
        },
        saveImage() {
            // #ifdef MP-WEIXIN
            uni.getSetting({
                success: (res) => {
                    if (!res.authSetting["scope.writePhotosAlbum"]) {
                        uni.authorize({
                            scope: "scope.writePhotosAlbum",
                            success: () => {
                                this.saveImageToAlbum();
                            },
                            fail: () => {
                                uni.showToast({
                                    title: "请授权保存图片到相册",
                                    icon: "none",
                                });
                            },
                        });
                    } else {
                        this.saveImageToAlbum();
                    }
                },
            });
            // #endif

            // #ifdef MP-ALIPAY
            // 支付宝小程序直接调用保存，会自动触发授权
            my.saveImage({
                url: this.posterInfo.tempFilePath,
                showActionSheet: false,
                success: () => {
                    uni.showToast({
                        title: "保存成功",
                        icon: "success",
                    });
                },
                fail: (err) => {
                    console.error("保存失败:", err);
                    uni.showToast({
                        title: "保存失败",
                        icon: "none",
                    });
                }
            });
            // #endif
        },
        saveImageToAlbum() {
            // #ifdef MP-WEIXIN
            uni.saveImageToPhotosAlbum({
                filePath: this.posterInfo.tempFilePath,
                success: () => {
                    uni.showToast({
                        title: "保存成功",
                        icon: "success",
                    });
                },
                fail: () => {
                    uni.showToast({
                        title: "保存失败",
                        icon: "none",
                    });
                },
            });
            // #endif
        },
    },
};
</script>
<style></style>
<style lang="scss" scoped>
.partner-home {
    min-height: 100vh;
    background-color: #f5f5f5;

    .section-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
        display: block;
    }

    .header {
        display: flex;
        align-items: flex-start;
        background-color: #4caf50;
        padding: 30rpx;
        padding-top: 45rpx;
        border-radius: 16rpx;
        margin-bottom: 20rpx;
        height: 322rpx;
        border-radius: 0rpx 0rpx 161rpx 161rpx;

        .avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 20rpx;
        }

        .header-text {
            flex: 1;
            color: #fff;

            .title {
                font-size: 32rpx;
                font-weight: bold;
                display: block;
            }

            .subtitle {
                font-size: 24rpx;
                opacity: 0.8;
            }
        }

        .rule-btn {
            padding: 10rpx 20rpx;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 30rpx;
            color: #fff;
            font-size: 24rpx;
        }
    }

    .income-section {
        background-color: #fff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin: 20rpx auto;
        width: calc(100% - 40rpx);

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;

            .tip {
                font-size: 24rpx;
                color: #999;
            }
        }

        .income-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20rpx;

            .income-item {
                background-color: #f8f8f8;
                padding: 20rpx;
                border-radius: 12rpx;
                text-align: center;

                .amount {
                    color: #ff4d4f;
                    font-size: 32rpx;
                    font-weight: bold;
                    display: block;
                }

                .label {
                    font-size: 24rpx;
                    color: #666;
                    margin-top: 8rpx;
                }
            }
        }
    }

    .tools-section {
        background-color: #fff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin: 20rpx auto;
        width: calc(100% - 40rpx);

        .tools-grid {
            display: flex;
            gap: 30rpx;

            .tool-item {
                flex: 1;
                display: flex;
                align-items: center;
                padding: 20rpx;
                border-radius: 12rpx;

                image {
                    width: 90rpx;
                    height: 90rpx;
                    margin-right: 10rpx;
                }

                text {
                    font-size: 26rpx;
                    color: #333;
                }
            }
        }
    }

    .generate-poster {
        width: calc(100% - 60rpx);
        height: 88rpx;
        line-height: 88rpx;
        background-color: #4caf50;
        color: #fff;
        border-radius: 10rpx;
        font-size: 28rpx;
        margin: 40rpx auto;
    }

    .poster-container {
        display: flex;
        flex-direction: column;
        align-items: center;

        .poster-image {
            width: 250px;
            height: 445px;
        }

        .poster-tip {
            font-size: 32rpx;
            color: #fff;
            text-align: center;
            background-color: #333;
            text-justify: space-between;
            width: 250px;
            line-height: 54rpx;
            position: relative;
            top: -2rpx;
        }
    }

    ::v-deep .u-mode-center-box {
        background-color: transparent !important;
    }
}
</style>
