<template>
    <view :style="themeColor()">
        <view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden" v-if="!loading">
            <view v-if="!loading" class="pb-20rpx">
                <view class="pl-[40rpx] pr-[35rpx] bg-linear pb-[100rpx]">
                    <!-- #ifdef MP-WEIXIN -->
                    <top-tabbar :data="topTabbarData" :scrollBool="topTabarObj.getScrollBool()" />
                    <!-- #endif -->
                    <view class="flex justify-between items-center pt-[40rpx]">
                        <view class="flex flex-col">
                            <image class="w-[28rpx] h-[20rpx] mb-[10rpx] ml-[4rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/head_001.png'
                            )
                                " mode="aspectFit" />
                            <view class="text-[#fff] text-[36rpx] font-500 leading-[42rpx]">{{
                                getStatusText(detail.orderStatus)
                            }}</view>
                        </view>
                        <view class="flex items-end relative -bottom-[6rpx]">
                            <image v-if="detail.orderStatus == 1" class="w-[160rpx] h-[140rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/payment.png'
                            )
                                " mode="aspectFit" />
                            <image v-if="detail.orderStatus == 2" class="w-[160rpx] h-[140rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/deliver_goods.png'
                            )
                                " mode="aspectFit" />
                            <image v-if="detail.orderStatus == 3" class="w-[160rpx] h-[140rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/receive.png'
                            )
                                " mode="aspectFit" />
                            <image v-if="detail.orderStatus == 5" class="w-[160rpx] h-[140rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/complete.png'
                            )
                                " mode="aspectFit" />
                            <image v-if="detail.orderStatus == -1" class="w-[160rpx] h-[140rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/close.png'
                            )
                                " mode="aspectFit" />
                            <image class="w-[8rpx] h-[30rpx] mb-[20rpx]" :src="img(
                                'https://v6.site.niucloud.com/addon/shop/detail/head_002.png'
                            )
                                " mode="aspectFit" />
                        </view>
                    </view>
                </view>
                <view class="sidebar-margin mt-[-86rpx] card-template">
                    <view>
                        <view class="text-[#303133] flex">
                            <text class="nc-iconfont nc-icon-dizhiguanliV6xx text-[40rpx] pt-[12rpx] mr-[20rpx]"></text>
                            <view class="flex flex-col">
                                <view class="text-[30rpx] leading-[38rpx] overflow-hidden">
                                    <text>{{ addressInfo.consignee }}</text>
                                    <text class="ml-[15rpx]">{{ addressInfo.phone }}</text>
                                </view>
                                <view
                                    class="mt-[12rpx] text-[24rpx] text-[var(--text-color-light6)] using-hidden leading-[26rpx]">
                                    {{ addressInfo.provincialCityCountry
                                    }}{{ addressInfo.address }}</view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="sidebar-margin mt-[var(--top-m)] card-template" v-if="progressSteps && progressSteps.length>0">
                    <u-steps :current="currentStep" dot direction="column" activeColor="var(--primary-color)">
                        <template v-for="(item, index) in progressSteps" :key="index + 'id'">
                            <u-steps-item :title="item.title" :desc="item.time"></u-steps-item>
                        </template>
                    </u-steps>
                </view>
                <view class="sidebar-margin card-template p-[0] py-[var(--pad-top-m)] overflow-hidden" :class="{
                    'pb-[var(--pad-top-m)]': detail.orderProductList.length <= 0,
                }" :style="detail.delivery_type == 'virtual' || detail.taker_name == ''
                    ? 'margin-top: -86rpx'
                    : 'margin-top: 20rpx'
                    ">
                    <view v-for="(goodsItem, goodsIndex) in detail.orderProductList" :key="goodsIndex"
                        class="px-[var(--pad-sidebar-m)]">
                        <view class="order-goods-item flex justify-between flex-wrap mb-[20rpx]">
                            <view class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
                                @click="goodsEvent(goodsItem.productId)">
                                <u--image class="overflow-hidden" radius="var(--goods-rounded-big)" width="150rpx"
                                    height="150rpx" :src="img(goodsItem.productImage)" model="aspectFill">
                                    <template #error>
                                        <image
                                            class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
                                            :src="img('static/resource/images/diy/shop_default.jpg')"
                                            mode="aspectFill" />
                                    </template>
                                </u--image>
                            </view>

                            <view class="ml-[20rpx] flex flex-1 flex-col justify-between">
                                <view>
                                    <view class="text-[28rpx] max-w-[490rpx] truncate leading-[40rpx] text-[#333]">{{
                                        goodsItem.productName }}
                                    </view>
                                </view>

                                <view class="flex justify-between items-baseline leading-[28rpx] text-[#333]">
                                    <view class="price-font">
                                        <text class="text-[24rpx]">￥</text>
                                        <text class="text-[40rpx] font-500">{{
                                            parseFloat(goodsItem.orderPrice).toFixed(2).split(".")[0]
                                        }}</text>
                                        <text class="text-[24rpx] font-500">.{{
                                            parseFloat(goodsItem.orderPrice)
                                                .toFixed(2)
                                                .split(".")[1]
                                        }}</text>
                                    </view>
                                    <text class="text-right text-[26rpx]">x{{ goodsItem.orderQuantity }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="sidebar-margin mt-[var(--top-m)] card-template">
                    <view class="justify-between card-template-item">
                        <view class="text-[28rpx]">订单号</view>
                        <view class="flex items-center text-[28rpx]">
                            <text>{{ detail.orderNo }}</text>
                            <text class="w-[2rpx] h-[20rpx] bg-[#999] mx-[10rpx]"></text>
                            <text class="text-[var(--primary-color)]" @click="copy(detail.orderNo)">复制</text>
                        </view>
                    </view>
                    <view class="justify-between card-template-item">
                        <view class="text-[28rpx]">创建时间</view>
                        <view class="text-[28rpx]">{{ detail.orderTime }}</view>
                    </view>
                    <view class="justify-between card-template-item">
                        <view class="text-[28rpx]">跟新时间</view>
                        <view class="text-[28rpx]">{{ detail.updateTime }}</view>
                    </view>
                </view>
                <view class="sidebar-margin mt-[var(--top-m)] card-template">
                    <view class="justify-between card-template-item">
                        <view class="text-[28rpx]">配送时间</view>
                        <view class="text-[28rpx]">{{ detail.expectedDeliveryTime || "-" }}
                        </view>
                    </view>
                    <view class="justify-between card-template-item">
                        <view class="text-[28rpx]">采购事由</view>
                        <view class="text-[28rpx]">{{ detail.purchaseReason || "-" }}
                        </view>
                    </view>
                    <view class="justify-between card-template-item">
                        <view class="text-[28rpx]">费用类型</view>
                        <view class="text-[28rpx]">日常物资采购</view>
                    </view>
                    <view class="card-template-item justify-between">
                        <view class="text-[28rpx]">订单备注</view>
                        <view class="text-[28rpx]">{{ detail.remark || "-" }}</view>
                    </view>
                </view>
                <view class="sidebar-margin mt-[var(--top-m)] card-template">
                    <view class="card-template-item justify-between">
                        <view class="text-[28rpx]">商品金额</view>
                        <view class="price-font font-500">
                            <template v-if="parseFloat(detail.totalAmount)">
                                <text class="text-[28rpx]">￥</text>
                                <text class="text-[28rpx]">{{
                                    parseFloat(detail.totalAmount).toFixed(2).split(".")[0]
                                }}</text>
                                <text class="text-[28rpx]">.{{
                                    parseFloat(detail.totalAmount).toFixed(2).split(".")[1]
                                }}</text>
                            </template>
                        </view>
                    </view>
                    <view class="card-template-item justify-between">
                        <view class="text-[28rpx]">配送费用</view>
                        <view class="price-font font-500 text-[28rpx]">￥{{ detail.shippingFee }}</view>
                    </view>
                    <view class="card-template-item justify-between items-baseline">
                        <view class="text-[28rpx]">实付金额</view>
                        <view class="text-[var(--price-text-color)] price-font">
                            <text v-if="
                                parseFloat(detail.order_money) || !parseFloat(detail.point)
                            " class="text-[28rpx]">￥{{ parseFloat(detail.totalAmount).toFixed(2) }}</text>
                        </view>
                    </view>
                </view>

                <view
                    class="flex z-2 justify-between items-center bg-[#fff] fixed left-0 right-0 bottom-0 min-h-[100rpx] pl-[30rpx] pr-[20rpx] flex-wrap pb-ios">
                    <view class="flex justify-end">
                        <view @click="orderBtnFn('index')" class="order-grey-hollow-btn ml-[20rpx]">首页</view>
                        <view
                            class="px-[35rpx] box-border text-[24rpx] h-[60rpx] flex-center text-center border-[2rpx] border-solid border-[#ccc] rounded-full ml-[20rpx] text-[var(--text-color-light3)]"
                            @click="orderBtnFn('logistics')"
                            v-if="detail.isNeedCheck == '0' && detail.checkStatus != '0'">查看物流
                        </view>
                        <view class="order-grey-hollow-btn ml-[20rpx]"
                            v-if="detail.orderStatus == 1 || detail.orderStatus == 0" @click="orderBtnFn('close')">取消订单
                        </view>
                        <view v-if="detail.orderStatus == 1"
                            class="px-[35rpx] box-border text-[24rpx] h-[60rpx] flex-center text-center text-[#fff] primary-btn-bg rounded-full ml-[20rpx]"
                            @click="orderBtnFn('pay')">去支付</view>
                        <view v-if="detail.orderStatus == 4"
                            class="px-[35rpx] box-border text-[24rpx] h-[60rpx] flex-center text-center text-[#fff] primary-btn-bg rounded-full ml-[20rpx]"
                            @click="orderBtnFn('finish')">确认收货</view>
                    </view>
                </view>
            </view>
            <view class="tab-bar-placeholder"></view>
            <pay ref="payRef" @close="payClose"></pay>
            <logistics-tracking ref="materialRef"></logistics-tracking>
        </view>

        <loading-page :loading="loading"></loading-page>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { img, redirect, copy, goback } from "@/utils/common";
import {
    getShopOrderDetail,
    getOrderFlowNodes,
    orderClose,
    orderFinish,
    getAddressInfo,
    selectOrderDeliverByOrderId,
} from "@/addon/shop/api/order";
import logisticsTracking from "@/addon/shop/pages/order/components/logistics-tracking/logistics-tracking.vue";
import useConfigStore from "@/stores/config";
import { topTabar } from "@/utils/topTabbar";

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar();
let topTabbarData = topTabarObj.setTopTabbarParam({ title: "订单详情" });
/********* 自定义头部 - end ***********/

const detail: any = ref<Object>({});
const addressInfo = ref<any>({});
const loading = ref<boolean>(true);
const orderId = ref("");
const progressSteps = ref<any>([]);
const currentStep = ref(1);

const wxPrivacyPopupRef: any = ref(null);

onLoad((option: any) => {
    if (option.order_id) {
        orderId.value = option.order_id;
        orderDetailFn(orderId.value);
        // #ifdef MP
        nextTick(() => {
            if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
        });
        // #endif
    } else {
        let parameter = {
            url: "/addon/shop/pages/order/list",
            title: "缺少订单id",
        };
        goback(parameter);
    }
});

const orderDetailFn = (id: any) => {
    loading.value = true;
    getShopOrderDetail(id)
        .then((res: any) => {
            detail.value = res.data;
            loadFlowNodes()
            getAddressInfo(res.data.shippingAddressId).then((res1: any) => {
                addressInfo.value = res1.data;
            });

            loading.value = false;
        })
        .catch(() => {
            loading.value = false;
        });


};

// 加载审批流程节点
const loadFlowNodes = async () => {
    try {
        const res = (await getOrderFlowNodes(orderId.value)) as any;
        if (res.code === 200) {
            const apiNodes: any = res.data || [];

            // 提交订单节点：显示订单的 createTime
            const steps: { title: string; desc: string; time: string; reviewStatus?: number }[] = [
                { title: '提交订单', desc: '订单已提交', time: formatTime(detail.value.createTime), reviewStatus: 2 }
            ];

            // 并行解析所有节点的审批人名称
            const handlerNames = await Promise.all(apiNodes.map((node: any) => resolveHandlerName(node.handlerId || node.handlerName || '')));

            apiNodes.forEach((node: any, idx: any) => {
                steps.push({
                    title: node.nodeName || '审批',
                    desc: handlerNames[idx] || '',
                    time: formatTime(node.updateTime || ''),
                    reviewStatus: node.reviewStatus ?? 0
                });
            });

            // 完成节点：显示订单的 updateTime
            // steps.push({ title: '完成', icon: CircleCheck, desc: '交易完成', time: formatTime(orderTimeInfo.updateTime), reviewStatus: 0 });

            progressSteps.value = steps;

            console.log(progressSteps, '???????????')

            // 计算当前步骤：找最后一个已处理节点的索引（reviewStatus > 0）
            let lastActiveIndex = 0;
            steps.forEach((step, idx) => {
                if (step.reviewStatus && step.reviewStatus > 0) {
                    lastActiveIndex = idx;
                }
            });
            // 若所有中间节点均已完成（reviewStatus === 2），则激活结束节点
            const middleNodes = steps.slice(1, steps.length - 1);
            if (middleNodes.length > 0 && middleNodes.every((s) => s.reviewStatus === 2)) {
                lastActiveIndex = steps.length - 1;
            }
            currentStep.value = lastActiveIndex;
        }
    } catch (error) {
        console.error('加载流程节点失败', error);
    }
};

// 格式化时间为 "2026/3/17 上午10:49" 格式
const formatTime = (timeStr: any): string => {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) return timeStr;
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true
    });
};

