<template>
    <view class="container">
        <!-- 顶部切换栏 -->
        <view class="tab-bar">
            <view :class="{ active: activeTab === 'delivery' }" class="tab-item" @click="switchTab('delivery')">配送
            </view>
        </view>
        <!-- 分隔线 -->
        <view class="divider"></view>
        <!-- 配送信息 -->
        <view class="info-section" v-if="activeTab === 'delivery'">
            <view class="address-section">
                <view class="section-title">
                    收货地址
                    <view v-if="!defAddress" class="addNewAddress" @click="chooseAddress">添加新地址  &gt;</view>
                </view>
                <view class="address-info" @click="chooseAddress" v-if="defAddress">
                    <view class="address-main">
                        <view class="address-name-phone">
                            <text class="name">{{ defAddress.name }}</text>
                            <text class="phone">{{ defAddress.phone }}</text>
                        </view>
                        <view class="address-detail">
                            {{ defAddress.address }}{{ defAddress.house_number }}
                            <view class="copy-icon" @click.stop="copyAddress" />
                        </view>
                    </view>
                    <view class="address-arrow"><u-icon name="arrow-right" size="25"></u-icon></view>
                </view>
            </view>
        </view>
        <!-- 分隔线 -->
        <view class="divider"></view>
        <!-- 商品信息 -->
        <view v-if="activeTab === 'delivery' && orderList.length > 0">
            <view class="goods-list">
                <view class="goods-item" v-for="(item, index) in orderList" :key="index">
                    <view class="goods-image">
                        <image :src="item.commodity_goods_info.commodity_pic" mode="aspectFill"></image>
                    </view>
                    <view class="goods-info">
                        <view class="goods-name">{{ item.commodity_goods_info.goods_name }}</view>
                        <view class="goods-desc">{{ item.commodity_goods_info.goods_spec }}</view>
                        <view class="price-container">
                            <view class="group-price">
                                <view>￥{{ item.commodity_goods_info.sales_price }}/{{
                                    item.commodity_goods_info.goods_unit
                                }}</view>
                                <!-- 运费 -->
                                <view class="goods-desc" style="margin-top: 10rpx;">运费 ￥{{
                                    item.commodity_goods_info.freight ? item.commodity_goods_info.freight : 0
                                }}</view>
                            </view>
                            <view class="quantity-control">
                                <view class="decrease-btn" @tap.stop="decreaseQuantity(item)">-</view>
                                <view class="quantity">{{ item.count }}</view>
                                <view class="increase-btn" @tap.stop="increaseQuantity(item)">+</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 总金额 -->
            <view class="total-section">
                <view class="total-name">总金额</view>
                <view class="total-value">￥{{ calculateTotal() }}</view>
            </view>
            <!-- 支付方式 -->
            <view class="payment-section">
                <view class="payment-item" @click="selectPayment('wechat')">
                    <view class="payment-icon">
                        <image
                            src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_wechat.png"
                            mode="aspectFit"></image>
                    </view>
                    <view class="payment-content">
                        <view class="payment-name">微信支付</view>
                        <view class="payment-desc"><text
                                style="color: #f03d0e;margin-right: 15rpx;">可用优惠券</text>单笔支付限额:¥10000.00</view>
                    </view>
                    <view class="payment-select" v-if="selectedPayment === 'wechat'">
                        <image
                            src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check2.png"
                            mode="aspectFit" style="width: 40rpx; height: 40rpx;"></image>
                    </view>
                    <view class="payment-select" v-else>
                        <image
                            src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/com_check1.png"
                            mode="aspectFit" style="width: 40rpx; height: 40rpx;"></image>
                    </view>
                </view>
            </view>
        </view>
        <view v-if="activeTab === 'delivery' && orderList.length == 0" class="empty-tip">
            暂无商品数据
        </view>
        <!-- 立即支付按钮 -->
        <view class="pay-button" @click="submitPayment">立即支付</view>

        <!-- 弹窗 - 支付成功 -->
        <view class="shadow" @click="changeShadow" v-if="boxshadow1">
            <view class="shadowBox2">
                <view class="shadowBox_img">
                    <view class="boxshadow_tit">
                        <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/af_√.png"
                            class="boxshadow_tit_img">
                        </image>
                        已支付成功
                    </view>
                    <view class="boxshadow_img">
                        <view v-if="verifyCode">核销码：{{ verifyCode }}</view>
                    </view>
                    <view>
                        <view class="wealBoxTit">
                            <view class="wealBoxTit1">下单福利</view>
                            <view class="wealBoxTit2">已获得</view>
                        </view>
                        <view class="wealBox">
                            <view class="wealBoxItem wealBoxItem1">
                                <view class="wealBoxItemTop">
                                    <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/activity_fen.png"
                                        mode="aspectFit">
                                    </image>
                                    <view>石榴分</view>
                                </view>
                                <view>
                                    {{ slFen }}
                                </view>
                                <view class="wealBoxItemBottom">
                                    可抵扣 ￥{{ slFen }}
                                </view>
                            </view>
                            <view class="wealBoxItem wealBoxItem2">
                                <view class="wealBoxItemTop">
                                    <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/activity_zi.png"
                                        mode="aspectFit">
                                    </image>
                                    <view>石榴籽</view>
                                </view>
                                <view>
                                    {{ slZi }}
                                </view>
                                <view class="wealBoxItemBottom">
                                    可抵扣 ￥{{ slZi }}
                                </view>
                            </view>
                            <view class="wealBoxItem wealBoxItem3">
                                <view class="wealBoxItemTop">
                                    <image src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/activity_jin.png"
                                        mode="aspectFit" />
                                    <view>石榴金</view>
                                </view>
                                <view>
                                    {{ slJin }}
                                </view>
                                <view class="wealBoxItemBottom">
                                    可抵扣 ￥{{ slJin }}
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>
<script>
import { picUrl, menuButtonInfo, request, NavgateTo } from "../../../utils";
import { apiArr } from "../../../api/shop";

