<template>
    <view class="main">
        <!-- 顶部用户积分信息卡片 -->
        <view class="pointsHeader">
            <view class="headerContent">
                <view class="pointsInfo">
                    <view class="pointsLabel">我的ETC积分</view>
                    <view class="pointsValue">{{ userPoints || 0 }}</view>
                </view>
                <view class="pointsInfo platformPointsInfo">
                    <view class="pointsLabel">我的彩云驿积分</view>
                    <view class="pointsValue">{{ platformUserPoints || 0 }}</view>
                </view>
            </view>
        </view>

        <!-- 积分兑换计算器 -->
        <view class="exchangeBox">
            <view class="boxTitle">积分兑换</view>

            <view class="exchangeContent">
                <!-- 源积分输入 -->
                <view class="inputBox">
                    <view class="inputLabel">{{ conversionDirection === 'etcToPlatform' ? 'ETC积分' : '彩云驿积分' }}</view>
                    <input class="inputField" type="digit" v-model="sourcePointsInput" :placeholder="sourcePlaceholder"
                        @input="handleCalculate" />
                    <view class="balanceText">可用余额: {{ conversionDirection === 'etcToPlatform' ? userPoints :
                        platformUserPoints }}</view>
                </view>

                <!-- 兑换方向切换 -->
                <view class="iconBox" @click="toggleConversion">
                    <text class="exchangeTextIcon">⇄</text>
                    <view class="rateText">兑换比例 {{ exchangeRate }}:1</view>
                </view>


                <!-- 目标积分显示 -->
                <view class="resultBox">
                    <view class="resultLabel">{{ conversionDirection === 'etcToPlatform' ? '彩云驿积分' : 'ETC积分' }}</view>
                    <view class="resultValue">{{ destinationPointsOutput }}</view>
                    <view class="balanceTextPlaceholder"></view> <!-- Placeholder for alignment -->
                </view>
            </view>

            <!-- 兑换按钮 -->
            <view class="exchangeBtn" @click="handleExchange">
                立即兑换
            </view>
        </view>

        <!-- 兑换规则 -->
        <view class="rulesBox">
            <view class="boxTitle">
                <text>兑换规则</text>
            </view>

            <view class="rulesList">
                <view class="ruleItem" v-for="(rule, index) in rules" :key="index">
                    <view class="ruleDot"></view>
                    <text class="ruleText">{{ rule }}</text>
                </view>
            </view>
        </view>

        <!-- 积分商品列表 -->
        <view class="productsBox">
            <view class="boxTitle">
                <text>积分商品</text>
                <view class="moreBtn" @click="handleGoProductList">
                    <text class="moreText">查看更多</text>
                    <image class="moreIcon" src="https://eshangtech.com/caiyunyiImg/moreIcon.png" mode="aspectFit" />
                </view>
            </view>

            <view class="productsList">
                <view class="productItem" v-for="(product, index) in productList" :key="index"
                    @click="handleGoProductDetail(product)">
                    <image class="productImg" :src="product.image" mode="aspectFill" />
                    <view class="productInfo">
                        <view class="productName">{{ product.name }}</view>
                        <view class="productPoints">
                            <text class="pointsNum">{{ product.points }}</text>
                            <text class="pointsUnit">积分</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import {
    mapGetters
} from "vuex";

