<template>
    <view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden order-list" :style="themeColor()">
        <view class="fixed left-0 top-0 right-0 z-10">
            <scroll-view :scroll-x="true" class="tab-style-2">
                <view class="tab-content">
                    <view class="tab-items" :class="{ 'class-select': orderState === item.key }"
                        @click="orderStateFn(item.key)" v-for="(item, index) in orderStateList">{{ item.name }}
                    </view>
                </view>
            </scroll-view>
        </view>

        <mescroll-body ref="mescrollRef" top="88rpx" @init="mescrollInit" :down="{ use: false }" @up="getShopOrderFn">
            <view class="sidebar-margin pt-[var(--top-m)]" v-if="list.length">
                <template v-for="(item, index) in list" :key="index">
                    <view class="mb-[var(--top-m)] card-template">
                        <view @click.stop="toLink(item)">
                            <view class="flex justify-between items-center">
                                <view class="text-[#303133] text-[24rpx] font-400 leading-[36rpx] flex items-center">
                                    <view class="ml-[10rpx] text-[24rpx] font-400 text-[#303133]">{{ item.orderTime }}
                                    </view>
                                </view>
                                <view class="text-[#303133] text-[26rpx] max-w-[150px] leading-[34rpx] truncate">
                                    {{ getStatusText(item.orderStatus) }}</view>
                            </view>
                            <template v-for="(subItem, index) in item.goodsList" :key="index">
                                <view class="flex box-border mt-[20rpx]">
                                    <u--image width="150rpx" height="150rpx" :radius="'var(--goods-rounded-big)'"
                                        :src="img(subItem.image ? subItem.image : '')" mode="aspectFill">
                                        <template #error>
                                            <image
                                                class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
                                                :src="img('https://v6.site.niucloud.com/static/resource/images/diy/shop_default.jpg')"
                                                mode="aspectFill" />
                                        </template>
                                    </u--image>
                                    <view class="ml-[20rpx] flex flex-1 flex-col box-border">
                                        <view class="flex justify-between items-baseline">
                                            <view
                                                class="max-w-[322rpx] text-[28rpx] leading-[40rpx] font-400 truncate text-[#303133]">
                                                {{ subItem.name
                                                }}</view>

                                            <view class="text-right leading-[42rpx] ml-[10rpx]">
                                                <text class="text-[22rpx] price-font">￥</text>
                                                <text class="text-[36rpx] font-500 price-font">{{
                                                    parseFloat(subItem.price).toFixed(2).split('.')[0] }}</text>
                                                <text class="text-[22rpx] font-500 price-font">.{{
                                                    parseFloat(subItem.price).toFixed(2).split('.')[1] }}</text>
                                            </view>
                                        </view>
                                        <view class="flex justify-between items-baseline text-[#303133] mt-[14rpx]">
                                            <view>
                                                <view
                                                    class="text-[24rpx] text-[var(--text-color-light6)] font-400 truncate leading-[34rpx] max-w-[369rpx] mb-[10rpx]">
                                                    {{ subItem.spec1 }}</view>
                                                <view
                                                    class="text-[24rpx] font-400 leading-[34rpx] text-[var(--text-color-light6)]">
                                                    {{ subItem.spec2 }}</view>
                                            </view>
                                            <text class="text-right text-[26rpx] font-400 w-[90rpx] leading-[36rpx]">x{{
                                                subItem.quantity }}</text>
                                        </view>
                                    </view>
                                </view>
                            </template>
                        </view>
                        <view class="flex justify-end items-center mt-[20rpx]">
                            <view class="flex items-baseline">
                                <view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]">实付款：</view>
                                <view class="leading-[1] text-[var(--price-text-color)]">
                                    <text class="text-[22rpx] leading-[26rpx] price-font">￥</text>
                                    <text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{
                                        parseFloat(item.payableAmount).toFixed(2).split('.')[0] }}</text>
                                    <text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{
                                        parseFloat(item.payableAmount).toFixed(2).split('.')[1] }}</text>
                                </view>
                            </view>
                        </view>
                        <view class="flex justify-end text-[28rpx] mt-[20rpx] items-center" >
                            <view
                                class="text-[24rpx] font-500 leading-[52rpx] h-[56rpx] min-w-[150rpx] text-center border-[2rpx] border-solid border-[#ccc] rounded-full text-[var(--text-color-light3)] box-border"
                                v-if="item.orderStatus == 1 || item.orderStatus == 0" @click.stop="orderBtnFn(item, 'close')">取消订单
                            </view>
                            <view
                                class="text-[24rpx] font-500 flex-center h-[56rpx] min-w-[150rpx] text-center border-[0] text-[#fff] primary-btn-bg rounded-full ml-[20rpx] box-border"
                                v-if="item.orderStatus == 1" @click.stop="orderBtnFn(item, 'pay')">去支付</view>
                            <view
                                class="text-[24rpx] font-500 flex-center h-[56rpx] min-w-[150rpx] text-center border-[0] text-[#fff] primary-btn-bg rounded-full ml-[20rpx] box-border"
                                v-if="item.orderStatus == 4" @click.stop="orderBtnFn(item, 'finish')">确认收货
                            </view>
                            <!-- <view
                                class="text-[24rpx] font-500 leading-[52rpx] h-[56rpx] min-w-[150rpx] text-center border-[2rpx] border-solid border-[#ccc] rounded-full ml-[20rpx]  text-[var(--text-color-light3)] box-border"
                                v-if="item.isNeedCheck == '0' && item.checkStatus != '0'"
                                @click.stop="orderBtnFn(item, 'evaluate')">查看物流
                            </view> -->
                        </view>
                    </view>
                </template>
            </view>
            <mescroll-empty v-if="!list.length && loading" :option="{ tip: '暂无订单' }"></mescroll-empty>
        </mescroll-body>
        <pay ref="payRef" @close="payClose"></pay>
        <!-- #ifdef MP-WEIXIN -->
        <!-- 小程序隐私协议 -->
        <wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
        <!-- #endif -->
    </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { img, redirect, copy } from '@/utils/common'
