<template>
    <view class="order-list-page" style="background-color: #fafafa">
        
        <view class="status" v-if="isLogin">
            <scroll-view scroll-x class="status-tabs" :show-scrollbar="false">
                <view style="padding-left: 20rpx">
                    <view 
                        class="tab-item"
                        v-for="(item, index) in firstTabs" 
                        :key="index"
                        :class="{ active: activeFirstId === item.id }" 
                        @click="handleFirstTabClick(item)"
                    >
                        {{ item.title }}
                    </view>
                </view>
            </scroll-view>

            <scroll-view scroll-x class="status-tabs2" :show-scrollbar="false">
                <view style="padding-left: 20rpx; white-space: nowrap; padding-bottom: 20rpx;">
                    <view 
                        class="tab-item2"
                        v-for="(item, index) in secondTabs" 
                        :key="index"
                        :class="{ active: activeSecondId === item.id }" 
                        @click="handleSecondTabClick(item.id, item.title)"
                    >
                        {{ item.title }}
                    </view>
                </view>
            </scroll-view>
        </view>

        <CommonList 
            ref="groupRef" 
            :isLogin="isLogin" 
            :apiUrl="apiUrl" 
            :listScrollHeight="`calc(100vh - 280rpx - 100rpx)`"
            @load-success="loadSuccess"
        >
            <template #listData="{ list }">
                <view class="order-item-wrap" v-for="item in popList" :key="item.id">
                    <OrderCard 
                        v-if="activeFirstId != 3" 
                        :haveButton="haveButton" 
                        :showState="false" 
                        :dataItem="item"
                        :typeId="activeFirstId" 
                        @cancel="cancelOrder($event, item)" 
                        @start="startOrder($event, item)"
                        @done="endOrder($event, item)" 
                        @goOrderDetail="goOrderDetail" 
                    />
                    
                    <WorkHourOrderCard 
                        v-else 
                        :showState="false" 
                        :dataItem="item" 
                        :typeId="activeFirstId"
                        @cancel="cancelOrder($event, item)" 
                        @accept="confirmOrder($event, item)"
                        @start="startOrder($event, item)" 
                        @done="endOrder($event, item)" 
                        @goOrderDetail="goOrderDetail"
                    >
                    </WorkHourOrderCard>
                </view>
            </template>

            <template #empty>
                <view class="noDataBox">
                    <noData tipText="暂无服务订单哟～" v-if="isLogin"></noData>
                    <view class="nologin_part" v-else>
                        <image src="/static/images/no_login.png" class="nologin_icon" mode="aspectFit"></image>
                        <view class="btn-login" @click="goLogin">
                            <text class="login-text">前去登录</text>
                        </view>
                    </view>
                </view>
            </template>
        </CommonList>

        <serviceCodeInput :show="showInput" @close="showInput = false" @confirm="onConfirm" />

        <TabBar :selected="1"></TabBar>
    </view>
</template>