export default {
    data() {
        return {
            userPoints: 0, // 用户当前ETC积分
            platformUserPoints: 0, // 用户当前彩云驿积分
            sourcePointsInput: '', // 用户输入的源积分
            destinationPointsOutput: 0, // 计算后的目标积分
            exchangeRate: 1, // 兑换比例 1:1
            conversionDirection: 'etcToPlatform', // etcToPlatform(ETC积分换平台积分) | platformToEtc(平台积分换ETC积分)  
            userInfo: {},
            // 兑换规则
            rules: [
                '1个ETC积分可兑换1个彩云驿积分',
                '1个彩云驿积分可兑换1个ETC积分',
                '兑换后不可撤销,请谨慎操作',
            ],

            // 积分商品列表(示例数据)
            productList: [{
                id: 1,
                name: '10元优惠券',
                points: 100,
                image: 'https://eshangtech.com/caiyunyiImg/product1.png'
            },
            {
                id: 2,
                name: '20元优惠券',
                points: 200,
                image: 'https://eshangtech.com/caiyunyiImg/product2.png'
            },
            {
                id: 3,
                name: '50元优惠券',
                points: 500,
                image: 'https://eshangtech.com/caiyunyiImg/product3.png'
            },
            {
                id: 4,
                name: '100元优惠券',
                points: 1000,
                image: 'https://eshangtech.com/caiyunyiImg/product4.png'
            }
            ]
        }
    },

    computed: {
        ...mapGetters({
            user: "user",
        }),
        sourcePointName() {
            return this.conversionDirection === 'etcToPlatform' ? 'ETC积分' : '彩云驿积分';
        },
        destinationPointName() {
            return this.conversionDirection === 'etcToPlatform' ? '彩云驿积分' : 'ETC积分';
        },
        sourcePointBalance() {
            return this.conversionDirection === 'etcToPlatform' ? this.userPoints : this.platformUserPoints;
        },
        sourcePlaceholder() {
            return `请输入兑换${this.sourcePointName}`;
        }
    },

    async onLoad() {
        // this.getUserPoints();
        // this.handleGetUserDetail()
        const results = await Promise.all([
            this.getUserPoints(),
            this.handleGetUserDetail()
        ]);
        this.userPoints = results[0]
        this.platformUserPoints = results[1]
    },
    computed: {
        ...mapGetters({
            user: "user",
        }),
    },
    methods: {
        // 拿到用户详情
        async handleGetUserDetail() {
            let _this = this;

            const data = await _this.$api
                .getCoop({
                    action_type: "GetMembershipInfo",
                    WechatUserId: _this.user.WechatUserId,
                    noLoading: true,
                })
            if (data.ResultCode === "100") {
                let _data = data;
                _this.userInfo = _data.Data
                _this.user.MEMBERSHIP_ID = _data.Data.MEMBERSHIP_ID || "";
                _this.user.MEMBERSHIP_NAME = _data.Data.MEMBERSHIP_NAME || "";
                _this.user.MEMBERSHIP_LEVEL_TEXT =
                    _data.Data.MEMBERSHIP_LEVEL_TEXT || "";
                _this.user.COUPON_COUNT = _data.Data.COUPON_COUNT || "";
                _this.user.PENDORDER_COUNT = _data.Data.PENDORDER_COUNT || "";
                _this.user.RESERVATION_COUNT = _data.Data.RESERVATION_COUNT || "";
                _this.user.ACCOUNT_BALANCE = _data.Data.ACCOUNT_BALANCE || "";
                _this.user.ISPLUS = _data.Data.ISPLUS || "";
                _this.user.INDUSTRY_MEMBERSHIP_ID =
                    _data.Data.INDUSTRY_MEMBERSHIP_ID || "";
                _this.user.MEMBERSHIP_TYPE = _data.Data.MEMBERSHIP_TYPE || "";
                _this.user.MEMBERSHIP_LEVEL = _data.Data.MEMBERSHIP_LEVEL || "";
                _this.user.InviteCode = _data.Data.InviteCode || "";
                _this.user.MEMBERSHIP_POINT = _data.Data.MEMBERSHIP_POINT || "";
                _this.user.MEMBERSHIP_MOBILEPHONE =
                    _data.Data.MEMBERSHIP_MOBILEPHONE || "";
                _this.WXProfile = _data.Data.MEMBERSHIP_HEADIMAGEURL;
                _this.user.TEST_MEMBER = _data.Data.TEST_MEMBER || "";
                _this.$store.commit("setUser", _this.user);

                // _this.platformUserPoints = _data.Data.MEMBERSHIP_POINT

                _this.$forceUpdate()
                return _data.Data.MEMBERSHIP_POINT
            } else {
                // _this.setUser({});
                _this.$store.commit("setUser", user);
                return 0
            }
        },

        // 切换兑换方向
        toggleConversion() {
            this.conversionDirection = this.conversionDirection === 'etcToPlatform' ? 'platformToEtc' : 'etcToPlatform';
            this.sourcePointsInput = '';
            this.destinationPointsOutput = 0;
        },

        // 获取用户ETC积分
        async getUserPoints() {
            uni.showLoading({
                title: "获取积分中..."
            })
            const req = {
                mobile: this.user.MEMBERSHIP_MOBILEPHONE,
                outUserId: this.user.MEMBERSHIP_ID,
                type: "encryption"
            }
            const data = await this.$api.$post('/MemberApi/ThirdInterface/GetYTSLMemberPoint', req)
            uni.hideLoading()
            if (data.Result_Code === 100) {
                // this.userPoints = data.Result_Data.balance;
                return data.Result_Data.balance;
            } else {
                uni.showToast({
                    title: data.Result_Desc,
                    icon: 'none'
                });
                return 0
            }
        },


        // 计算兑换积分
        handleCalculate(e) {
            const value = e.detail.value;
            if (value && !isNaN(value)) {
                this.destinationPointsOutput = Math.floor(Number(value) / this.exchangeRate);
            } else {
                this.destinationPointsOutput = 0;
            }
        },

        // 执行兑换
        handleExchange() {
            if (!this.sourcePointsInput) {
                uni.showToast({
                    title: '请输入要兑换的积分!',
                    icon: 'none'
                });
                return
            }

            if (this.sourcePointsInput > 0) {

            } else {
                uni.showToast({
                    title: '请输入要兑换的积分!',
                    icon: 'none'
                });
                return
            }


            if (this.conversionDirection === 'etcToPlatform') {
                // ETC 换 平台
                if (this.sourcePointsInput > this.userPoints) {
                    uni.showToast({
                        title: 'ETC积分不足',
                        icon: 'none'
                    });
                    return;
                }
            } else {
                // 平台 换 ETC积分
                if (this.sourcePointsInput > this.platformUserPoints) {
                    uni.showToast({
                        title: '彩云驿积分不足',
                        icon: 'none'
                    });
                    return;
                }
            }
            let _this = this
            uni.showModal({
                title: '确认兑换',
                content: `确定使用${this.sourcePointsInput}个${this.conversionDirection === 'etcToPlatform' ? 'ETC积分' : '彩云驿积分'}兑换${this.destinationPointsOutput}个${this.conversionDirection === 'etcToPlatform' ? '彩云驿积分' : 'ETC积分'}吗?`,
                success: (res) => {
                    if (res.confirm) {
                        _this.doExchange()
                    }
                }
            });
        },

        async doExchange() {

            uni.showLoading({
                title: '兑换中...'
            });
            const req = {
                orderno: `535001-${new Date().getFullYear()}-${new Date().getTime()}`,
                outUserId: this.user.MEMBERSHIP_ID,
                changePoint: this.conversionDirection === 'etcToPlatform' ? this.destinationPointsOutput : -this.destinationPointsOutput,
                memo: "ETC积分兑换彩云驿积分",
                type: "encryption"
            }

            const data = await this.$api.$post('/MemberApi/ThirdInterface/ChangeYTSLMemberPoint', req)
            uni.hideLoading();
            if (data.Result_Code === 100) {
                uni.showToast({
                    title: '兑换成功',
                    icon: 'none'
                });
                this.sourcePointsInput = '';
                this.destinationPointsOutput = 0;
                // this.getUserPoints(); // 刷新ETC积分
                // this.handleGetUserDetail(); // 刷新彩云驿积分

                const results = await Promise.all([
                    this.getUserPoints(),
                    this.handleGetUserDetail()
                ]);
                this.userPoints = results[0]
                this.platformUserPoints = results[1]

            } else {
                uni.showToast({
                    title: data.Result_Desc,
                    icon: 'none'
                });
            }
        },

        // 跳转到商品详情
        handleGoProductDetail(product) {
            uni.showToast({
                title: `查看${product.name}详情`,
                icon: 'none'
            });
        },

        // 查看更多商品
        handleGoProductList() {
            uni.showToast({
                title: '查看更多商品',
                icon: 'none'
            });
        }
    }
}
</script>

