<template>
    <view class="settlementContainer">
        <!-- 头部导航 -->
        <view class="navBar" :style="{ paddingTop: menu.top + 'px', height: menu.height + 8 + 'px' }">
            <view class="navContent" :style="{ height: menu.height + 'px' }">
                <view class="backBtn" @click="handleBack">
                    <image class="backIcon" src="/static/images/home/backArrowblack.svg" />
                </view>
                <view class="navTitle">确认订单</view>
                <view class="placeholder"></view>
            </view>
        </view>

        <scroll-view class="contentArea" scroll-y>
            <!-- 地址部分 -->
            <view class="addressCard card">
                <view class="userInfo">
                    <text class="userName">{{ userData.MEMBERSHIP_NAME || '收货人' }}</text>
                    <text class="userPhone">{{ userData.MEMBERSHIP_MOBILEPHONE || '' }}</text>
                </view>
                <view class="addressDetail">
                    <text class="addrText">{{ currentAddress || '请选择收货地址' }}</text>
                    <view class="editBtn" @click="handleEditAddress">
                        <text>修改</text>
                        <uni-icons type="right" size="14" color="#1890FF"></uni-icons>
                    </view>
                </view>
                <image class="addressLine" src="/static/images/newShopDetail/address.png" mode="aspectFill" />
            </view>


            <!-- 选择站点 -->
            <view class="shopListBox card">
                <view class="cardHeader">配送站点</view>
                <picker @change="handleShopChange" :value="selectedShopIndex" :range="userData.ShopList"
                    range-key="SERVERPART_NAME">
                    <view class="shopPickerContent">
                        <view class="shopInfo">
                            <uni-icons type="shop" size="20" color="#4BCB7E"></uni-icons>
                            <text class="shopName">{{ (selectedShopIndex !== -1 && userData.ShopList &&
                                userData.ShopList[selectedShopIndex]) ?
                                userData.ShopList[selectedShopIndex].SERVERPART_NAME : '请选择配送站点' }}</text>
                        </view>
                        <uni-icons type="right" size="16" color="#999"></uni-icons>
                    </view>
                </picker>
            </view>


            <!-- 商品列表 -->
            <view class="productCard card">
                <view class="cardHeader">商品明细</view>
                <view class="productList">
                    <view class="productItem" v-for="(item, index) in displayList" :key="index">
                        <view class="itemMain">
                            <image class="productImg"
                                :src="item.IMAGE_PATH || 'https://eshangtech.com/ShopICO/no-picture.png'"
                                mode="aspectFill" />
                            <view class="itemInfo">
                                <view class="itemTitle">{{ item.COMMODITY_NAME }}</view>
                                <view class="itemPriceRow">
                                    <view class="price">
                                        <text class="symbol">¥</text>
                                        <text class="val">{{ item.COMMODITY_MEMBERPRICE }}</text>
                                        <text class="unit">/{{ item.COMMODITY_UNIT }}</text>
                                    </view>
                                    <view class="count">x{{ item.count }}</view>
                                </view>
                            </view>
                        </view>
                        <view style="height: 10rpx;"></view>
                        <!-- 单品备注 -->
                        <view class="itemRemark">
                            <input class="remarkInput" v-model="item.SALEDETAIL_DESC" placeholder="在此输入单品要求..." />
                        </view>
                    </view>
                </view>
                <!-- 折叠按钮控制 -->
                <view class="expandBox" v-if="shopList.length > 5">
                    <view class="expandBtn" @click="isExpand = !isExpand">
                        <text>{{ isExpand ? '收起更多' : '点击展开' }}</text>
                        <uni-icons :type="isExpand ? 'arrowup' : 'arrowdown'" size="14" color="#1890FF"></uni-icons>
                    </view>
                    <view class="totalKindTip">
                        共计 {{ totalUnits }} 件商品
                    </view>
                </view>
            </view>

            <!-- 订单备注 -->
            <view class="remarkCard card">
                <view class="cardHeader">订单备注</view>
                <textarea class="orderRemark" v-model="orderRemark" placeholder="请输入您的其他需求 (选填)" />
            </view>

            <view class="bottomPlaceholder"></view>
        </scroll-view>

        <!-- 底部结算栏 -->
        <view class="footerBar">
            <view class="priceTotal">
                <text class="label">合计：</text>
                <text class="symbol">¥</text>
                <text class="totalVal">{{ totalPrice }}</text>
            </view>
            <view class="submitBtn" @click="handleSubmit">立即下单</view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            menu: {},
            userData: {},
            currentAddress: '',
            shopList: [],
            orderRemark: '',
            isExpand: false,
            selectedShopIndex: 0
        };
    },
    computed: {
        displayList() {
            if (this.isExpand || this.shopList.length <= 5) {
                return this.shopList;
            }
            return this.shopList.slice(0, 5);
        },
        totalUnits() {
            return this.shopList.reduce((acc, cur) => acc + (cur.count || 0), 0);
        },
        totalPrice() {
            let total = 0;
            this.shopList.forEach(item => {
                total += parseFloat(item.COMMODITY_MEMBERPRICE) * item.count;
            });
            return total.toFixed(2);
        }
    },
    onLoad(options) {
        this.menu = uni.getMenuButtonBoundingClientRect();
        // 尝试从缓存中获取用户信息
        try {
            const user = uni.getStorageSync('userData');
            if (user) {
                this.userData = user;
            }
        } catch (e) { }

        // 接收从购物车传来的数据
        if (options.data) {
            try {
                const params = JSON.parse(decodeURIComponent(options.data));
                if (params.shopList) this.shopList = params.shopList;
                if (params.address) this.currentAddress = params.address;
            } catch (e) {
                console.error('解析订单数据失败', e);
            }
        }

        console.log('this.shopListthis.shopList', this.shopList);
    },
    methods: {
        handleBack() {
            uni.navigateBack();
        },
        handleEditAddress() {
            // 占位逻辑
            uni.showToast({ title: '修改地址功能已预留', icon: 'none' });
        },
        handleShopChange(e) {
            this.selectedShopIndex = e.detail.value;
        },
        handleSubmit() {
            let _this = this

            if (_this.selectedShopIndex === -1) {
                uni.showToast({
                    title: '请选择配送站点',
                    icon: 'none'
                })
                return
            }

            uni.showModal({
                title: '确认下单',
                content: `总金额：¥${_this.totalPrice}\n确定要提交订单吗？`,
                success: async (res) => {
                    if (res.confirm) {
                        console.log('dadas', _this.shopList);

                        // SUPPLIER_ID  这个的赋值 规则 若商品列表里面的 SUPPLIER_ID 是单个的话 那么就赋值单个进入  如果是多个的话 就变成0了
                        let SUPPLIER_IDList = []

                        // 商品信息
                        let t_saleorderdetail = []
                        _this.shopList.forEach(item => {
                            t_saleorderdetail.push({
                                COMMODITY_ID: item.COMMODITY_ID, // 商品内码
                                ORDER_COUNT: item.count, // 下单数量 
                                COMMODITY_NAME: item.COMMODITY_NAME, // 商品名称
                                COMMODITY_CODE: item.COMMODITY_CODE, // 商品编号
                                COMMODITY_BARCODE: item.COMMODITY_BARCODE, // 商品条码 
                                COMMODITY_UNIT: item.COMMODITY_UNIT, // 商品单位
                                COMMODITY_RULE: item.COMMODITY_RULE, // 商品规格
                                AVERAGE_PRICE: item.COMMODITY_MEMBERPRICE, // 商品单价 
                                ORDER_AMOUNT: item.COMMODITY_MEMBERPRICE * item.count, // 下单金额 
                                DISCOUNT_AMOUNT: "", // 优惠金额
                                SALEDETAIL_DESC: item.SALEDETAIL_DESC, // 商品备注
                                SUPPLIER_ID: item.SUPPLIER_ID // 供应商内码
                            })
                            if (SUPPLIER_IDList && SUPPLIER_IDList.length > 0) {
                                if (SUPPLIER_IDList.indexOf(item.SUPPLIER_ID) === -1) {
                                    SUPPLIER_IDList.push(item.SUPPLIER_ID)
                                }
                            } else {
                                SUPPLIER_IDList.push(item.SUPPLIER_ID)
                            }
                        })

                        // 订单信息相关
                        let purchaseModel = {
                            PURCHASE_PERSON: _this.userData.MEMBERSHIP_NAME, // 采购人
                            PURCHASE_PERSONTEL: _this.userData.MEMBERSHIP_MOBILEPHONE,//联系电话
                            STAFF_ID: _this.userData.MEMBERSHIP_ID,// 采购人ID
                            PURCHASE_DATE: _this.$utils.cutDate(new Date(), 'YYYY-MM-DD hh:mm:ss'), // 采购时间
                            PURCHASE_AMOUNT: _this.totalPrice,//采购金额
                            SUPPLIER_ID: SUPPLIER_IDList && SUPPLIER_IDList.length > 1 ? 0 : SUPPLIER_IDList[0],//供应商内码
                            SUPPLIER_NAME: "",//供应商名称
                            SELLER_ID: 11,//商户内码
                            PURCHASE_DESC: _this.orderRemark,//采购说明
                            WAREHOUSE_ID: "289",// 配送单位内码
                            WAREHOUSE_NAME: "自有品牌水",// 配送单位名称 
                            DELIVERY_ADDRESS: _this.currentAddress, // 收货地址
                            SUPPLIER_ID: _this.userData.ShopList && _this.userData.ShopList[_this.selectedShopIndex] ? _this.userData.ShopList[_this.selectedShopIndex].SERVERPARTSHOP_ID : ""// 用户选择的站点
                        }


                        let req = {
                            WareHouse_Type: 1,
                            purchaseModel: purchaseModel,
                            t_saleorderdetail: t_saleorderdetail
                        }
                        console.log('req', req);
                        const data = await _this.$api.$samemberPost(
                            "/EShangApiMain/WeChatMall/ScanOrder",
                            req
                        );

                        if (data.Result_Code === 100) {
                            uni.showToast({ title: '订单提交成功', icon: 'success' });

                            // 这是订单创建之后  对缓存进行处理的内容
                            // 1. 获取全量购物车数据
                            let cart = uni.getStorageSync("waterShopCar") || [];
                            // 2. 这里的 shopList 是当前结算页展示的勾选商品，我们需要从购物车中剔除
                            const orderedIds = _this.shopList.map(item => item.COMMODITY_ID);
                            const newCart = cart.filter(item => !orderedIds.includes(item.COMMODITY_ID));

                            // 3. 更新缓存，触发首页和购物车页 onShow 时的自动同步
                            uni.setStorageSync("waterShopCar", newCart);

                            // 4. 下单成功后跳转至订单列表页
                            setTimeout(() => {
                                uni.redirectTo({
                                    url: '/pages/ownWater/waterOrderList'
                                });
                            }, 1500);
                        } else {
                            uni.showToast({ title: data.Result_Desc, icon: 'none' });
                        }
                    }
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.settlementContainer {
    width: 100%;
    min-height: 100vh;
    background-color: #f2f4f5;
    display: flex;
    flex-direction: column;

    .navBar {
        background: #fff;
        width: 100%;
        position: sticky;
        top: 0;
        z-index: 100;
        border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);

        .navContent {
            display: flex;
            align-items: center;
            padding: 0 30rpx;

            .backBtn {
                width: 60rpx;
                display: flex;
                align-items: center;

                .backIcon {
                    width: 40rpx;
                    height: 40rpx;
                }
            }

            .navTitle {
                flex: 1;
                text-align: center;
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }

            .placeholder {
                width: 60rpx;
            }
        }
    }

    .shopListBox {
        .shopPickerContent {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10rpx 0;

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

                .shopName {
                    font-size: 28rpx;
                    color: #333;
                    margin-left: 12rpx;
                    font-weight: 500;
                }
            }
        }
    }

    .contentArea {
        flex: 1;
        padding: 20rpx;
        box-sizing: border-box;

        .card {
            background: #fff;
            border-radius: 16rpx;
            padding: 24rpx;
            margin-bottom: 20rpx;
            box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

            .cardHeader {
                font-size: 30rpx;
                font-weight: bold;
                color: #333;
                margin-bottom: 20rpx;
                padding-bottom: 10rpx;
                border-bottom: 1rpx solid #f5f5f5;
            }
        }

        .addressCard {
            position: relative;
            padding-bottom: 30rpx;

            .userInfo {
                margin-bottom: 10rpx;

                .userName {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                    margin-right: 20rpx;
                }

                .userPhone {
                    font-size: 28rpx;
                    color: #666;
                }
            }

            .addressDetail {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;

                .addrText {
                    flex: 1;
                    font-size: 26rpx;
                    color: #333;
                    line-height: 38rpx;
                }

                .editBtn {
                    display: flex;
                    align-items: center;
                    margin-left: 20rpx;
                    color: #1890ff;
                    font-size: 26rpx;
                    font-weight: 500;
                }
            }

            .addressLine {
                position: absolute;
                bottom: 0;
                left: 0;
                width: 100%;
                height: 6rpx;
            }
        }

        .productCard {
            .productList {
                .productItem {
                    margin-bottom: 30rpx;

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

                    .itemMain {
                        display: flex;

                        .productImg {
                            width: 140rpx;
                            height: 140rpx;
                            border-radius: 12rpx;
                            background-color: #f9f9f9;
                        }

                        .itemInfo {
                            flex: 1;
                            margin-left: 20rpx;
                            display: flex;
                            flex-direction: column;
                            justify-content: space-between;

                            .itemTitle {
                                font-size: 28rpx;
                                color: #333;
                                line-height: 40rpx;
                                display: -webkit-box;
                                -webkit-line-clamp: 2;
                                line-clamp: 2;
                                -webkit-box-orient: vertical;
                                overflow: hidden;
                            }

                            .itemPriceRow {
                                display: flex;
                                justify-content: space-between;
                                align-items: flex-end;

                                .price {
                                    color: #ff4d4f;

                                    .symbol {
                                        font-size: 24rpx;
                                    }

                                    .val {
                                        font-size: 34rpx;
                                        font-weight: bold;
                                    }

                                    .unit {
                                        font-size: 24rpx;
                                        color: #999;
                                        margin-left: 4rpx;
                                    }
                                }

                                .count {
                                    font-size: 26rpx;
                                    color: #999;
                                }
                            }
                        }
                    }

                    .itemRemark {
                        margin-top: 30rpx;
                        background: #f7f8f9;
                        padding: 12rpx 20rpx;
                        border-radius: 8rpx;

                        .remarkInput {
                            font-size: 24rpx;
                            color: #666;
                        }
                    }
                }
            }

            .expandBox {
                border-top: 1rpx solid #f5f5f5;
                padding: 24rpx 0 0rpx;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                width: 100%;
                background: #fff;

                .expandBtn {
                    display: flex !important;
                    align-items: center !important;
                    justify-content: center !important;
                    font-size: 26rpx;
                    color: #1890ff;
                    margin-bottom: 8rpx;
                    padding: 10rpx 30rpx;

                    text {
                        margin-right: 4rpx;
                    }
                }

                .totalKindTip {
                    font-size: 24rpx;
                    color: #999;
                    text-align: center;
                }
            }
        }
    }

    .remarkCard {
        .orderRemark {
            width: 100%;
            min-height: 200rpx;
            background: #f7f8f9;
            padding: 20rpx;
            box-sizing: border-box;
            border-radius: 12rpx;
            font-size: 26rpx;
            color: #333;
        }
    }

    .bottomPlaceholder {
        height: 200rpx;
    }
}

.footerBar {
    z-index: 999;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 160rpx;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 40rpx 0;
    padding-bottom: env(safe-area-inset-bottom);
    box-sizing: border-box;
    box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.05);

    .priceTotal {
        .label {
            font-size: 28rpx;
            color: #666;
        }

        .symbol {
            font-size: 28rpx;
            color: #ff4d4f;
            font-weight: bold;
        }

        .totalVal {
            font-size: 44rpx;
            color: #ff4d4f;
            font-weight: bold;
        }
    }

    .submitBtn {
        height: 72rpx;
        line-height: 72rpx;
        padding: 0 40rpx;
        background: #4BCB7E;
        color: #fff;
        border-radius: 36rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        font-weight: bold;
        box-shadow: 0 4rpx 10rpx rgba(75, 203, 126, 0.2);
    }
}
</style>