import { getShopOrderStatus, getShopOrder, orderClose, orderFinish, getproducts } from '@/addon/shop/api/order';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onLoad, onPageScroll, onReachBottom, onShow } from '@dcloudio/uni-app';
import useConfigStore from "@/stores/config";

const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const list = ref<any>([]);
const loading = ref<boolean>(false);
const orderState = ref('all')
const orderStateList: any = ref([
    { key: 'all', name: '全部订单' },
    { key: '0', name: '预下单' },
    { key: '4', name: '待收货' },
    { key: '5', name: '已完成' },
    { key: '7', name: '已取消' }
]);

const wxPrivacyPopupRef: any = ref(null)

onLoad((option: any) => {
    orderState.value = option.status || "all";
    // #ifdef MP
    nextTick(() => {
        if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
    })
    // #endif
});

onShow(() => {
    nextTick(() => {
        // 评价完成之后，会返回到订单列表，需要请求最新数据
        if (getMescroll()) {
            getMescroll().resetUpScroll();
        }
    })
})

const getShopOrderFn = async (mescroll: any) => {
    loading.value = false;
    try {
        const data = {
            pageNum: mescroll.num,
            pageSize: mescroll.size,
            orderStatuses: orderState.value === 'all' ? '' : orderState.value
        };

        const res: any = await getShopOrder(data);
        let newArr = res.rows || [];

        if (mescroll.num === 1) {
            list.value = []; // 第一页清空
        }
        const orderProductsMap: Record<number, any[]> = {};
        // 获取商品详情（可选）
        if (newArr.length > 0) {

            let orderIds = newArr.map((o: any) => o.id);
            orderIds = orderIds.join(",")
            console.log(orderIds, 'orderIds')
            try {
                const prodRes: any = await getproducts({ orderIds: orderIds });
                if (prodRes.code === 200 && prodRes.rows) {
                    prodRes.rows.forEach((p: any) => {
                        if (!orderProductsMap[p.orderId]) {
                            orderProductsMap[p.orderId] = [];
                        }
                        orderProductsMap[p.orderId].push({
                            id: p.id,
                            productId: p.productId,
                            image: p.productImage || '',
                            name: p.productName || '',
                            spec1: p.productUnit || '',
                            spec2: p.productNo || '',
                            price: p.orderPrice || 0,
                            quantity: p.orderQuantity || 0
                        });
                    });
                    console.log(prodRes, 'prodRes')
                }
            } catch (e) {
                console.error('获取商品列表失败:', e);
                // 不中断主流程，继续显示订单
            }
        }
        newArr.forEach((item: any) => {
            item.goodsList = orderProductsMap[item.id] || []
        });
        list.value = list.value.concat(newArr);
        mescroll.endSuccess(newArr.length);
    } catch (error) {
        console.error('获取订单列表失败:', error);
        mescroll.endErr();
    } finally {
        loading.value = true;
    }
};

// 根据订单状态获取状态文本
const getStatusText = (status: string) => {
    const statusMap: Record<string, string> = {
        '0': '待支付',
        '1': '待确认',
        '2': '待发货',
        '3': '部分发货',
        '4': '发货完成',
        '5': '已完成',
        '6': '已关闭',
        '7': '已取消'
    };
    return statusMap[status] || status;
};

const orderStateFn = (status: any) => {
    orderState.value = status;
    list.value = [];
    getMescroll().resetUpScroll();
};

const toLink = (data: any) => {
    redirect({ url: '/addon/shop/pages/order/detail', param: { order_id: data.id } })
}

// 支付
const payRef =  ref<any>(null);
const orderBtnFn = (data: any, type = '') => {
    if (type == 'pay')
        payRef.value?.open(data.id, `/addon/shop/pages/order/detail?order_id=${data.id}`);
    else if (type == 'close') {
        close(data);
    } else if (type == 'finish') {
        finish(data);
    }
}

//关闭订单
const close = (item: any) => {
    uni.showModal({
        title: '提示',
        content: '您确定要取消订单吗？',
        confirmColor: useConfigStore().themeColor['--primary-color'],
        success: res => {
            if (res.confirm) {
                orderClose({id:item.id}).then((data) => {
                    getMescroll().resetUpScroll();
                })
            }
        }
    })
}

//订单完成
const finish = (item: any) => {
    uni.showModal({
        title: "提示",
        content: "您确定物品已收到吗？",
        confirmColor: useConfigStore().themeColor["--primary-color"],
        success: (res) => {
            if (res.confirm) {
                orderFinish({id:item.id}).then((data) => {
                    getMescroll().resetUpScroll();
                });
            }
        },
    });
}

const payClose =()=>{}
</script>
<style>
.order-list .mescroll-body {
    padding-bottom: constant(safe-area-inset-bottom) !important;
    padding-bottom: env(safe-area-inset-bottom) !important;
}

.order-list :deep(.u-count-down__text) {
    font-size: 24rpx !important;
    color: #EF000C !important;
}
</style>
<style lang="scss" scoped>
.text-color {
    color: var(--primary-color);
}

.bg-color {
    background-color: var(--primary-color);
}
</style>