// 单人：返回姓名；多人：返回"xx或xx审核"
const resolveHandlerName = async (handlerId: string): Promise<string> => {
    if (!handlerId) return '';
    const ids = handlerId
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
    if (ids.length === 0) return '';
    try {
        const results = await Promise.all(ids.map((id) => getContactInfo(String(id)).catch(() => null)));
        const names = results.map((res: any) => res?.data?.contactName || '').filter(Boolean);
        if (names.length === 0) return '';
        if (names.length === 1) return names[0];
        return names.join('或') + '审核';
    } catch {
        return '';
    }
};

//关闭订单
const close = () => {
    uni.showModal({
        title: "提示",
        content: "您确定要关闭该订单吗？",
        confirmColor: useConfigStore().themeColor["--primary-color"],
        success: (res) => {
            if (res.confirm) {
                orderClose({ id: orderId.value }).then((data) => {
                    orderDetailFn(orderId.value);
                });
            }
        },
    });
};

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

const goodsEvent = (id: number) => {
    redirect({
        url: "/addon/shop/pages/goods/detail",
        param: {
            goodsId: id,
        },
    });
};

const payRef = ref<any>(null);
const materialRef: any = ref(null);
const orderBtnFn = (type = "") => {
    if (type == "pay")
        payRef.value?.open(
            orderId.value,
            `/addon/shop/pages/order/detail?order_id=${orderId.value}`
        );
    else if (type == "close") {
        close();
    } else if (type == "finish") {
        finish();
    } else if (type == "index") {
        redirect({
            url: "/addon/shop/pages/index",
            mode: "reLaunch",
        });
    } else if (type == "logistics") {
        selectOrderDeliverByOrderId({ orderId: orderId.value }).then(
            (res1: any) => {
                if (res1.rows.length > 0) {
                    let list = res1.rows;
                    materialRef.value.open(list[0]);
                    materialRef.value.packageList = list;
                }
            }
        );
    }
};
// 根据订单状态获取状态文本
const getStatusText = (status: string) => {
    const statusMap: Record<string, string> = {
        "0": "待支付",
        "1": "待确认",
        "2": "待发货",
        "3": "部分发货",
        "4": "发货完成",
        "5": "已完成",
        "6": "已关闭",
        "7": "已取消",
    };
    return statusMap[status] || status;
};

const payClose = () => { };
</script>
<style lang="scss" scoped>
.text-item {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.order-goods-item:nth-child(1) {
    margin-top: 0;
}

.text-color {
    color: $u-primary;
}

.bg-color {
    background-color: $u-primary;
}

.bg-linear {
    background: linear-gradient(90deg, #ff0000 0%, #ff7800 100%);
}

.triangle {
    @apply relative;

    &::before {
        content: "";
        @apply absolute;
        width: 0;
        height: 0;
        position: absolute;
        bottom: -40rpx;
        border: 20rpx solid transparent;
        border-top-color: #eef3ff;
    }
}

.tab-bar-placeholder {
    padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}

:deep(.u-image__error) {
    background-color: transparent !important;
}

.friend-pay {
    &::after {
        content: "";
        display: block;
        width: 20rpx;
        height: 20rpx;
        background-color: #f2f2f2;
        position: absolute;
        right: 30rpx;
        top: 0;
        transform: translateY(-50%) rotate(45deg);
        border-radius: 4rpx;
    }
}
</style>