<script>
    import OrderCard from "@/pages/home/components/orderCard2.vue";
    import WorkHourOrderCard from "@/pages/home/components/workOrderCard.vue";
    import CommonList from "@/components/common/CommonList.vue";
    import noLogin from "@/components/noData/noLogin.vue";
    import request from "@/utils/request";
    import serviceCodeInput from "@/components/service-code-input/service-code-input.vue";
    import TabBar from "@/components/tabbar/tabbar.vue";

    export default {
        name: "filters",
        props: {
            title: {
                type: String,
                default: "",
            },
            userInfo: {
                type: Object,
                default: () => ({}),
            },
            // 自营状态 0未加入 1加入 2停用
            selfState: {
                type: Number,
                default: 0,
            },
        },
        components: {
            CommonList,
            noLogin,
            serviceCodeInput,
            OrderCard,
            WorkHourOrderCard,
            TabBar
        },
        data() {
            return {
                isLogin: false, // 将isLogin移至data内管理
                popList:[],
                haveButton: true,
                statusBarHeight: 0,
                tabs: [{
                        title: "到店订单",
                        id: 1
                    },
                    {
                        title: "自营到店订单",
                        id: 2,
                        isNeedLogin: true,
                        isRuzHu: true,
                        isSelfOrder: true
                    },
                    {
                        title: "工位订单",
                        id: 3,
                        isNeedLogin: true,
                        id_type: 1
                    },
                    {
                        title: "上门订单",
                        id: 4,
                        isNeedLogin: true,
                        id_type: 1
                    },
                    {
                        title: "自营上门订单",
                        id: 5,
                        isNeedLogin: true,
                        id_type: 1
                    },
                ], // 1级类目
                activeFirstId: 1, // 记录选中的1级tab id
                activeSecondId: 3, // 记录选中的2级tab id（null表示"全部"）
                numInfo: {
                    djd: 0,
                    dfw: 0,
                    dwc: 0,
                    nocompletednum: 0,
                    noconfirmnum: 0,
                    noservernum: 0,
                },
                sjId: undefined,
                idType: undefined,
                showInput: false,
                orderInfo: {},
                urls: {
                    1: {
                        weChatRefund: "/sj/yhwechatrefund",
                        aliRefund: "/sj/yhalirefund",
                        startOrder: "/sj/startserver",
                        endOrder: "/sj/endserver",
                        ordernum: "/sj/ordernum",
                        list: "/sj/sjgetyhorder",
                    },
                    2: {
                        weChatRefund: "/sj/orderSelf/weChatRefund",
                        aliRefund: "/sj/orderSelf/aliRefund",
                        startOrder: "/sj/orderSelf/start",
                        endOrder: "/sj/orderSelf/end",
                        ordernum: "/sj/orderSelf/orderNum",
                        list: "/sj/orderSelf/list",
                    },
                    3: {
                        weChatRefund: "/sj/workSeatOrder/weChatRefund",
                        aliRefund: "/sj/workSeatOrder/aliRefund",
                        startOrder: "/sj/workSeatOrder/start",
                        sureOrder:"/sj/workSeatOrder/sure",
                        endOrder: "/sj/workSeatOrder/end",
                        ordernum: "/sj/workSeatOrder/orderNum",
                        list: "/sj/workSeatOrder/list",
                    },
                    4: {
                        ordernum: "/sj/sjonsiteordernum",
                        list: "/sj/sjonsiteorder",
                    },
                    5: {
                        ordernum: "/sj/sjonsiteordernumself",
                        list: "/sj/sjonsiteorderself",
                    }
                },
            };
        },
        computed: {
            apiUrl() {
                if(!this.urls[this.activeFirstId]){
                    return ""
                } 
                const urls = this.urls[this.activeFirstId];
                return urls.list;
            },
            getNumUrl() {
                const urls = this.urls[this.activeFirstId];
                return urls.ordernum;
            },
            // 计算是否显示自营订单tab
            showSelfOrderTab() {
                // 只有当self_state为1或2时才显示自营订单tab
                return this.selfState == 1 || this.selfState == 2;
            },
            firstTabs() {
                return this.tabs
                    .filter((tab) => !tab.isNeedLogin || this.isLogin)
                    .filter((tab) => {
                        if (tab.id_type) {
                            return this.idType == tab.id_type;
                        }
                        return true;
                    })
                    .filter((tab) => !tab.isRuzHu || this.idType != 0)
                    // 自营订单tab显示条件
                    .filter((tab) => {
                        if (tab.isSelfOrder) {
                            return this.showSelfOrderTab;
                        }
                        return true;
                    });
            },
            secondTabs() {
                if (this.activeFirstId == 1 || this.activeFirstId == 2) {
                    return [{
                            title: `待开始(${this.numInfo.noservernum})`,
                            id: 3
                        },
                        {
                            title: `待完成(${this.numInfo.nocompletednum})`,
                            id: 4
                        },
                    ];
                } else if (this.activeFirstId == 4 || this.activeFirstId == 5) {
                    return [{
                            title: `待接单(${this.numInfo.noconfirmnum})`,
                            id: 2
                        },
                        {
                            title: `待开始(${this.numInfo.noservernum})`,
                            id: 3
                        },
                        {
                            title: `待完成(${this.numInfo.nocompletednum})`,
                            id: 4
                        },
                    ];
                } else {
                    return [{
                            title: `待接单(${this.numInfo.djd})`,
                            id: 2
                        },
                        {
                            title: `待服务(${this.numInfo.dfw})`,
                            id: 3
                        },
                        {
                            title: `待完成(${this.numInfo.dwc})`,
                            id: 4
                        },
                    ];
                }

            },
        },
        onLoad() {
            uni.hideTabBar(); // 隐藏原生TabBar
        },
        onShow() {
			this.isLogin = uni.getStorageSync("accessToken") ? true : false;
			if (this.isLogin) {
				// 确保默认选中项正确
				if(!this.activeFirstId) this.activeFirstId = 1;
				if(!this.activeSecondId) this.activeSecondId = 3; // 或者你想默认 2 (待接单)，这里统一就行
				
				// 使用 $nextTick 确保 CommonList 组件已经渲染完毕再调用刷新
				this.$nextTick(() => {
					this.searchList();
				});
			} else {
				this.activeFirstId = null;
				this.activeSecondId = null; 
				this.popList = []; // 没登录清空数据
			}
		},
        // watch: {
        //     isLogin(newVal) {
        //         if (newVal) {
        //             this.activeFirstId = 1;
        //             this.activeSecondId = 2; // 默认选中"待接单"
        //             this.searchList();
        //         }
        //     },
        // },
        methods: {
            searchList() {
                if (this.syrId && this.idType) {
                    this.$refs.groupRef.manualRefresh({
                        sjid: this.sjId,
                        state: this.activeSecondId || undefined,

                    });
                } else {
                    request.post("/sj/user/getUser").then((result) => {
                        this.sjId = result.data.id;
                        this.idType = result.data.id_type;
                        this.$refs.groupRef.manualRefresh({
                            sjid: this.sjId,
                            state: this.activeSecondId,
                        });
                    });
                }
            },
            loadSuccess(res) {
                this.popList = res.list
                request
                    .post(this.getNumUrl, {
                        sjid: this.sjId,
                    })
                    .then((result) => {
                        for (let key in result.data) {
                            this.numInfo[key] = result.data[key];
                        }
                    });
            },
            // 一级tab点击事件
            handleFirstTabClick(item) {
				if (!this.isLogin) return;
				// 避免重复点击 (一定要在最前面！)
				if (this.activeFirstId === item.id) return;
				
				// 【修改点】：判断完不是重复点击后，再清空旧数据
				this.popList = []; 
				
				// 更新1级选中状态
				this.activeFirstId = item.id;

				this.haveButton = true;
				if (this.activeFirstId == 4 || this.activeFirstId == 5) {
					this.haveButton = false;
				}

				// 重置2级选中状态
				if (this.activeFirstId == 1 || this.activeFirstId == 2) {
					this.activeSecondId = 3;
				} else {
					this.activeSecondId = 2;
				}

				this.$emit("tabChange", {
					firstId: this.activeFirstId,
					secondId: this.activeSecondId,
				});
				
				this.$nextTick(() => {
					this.searchList();
				});
			},
            // 二级tab点击事件
            handleSecondTabClick(id, title) {
				if (!this.isLogin) return;
				// 避免重复点击！
				if (this.activeSecondId === id) return;	
				// 判断完不是重复点击后，再清空旧数据
				this.popList = []; 		
				// 更新2级选中状态
				this.activeSecondId = id;			
				this.$emit("tabChange", {
					firstId: this.activeFirstId,
					secondId: this.activeSecondId,
				});
				
				this.$nextTick(() => {
					this.searchList();
				});
			},
            cancelOrder(e, order) {
                uni.showModal({
                    title: "取消订单",
                    content: "确定要取消该订单吗？（订单取消后，支付金额将原路退回）",
                    success: (res) => {
                        if (res.confirm) {
                            // TODO: 取消订单
                            let data = {
                                orderNo: order.number,
                                amount: order.pay_money,
                                syrid: this.syrId,
                            };
                            let url = "";
                            if (order.pay_kind == 1) {
                                url = "";
                            } else if (order.pay_kind == 2) {
                                url = this.urls[this.activeFirstId].weChatRefund;
                            } else if (order.pay_kind == 3) {
                                url = this.urls[this.activeFirstId].aliRefund;
                            }
                            console.log(data, url);
                            if (this.clickType) {
                                return;
                            }
                            this.clickType = true;
                            request
                                .post(url, data)
                                .then((res) => {
                                    if (res.state == 1 || res.code == 200 || res.code == 1) {
                                        uni.showToast({
                                            title: "取消成功！",
                                            icon: "none",
                                        });
                                        this.searchList();
                                    } else {
                                        uni.showToast({
                                            title: res.msg,
                                            icon: "none",
                                        });
                                    }
                                })
                                .catch((err) => {
                                    console.log(err);
                                })
                                .finally(() => {
                                    this.clickType = false;
                                });
                        }
                    },
                });
            },
            // 确认接单
            confirmOrder(e, order) {
                if (this.clickType) {
                    return;
                }
                this.clickType = true;
                console.log(111,this.activeFirstId,this.urls)
                request
                    .post(this.urls[this.activeFirstId].sureOrder, {
                        id: order.id,
                        syrid: this.syrId,
                        order_kind: this.idType == 2 ? 3 : 1,
                    })
                    .then((res) => {
                        if (res.state != 1 || res.code != 200) {
                            uni.showToast({
                                title: "开始服务",
                                icon: "none",
                            });
                        } else {
                            uni.showToast({
                                title: "已接单",
                                icon: "none",
                            });
                        }
                        this.searchList();
                    })
                    .finally(() => {
                        this.clickType = false;
                    });
            },
            // 开始服务
            startOrder(e, order) {
                if (order.team_buy_order_state == 1) {
                    uni.showToast({
                        title: "订单当前处于拼团中，服务将在拼团完成后才开启~",
                        icon: "none",
                    });
                    return
                }
                this.showInput = true;
                this.orderInfo = order;
            },
            // 输入完成
            onConfirm(code) {
                this.showInput = false;
                if (this.clickType) {
                    return;
                }
                this.clickType = true;
                console.log(this.orderInfo, "this.urls[this.activeFirstId].startOrder");
                request
                    .post(this.urls[this.activeFirstId].startOrder, {
                        id: this.orderInfo.id,
                        server_code: code,
                        sjid: this.sjId,
                    })
                    .then((res) => {
                        console.log(res);
                        if (res.state == 1 || res.code == 200) {
                            uni.showToast({
                                title: "开始服务",
                                icon: "none",
                            });
                            this.searchList();
                        } else {
                            uni.showToast({
                                title: res.msg,
                                icon: "none",
                            });
                        }
                        this.orderInfo = {};
                    })
                    .finally(() => {
                        this.clickType = false;
                    });
            },
            // 完成服务
            endOrder(e, order) {
                // app阻止事件冒泡
                // #ifdef APP-PLUS
                // e.preventDefault();
                // e.stopPropagation();
                // #endif
                if (this.clickType) {
                    return;
                }
                this.clickType = true;
                request
                    .post(this.urls[this.activeFirstId].endOrder, {
                        id: order.id,
                        sjid: this.sjId,
                    })
                    .then((res) => {
                        if (res.state == 1 || res.code == 200) {
                            uni.showToast({
                                title: res.msg,
                                icon: "none",
                            });
                            this.searchList();
                        } else {
                            uni.showToast({
                                title: res.msg,
                                icon: "none",
                            });
                        }
                    })
                    .finally(() => {
                        this.clickType = false;
                    });
            },
            goOrderDetail(order) {
                if (this.idType == 1) {
                    if (this.activeFirstId == 1) {
                        uni.navigateTo({
                            url:  `/pages/shop/userorder-detail?order_id=${order.id}&order_kind=${order.order_kind}&haveButton=${this.haveButton}`,
                        });
                    }
                    if (this.activeFirstId == 2) {
                        uni.navigateTo({
                            url: `/pages/shop/userorder-detail?order_id=${order.id}&serviceType=2&haveButton=${this.haveButton}`,
                        });
                    }
                    if (this.activeFirstId == 3) {
                        uni.navigateTo({
                            url: `/pages/shop/SellerDetail?order_id=${order.id}&haveButton=${this.haveButton}`,
                        });
                    }
                    if (this.activeFirstId == 4) {
                        uni.navigateTo({
                            url: `/pages/shop/userorder-detail?order_id=${order.id}&order_kind=${order.order_kind}&haveButton=${this.haveButton}`,
                        });
                    }
                    if (this.activeFirstId == 5) {
                        uni.navigateTo({
                            url: `/pages/shop/userorder-detail?order_id=${order.id}&order_kind=${order.order_kind}&serviceType=2&haveButton=${this.haveButton}`,
                        });
                    }
                }
            },
            // 去登录
            goLogin() {
                uni.navigateTo({ url: '/pages/blogPopup/blogPopup' });
            }
        },
    };
