<template>
    <view class="my-order-page">
        <!-- 标签页 -->
        <view class="tabs-wrapper">
            <u-tabs :list="tabList" :current="currentTab" @change="handleTabChange" active-color="#38C148" bar-width="60"></u-tabs>
        </view>

        <!-- 订单列表 -->
        <page-scroll :page-size="10" @updateList="handleUpdateList" ref="pageRef" slotEmpty
            url="/token/shop/order/getShopOrderList" :params="params" :immediate="false">
            <view v-if="orderList.length > 0" class="order-list-container">
                <buy-order-item v-for="(order, index) in orderList" :key="index" :order="order"
                    @action="handleAction"></buy-order-item>
            </view>
        </page-scroll>

        <!-- 更多操作菜单 -->
        <u-action-sheet :list="actionSheetList" v-model="showActionSheet"
            @click="handleActionSheetClick"></u-action-sheet>
    </view>
</template>

<script>
    import BuyOrderItem from '../components/buy-order-item.vue';
    import pageScroll from '@/components/pageScroll/index.vue';

    export default {
        components: {
            BuyOrderItem,
            pageScroll
        },
        data() {
            return {
                // value用于前端标识，params用于后端查询
                tabList: [
                    { name: '全部', value: '0', params: {} },
                    { name: '待付款', value: '1', params: { status: '1' } },
                    { name: '待发货', value: '2', params: { status: '2' } },
                    { name: '待收货', value: '3', params: { status: '3' } },
                    { name: '已完成', value: '4', params: { status: '4' } },
                    { name: '退款/售后', value: '5', params: { status: '5' } },
                ],
                currentTab: 0,
                orderList: [],
                params: {},
                showActionSheet: false,
                actionSheetList: [],
                currentOrder: null
            };
        },
        onLoad(options) {
            if (options.status) {
                const index = this.tabList.findIndex(item => item.value == options.status);
                if (index !== -1) {
                    this.currentTab = index;
                    this.params = this.tabList[index].params;
                }
            }

            this.loadOrders(true, this.params);
        },
        methods: {
            loadOrders(refresh = false, params = {}) {
                this.$nextTick(() => {
                    this.$refs.pageRef?.loadData(refresh, params);
                });
            },
            handleTabChange(index) {
                this.currentTab = index;
                this.params = this.tabList[index].params;
                this.loadOrders(true, this.params);
            },
            handleUpdateList(list) {
                this.orderList = list;
            },
            handleAction({ type, order, data }) {
                console.log('Action:', type, order);
                this.currentOrder = order;

                if (type === 'more') {
                    // data contains the list of actions to show in sheet
                    // Map internal keys to display text
                    const actionMap = {
                        'applyAfterSales': { text: '申请售后', type: 'refund' },
                        'logistics': { text: '查看物流', type: 'logistics' },
                        'invoice': { text: '申请开票', type: 'invoice' }
                    };

                    this.actionSheetList = data.map(key => actionMap[key]).filter(Boolean);
                    this.showActionSheet = true;
                    return;
                }

                this.processAction(type, order);
            },
            handleActionSheetClick(index) {
                const action = this.actionSheetList[index];
                if (action && action.type) {
                    this.processAction(action.type, this.currentOrder);
                }
            },
            processAction(type, order) {
                if (type === 'rebuy' || type === 'addToCart') {
                    // Logic to add to cart
                    uni.showToast({ title: '已加入购物车', icon: 'none' });
                } else if (type === 'delete') {
                    uni.showModal({
                        title: '提示',
                        content: '确定要删除该订单吗？',
                        success: (res) => {
                            if (res.confirm) {
                                // Remove from list
                                this.orderList = this.orderList.filter(item => item.orderId !== order.orderId);
                                uni.showToast({ title: '删除成功', icon: 'none' });
                                // Call API to delete if needed
                            }
                        }
                    });
                } else if (type === 'remind') {
                    uni.showToast({ title: '已提醒商家发货', icon: 'none' });
                } else if (type === 'refund') {
                    uni.showToast({ title: '进入极速退款/售后流程', icon: 'none' });
                } else if (type === 'confirm') {
                    uni.showModal({
                        title: '提示',
                        content: '确认已收到商品？',
                        success: (res) => {
                            if (res.confirm) {
                                uni.showToast({ title: '确认收货成功', icon: 'none' });
                                // Update status locally or reload
                                this.loadOrders(true, this.params);
                            }
                        }
                    });
                } else if (type === 'logistics') {
                    uni.showToast({ title: '查看物流信息', icon: 'none' });
                } else if (type === 'address') {
                    uni.showToast({ title: '修改地址', icon: 'none' });
                } else if (type === 'pay') {
                    // 跳转到收银台
                    uni.navigateTo({
                        url: `/pages-car/pages/cashier-desk?id=${order.orderId}`
                    });
                } else if (type === 'cancel') {
                    uni.showModal({
                        title: '提示',
                        content: '确定要取消订单吗？',
                        success: (res) => {
                            if (res.confirm) {
                                uni.showToast({ title: '订单已取消', icon: 'none' });
                                this.loadOrders(true, this.params);
                            }
                        }
                    });
                } else {
                    uni.showToast({ title: '功能开发中', icon: 'none' });
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
    .my-order-page {
        min-height: 100vh;
        background-color: #F5F5F5;

        .tabs-wrapper {
            position: sticky;
            top: 0;
            z-index: 99;
            background: #FFFFFF;
            border-bottom: 1rpx solid #eee;
        }

        .order-list-container {
            padding: 20rpx;
        }
    }
</style>