<style lang="less" scoped>
.main {
    width: 100vw;
    min-height: 100vh;
    background: #F7F8FA;
    padding-bottom: 40rpx;
    box-sizing: border-box;
}

/* 顶部积分卡片 */
.pointsHeader {
    width: 100%;
    background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
    padding: 40rpx 32rpx 80rpx;
    box-sizing: border-box;

    .headerContent {
        display: flex;
        align-items: center;
        justify-content: space-around;

        .pointsInfo {
            text-align: center;

            .pointsLabel {
                font-size: 28rpx;
                color: rgba(255, 255, 255, 0.8);
                margin-bottom: 16rpx;
            }

            .pointsValue {
                font-size: 60rpx;
                font-weight: bold;
                color: #FFFFFF;
                line-height: 1;
            }
        }
    }
}

/* 积分兑换计算器 */
.exchangeBox {
    width: calc(100% - 64rpx);
    margin: -40rpx 32rpx 24rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    padding: 24rpx;
    box-sizing: border-box;

    .boxTitle {
        font-size: 28rpx;
        font-weight: 600;
        color: #222222;
        margin-bottom: 32rpx;
    }

    .exchangeContent {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 24rpx; // Add some bottom margin to separate from the button

        .inputBox {
            // flex: 1;
            width: calc((100% - 100rpx)/ 2);
            margin-bottom: 0; // Remove vertical margin

            .inputLabel {
                font-size: 28rpx;
                color: #666666;
                margin-bottom: 16rpx;
            }

            .inputField {
                width: 100%;
                height: 80rpx;
                background: #F7F8FA;
                border-radius: 12rpx;
                padding: 0 24rpx;
                font-size: 32rpx;
                color: #222222;
                box-sizing: border-box;
            }

            .balanceText {
                font-size: 24rpx;
                color: #999999;
                margin-top: 12rpx;
                text-align: right;
            }
        }

        .iconBox {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100rpx; // Fixed width for the icon box
            flex-shrink: 0; // Prevent shrinking
            margin: 0 20rpx; // Horizontal margin
            cursor: pointer;

            &:active {
                opacity: 0.7;
            }

            .exchangeTextIcon {
                font-size: 56rpx;
                color: #667EEA;
                font-weight: bold;
                line-height: 1;
            }

            .rateText {
                font-size: 24rpx;
                color: #667EEA;
                font-weight: 500;
                margin-top: 8rpx;
                text-align: center;
            }
        }


        .resultBox {
            // flex: 1;
            width: calc((100% - 100rpx)/ 2);
            margin-bottom: 0; // Remove vertical margin

            .resultLabel {
                font-size: 28rpx;
                color: #666666;
                margin-bottom: 16rpx;
            }

            .resultValue {
                width: 100%;
                height: 80rpx;
                background: #F7F8FA;
                border-radius: 12rpx;
                padding: 0 24rpx;
                font-size: 32rpx;
                font-weight: bold;
                color: #667EEA;
                display: flex;
                align-items: center;
                box-sizing: border-box;
                overflow-x: auto;
                white-space: nowrap;
            }

            .resultValue::-webkit-scrollbar {
                display: none;
            }

            .balanceTextPlaceholder {
                height: 24rpx; // Match font-size of balanceText
                margin-top: 12rpx; // Match margin-top of balanceText
            }
        }
    }

    .exchangeBtn {
        width: 100%;
        height: 80rpx;
        background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 400;
        color: #FFFFFF;
        margin-top: 0; // Adjust margin as exchangeContent now has bottom margin

        &:active {
            opacity: 0.8;
        }
    }
}