</script>

<style scoped lang="less">
    .order-list-page {
        min-height: 100vh;
        display: flex;
        flex-direction: column;
    }

    /* 状态标签栏 (移植自用户端示例) */
    .status {
        position: sticky;
        top: 0;
        /* #ifdef H5 */
        top: 88rpx;
        /* H5端顶部适配 */
        /* #endif */
        left: 0;
        right: 0;
        background: #fff;
        z-index: 99;
    }

    .status-tabs {
        height: 94rpx;
        background-color: #ffffff;
        white-space: nowrap;
    }

    .tab-item {
        display: inline-block;
        height: 48rpx;
        position: relative;
        font-weight: 500;
        font-size: 30rpx;
        color: #333333;
        line-height: 42rpx;
        text-align: left;
        font-style: normal;
        margin: 20rpx 50rpx 26rpx 0rpx;
        
        &.active {
            color: #ff4767;
            font-weight: 500;
        }

        &.active::after {
            content: "";
            position: absolute;
            width: 34rpx;
            height: 6rpx;
            left: 50%;
            bottom: -16rpx;
            transform: translateX(-50%);
            background-color: #ff4767;
            border-radius: 3rpx;
        }
    }

    .status-tabs2 {
        height: 56rpx;
        background-color: #ffffff;
        white-space: nowrap;
        padding-bottom: 30rpx;
        padding-top: 10rpx;
    }

    .tab-item2 {
        display: inline-block;
        height: 56rpx;
        padding: 0 20rpx;
        background: #f3f5f6;
        border-radius: 10rpx;
        position: relative;
        margin: 0 18rpx 0 0;
        font-weight: 400;
        font-size: 28rpx;
        color: #333333;
        line-height: 56rpx;
        text-align: left;
        font-style: normal;
        
        &.active {
            color: #ff4767;
            font-weight: 500;
            background: #fee5e7;
        }
    }

    /* 数据列表及卡片外框样式 */
    .order-item-wrap {
        margin: 0 0 24rpx 0;
        border-radius: 20rpx;
        overflow: hidden;
    }

    .noDataBox {
        background-color: transparent;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    /* 未登录状态的样式 */
    .nologin_part {
        display: flex;
        flex-flow: column nowrap;
        justify-content: center;
        align-items: center;
    }

    .nologin_icon {
        width: 360rpx;
        height: 360rpx;
        margin-top: 100rpx;
        margin-bottom: 40rpx;
    }

    .btn-login {
        width: 200rpx;
        height: 68rpx;
        background-color: #ff4767;
        border-radius: 34rpx;
        display: flex;
        flex-flow: row nowrap;
        justify-content: center;
        align-items: center;
        box-shadow: 0 4rpx 10rpx rgba(255, 71, 103, 0.3);
    }

    .login-text {
        font-size: 30rpx;
        color: #fff;
    }

    ::v-deep .list-scroll {
        margin-top: 0 !important;
        box-sizing: border-box;
        /* padding-top: 24rpx; */
    }
</style>