export default {
    data() {
        return {
            activeTab: 'delivery', // 默认选中配送
            quantity: 1, // 商品数量
            selectedPayment: 'wechat',
            boxshadow1: false,
            boxshadow2: false,
            defAddress: {},
            orderList: [],
            carList: [],

            slJin: 0,
            slFen: 0,
            slZi: 0,

            // 核销码
            verifyCode: '',
        };
    },
    onLoad(options) {
        this.carList = JSON.parse(options.shopCarList)
    },
    onShow() {
        this.getUserAddress()
        this.getGoodsList()
    },
    onUnload() {
        uni.removeStorageSync('changeZTAddress')
    },
    methods: {
        switchTab(tab) {
            this.activeTab = tab;
        },
        //用户收货地址
        getUserAddress() {
            request(apiArr.getUserDefAddress, "POST", {}).then(res => {
                this.defAddress = res.default_address
            })
        },
        // 商品列表
        getGoodsList() {
            this.orderList = []

            this.carList.forEach(item => {
                // 如果图片URL不是以https开头，则拼接picUrl
                if (item.commodity_goods_info.commodity_pic && item.commodity_goods_info.commodity_pic.indexOf('https') !== 0) {
                    item.commodity_goods_info.commodity_pic = picUrl + item.commodity_goods_info.commodity_pic
                }
                this.orderList.push(item)
            })
        },
        chooseAddress() {
            NavgateTo('/packages/shop/address/index')
        },
        decreaseQuantity(item) {
            if (item.count > 0) {
                item.count--

                // 当数量减到0时，从carList中删除该商品
                if (item.count === 0) {
                    const index = this.carList.findIndex(carItem => carItem.goods_id === item.goods_id);
                    if (index > -1) {
                        this.carList.splice(index, 1);
                        // 重新加载商品列表以更新页面显示
                        this.getGoodsList();
                    }
                }

                this.changeCart(item)
            }
        },
        increaseQuantity(item) {
            if (item.count >= item.commodity_goods_info.stock_quantity) {
                uni.showToast({
                    title: '库存不足',
                    icon: 'none'
                });
                return
            }
            item.count++;
            this.changeCart(item);
        },
        // 更改购物车
        changeCart(item) {
            const params = {
                goods_id_and_count: [
                    {
                        goods_id: item.goods_id,
                        count: item.count,
                    },
                ],
            }
            request(apiArr.updateCar, "POST", params).then(res => {
                uni.showToast({
                    title: "操作成功！",
                    success() { },
                });
            })
        },

        // 计算总金额
        calculateTotal() {
            let total = 0;
            this.orderList.forEach(goods => {
                total += goods.commodity_goods_info.sales_price * goods.count + (goods.commodity_goods_info.freight || 0);
            });
            return total.toFixed(2);
        },
        selectPayment(payment) {
            this.selectedPayment = payment;
        },
        submitPayment() {
            // 检查是否有收货地址
            if (!this.defAddress || Object.keys(this.defAddress).length === 0) {
                uni.showToast({
                    title: '请选择收货地址',
                    icon: 'none'
                });
                return;
            }

            // 检查是否存在isafterSale属性且值为true
            const hasAfterSaleItem = this.carList.some(item => item.isafterSale === true);
            const orderIdFromAfterSale = hasAfterSaleItem ? this.carList.find(item => item.isafterSale === true)?.orderId : null;

            // 根据平台设置不同的trans_type值
            // 小程序: 71, App: 51
            const systemInfo = uni.getSystemInfoSync();
            let trans_type = 51; // 默认App环境

            // 运行时判断是否为小程序环境
            if (systemInfo.platform === 'devtools' || systemInfo.platform === 'unknown') {
                trans_type = 71; // 开发工具或未知环境默认为小程序
            }

            // 条件编译：针对不同平台设置不同值
            // #ifdef MP
            trans_type = 71; // 所有小程序平台
            // #endif

            // #ifdef APP-PLUS
            trans_type = 51; // App平台
            // #endif

            // 如果存在isafterSale属性且为true，则跳过createOrder接口调用
            if (hasAfterSaleItem && orderIdFromAfterSale) {
                const param = {
                    order_id: orderIdFromAfterSale,
                    user_id: uni.getStorageSync('userId'),
                    trans_type: trans_type
                }
                request(apiArr.mergePreorder, "POST", param).then(res => {
                    this.handleMergePreorderResponse(res, orderIdFromAfterSale);
                })
            } else {
                // 原始逻辑：创建订单后再进行支付
                const params = {
                    user_id: uni.getStorageSync('userId'),
                    // 先判断shopCarList数据中是否包含isAdver且为true
                    order_cate: this.carList.some(item => item.isAdver === true) ? 3 : 1,
                    goods_list: [{
                        supplier_id: this.orderList[0].supplier_id,
                        supplier_name: this.orderList[0].supplier_name || '',
                        is_same_day: this.orderList[0].commodity_goods_info.is_same_day,
                        receiving_name: this.defAddress.name,
                        receiving_phone: this.defAddress.phone,
                        receiving_address: this.defAddress.address + this.defAddress.house_number,
                        merchant_id: this.defAddress.address_id,
                        goods_and_count: this.orderList.map(item => ({
                            goods_id: item.goods_id,
                            count: item.count,
                            price: item.commodity_goods_info.sales_price,
                            freight: item.commodity_goods_info.freight,
                        }))
                    }]
                }

                request(apiArr.createOrder, "POST", params).then(resVal => {
                    const param = {
                        order_id: resVal.order_id,
                        user_id: uni.getStorageSync('userId'),
                        trans_type: trans_type
                    }
                    request(apiArr.mergePreorder, "POST", param).then(res => {
                        this.handleMergePreorderResponse(res, resVal.order_id);
                    })
                })
            }
        },

        // 处理mergePreorder接口的响应
        handleMergePreorderResponse(res, orderId) {
            if (res && res.timeStamp && res.nonceStr && res.package && res.signType && res.paySign) {
                // 调用微信支付
                uni.requestPayment({
                    timeStamp: res.timeStamp,
                    nonceStr: res.nonceStr,
                    package: res.package,
                    signType: res.signType,
                    paySign: res.paySign,
                    success: (payRes) => {
                        const params = {
                            order_id: orderId,
                            from: this.carList.some(item => item.isAdver === true) ? 3 : 1,
                            adver_id: this.carList.some(item => item.isAdver === true) ? this.carList.find(item => item.isAdver === true).adver_id : ''
                        }
                        request(apiArr.queryOrder, "POST", params).then(res => {
                            this.verifyCode = res.verification_code
                            this.slJin = res.shiliu_money
                            this.boxshadow1 = true
                        })
                    },
                    fail: (payErr) => {
                        uni.showToast({
                            title: payErr.errMsg == 'requestPayment:fail cancel' ? '已取消支付' : '支付失败',
                            icon: 'none'
                        })
                        const params = {
                            order_ids: orderId,
                        }
                        request(apiArr.cancelPay, "POST", params).then(res => {
                        })
                    },
                    complete: () => {
                        // 支付完成后的回调，无论成功失败都会执行
                    }
                })
            } else {
                console.error("获取支付参数失败，缺少必要参数")
                uni.showToast({
                    title: '获取支付信息失败',
                    icon: 'none'
                })
            }
        },
        // 复制收货地址
        copyAddress() {
            // 使用uni-app的复制API
            uni.setClipboardData({
                data: this.defAddress.address + this.defAddress.house_number,
                success: () => {
                    uni.showToast({
                        title: '复制成功',
                        icon: 'success'
                    });
                },
                fail: () => {
                    uni.showToast({
                        title: '复制失败',
                        icon: 'none'
                    });
                }
            });
        },
        openSave() {
            this.boxshadow1 = false;
            this.boxshadow2 = true;
        },
        changeShadow() {
            this.boxshadow1 = false;
        },
        changeShadow2() {
            this.boxshadow2 = false;
        },
        // 保存海报
        saveImg() {
            this.boxshadow2 = false;
            // 微信小程序保存图片
            uni.downloadFile({
                url: "https://wechat-img-file.oss-cn-beijing.aliyuncs.com/property-img-file/shop_share_img.png",
                success: (res) => {
                    if (res.statusCode === 200) {
                        uni.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success: (res) => {
                                uni.showToast({
                                    title: "保存成功",
                                    icon: "success",
                                    duration: 2000,
                                });
                            },
                            fail: (err) => {
                                console.log("保存失败", err);
                            },
                        });
                    }
                },
                fail: (err) => {
                    console.log("下载失败", err);
                },
            });
        },
    }
};
</script>
<style>
@import url('./index.css');
</style>