/* 兑换规则 */
.rulesBox {
    width: calc(100% - 64rpx);
    margin: 0 32rpx 24rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    padding: 24rpx;
    box-sizing: border-box;

    .boxTitle {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        font-weight: 600;
        color: #222222;
        margin-bottom: 24rpx;
    }

    .rulesList {
        .ruleItem {
            display: flex;
            align-items: flex-start;
            margin-bottom: 20rpx;

            &:last-child {
                margin-bottom: 0;
            }

            .ruleDot {
                width: 12rpx;
                height: 12rpx;
                background: #667EEA;
                border-radius: 50%;
                margin-top: 12rpx;
                margin-right: 16rpx;
                flex-shrink: 0;
            }

            .ruleText {
                flex: 1;
                font-size: 24rpx;
                color: #666666;
                line-height: 1.6;
            }
        }
    }
}

/* 积分商品列表 */
.productsBox {
    width: calc(100% - 64rpx);
    margin: 0 32rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    padding: 24rpx;
    box-sizing: border-box;


    .boxTitle {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        font-weight: 600;
        color: #222222;
        margin-bottom: 24rpx;

        .moreBtn {
            display: flex;
            align-items: center;

            .moreText {
                font-size: 24rpx;
                color: #999999;
                font-weight: 400;
                margin-right: 8rpx;
            }

            .moreIcon {
                width: 24rpx;
                height: 24rpx;
            }
        }
    }

    .productsList {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        .productItem {
            width: calc((100% - 24rpx) / 2);
            background: #F7F8FA;
            border-radius: 12rpx;
            overflow: hidden;
            margin-bottom: 24rpx;

            &:active {
                opacity: 0.8;
            }

            .productImg {
                width: 100%;
                height: 240rpx;
                background: #E5E5E5;
            }

            .productInfo {
                padding: 20rpx;

                .productName {
                    font-size: 28rpx;
                    color: #222222;
                    margin-bottom: 12rpx;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .productPoints {
                    .pointsNum {
                        font-size: 32rpx;
                        font-weight: bold;
                        color: #667EEA;
                    }

                    .pointsUnit {
                        font-size: 24rpx;
                        color: #999999;
                        margin-left: 8rpx;
                    }
                }
            }
        }
    }
}
</style>