<template>
    <pb-layout
        title="订单"
        navbar="normal"
        tabbar="/pages/index/order"
        :bgStyle="bgStyle"
        opacityBgUi="bg-white"
        color="black"
    >
        <pb-sticky bgColor="#fff">
            <pb-tabs :list="tabMaps" :scrollable="false" @change="onTabsChange" :current="state.currentTab" />
        </pb-sticky>
        <p-empty
            v-if="state.pagination.total === 0"
            icon="/static/order-empty.png"
            text="暂无订单"
            bgColor="transparent"
        />
        <view v-if="state.pagination.total > 0">
            <view
                class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
                v-for="order in state.pagination.list"
                :key="order.id"
            >
                <view @tap="onOrderDetail(order.id)">
                    <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
                        <view class="order-no">订单号：{{ order.no }}</view>
                        <view class="order-state ss-font-26" :class="formatOrderColor(order)">
                            {{ formatOrderStatus(order) }}
                        </view>
                    </view>
                    <view class="border-bottom" v-for="item in order.items" :key="item.id">
                        <p-goods-item
                            :img="item.picUrl"
                            :title="item.spuName"
                            :skuText="item.properties.map((property) => property.valueName).join(' ')"
                            :price="item.price"
                            :num="item.count"
                        />
                    </view>

                    <view
                        class="order-card-footer ss-flex ss-col-center ss-p-x-20"
                        :class="order.buttons.length > 3 ? 'ss-row-between' : 'ss-row-right'"
                    >
                        <view class="ss-flex ss-col-center">
                            <button
                                v-if="order.buttons.length === 0"
                                class="tool-btn ss-reset-button"
                                @tap.stop="onOrderDetail(order.id)"
                            >
                                查看详情
                            </button>
                            <button
                                v-if="order.buttons.includes('confirm')"
                                class="tool-btn ss-reset-button"
                                @tap.stop="onConfirm(order)"
                            >
                                确认收货
                            </button>
                            <button
                                v-if="order.buttons.includes('express')"
                                class="tool-btn ss-reset-button"
                                @tap.stop="onExpress(order.id)"
                            >
                                查看物流
                            </button>
                            <button
                                v-if="order.buttons.includes('cancel')"
                                class="tool-btn ss-reset-button"
                                @tap.stop="onCancel(order.id, sindex)"
                            >
                                取消订单
                            </button>
                            <button
                                v-if="order.buttons.includes('comment')"
                                class="tool-btn ss-reset-button"
                                @tap.stop="onComment(order.id)"
                            >
                                评价
                            </button>
                            <button
                                v-if="order.buttons.includes('delete')"
                                class="delete-btn ss-reset-button"
                                @tap.stop="onDelete(order.id)"
                            >
                                删除订单
                            </button>
                            <button
                                v-if="order.buttons.includes('verification')"
                                class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                                @tap.stop="onVerification(order.id)"
                            >
                                核销订单
                            </button>
                            <button
                                v-if="order.buttons.includes('delivery')"
                                class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                                @tap.stop="onDelivery(order.id)"
                            >
                                配送完成
                            </button>
                        </view>
                    </view>
                    <view class="pay-box ss-m-t-30 ss-flex ss-gap-40 ss-p-b-40 ss-row-right ss-p-r-20">
                        <view class="ss-flex ss-col-center">
                            <view class="discounts-title pay-color"
                                >共 {{ totalNumsPerOrder(order) }} 件商品,总金额:</view
                            >
                            <view class="discounts-money pay-color"> ￥{{ fen2yuan(totalPricePerOrder(order)) }} </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <uni-load-more
            v-if="state.pagination.total > 0"
            :status="state.loadStatus"
            :content-text="{ contentdown: '上拉加载更多' }"
        />
    </pb-layout>
</template>

<script setup>
import { ref } from 'vue'
import OrderApi from '@/peach/api/trade/order'
import { onLoad, onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { fen2yuan, formatOrderColor, formatOrderStatus, handleOrderButtons } from '@/peach/hooks/useGoods'
import peach from '@/peach'
import _, { isEmpty } from 'lodash'
import { resetPagination } from '@/peach/utils'

const bgStyle = {
    backgroundColor: 'var(--ui-BG-1)',
    description: '',
}

const state = ref({
    currentTab: 0,
    pagination: {
        list: [],
        total: 0,
        pageNo: 1,
        pageSize: 6,
    },
    loadStatus: '',
})

const tabMaps = [
    {
        name: '全部',
    },
    {
        name: '已付款',
        value: '50,60',
    },
    {
        name: '已评价',
        value: '30',
    },
    {
        name: '已退货',
        value: '10,20',
    },
]

function onDelivery(id) {
    OrderApi.orderComplete({ orderId: id }).then(() => {
        uni.showToast({
            title: '配送成功',
            icon: 'success',
        })
        setTimeout(() => {
            peach.$router.go('/pages/order/detail', {
                id: id,
            })
        }, 500)
    })
}

// 单个订单总商品数
function totalNumsPerOrder(order) {
    if (order.items.length) {
        return order.items.reduce((per, cur) => {
            return per + cur.count
        }, 0)
    }
}

// 单个订单总金额
function totalPricePerOrder(order) {
    if (order.items.length) {
        return order.items.reduce((per, cur) => {
            return per + cur.payPrice
        }, 0)
    }
}

// 切换选项卡
function onTabsChange(e) {
    if (state.value.currentTab === e.index) {
        return
    }
    // 重头加载代码
    resetPagination(state.value.pagination)
    state.value.currentTab = e.index
    getOrderList()
}

// 订单详情
function onOrderDetail(id) {
    peach.$router.go('/pages/order/detail', {
        id,
    })
}

// 获取订单列表
async function getOrderList() {
    state.value.loadStatus = 'loading'
    let { data } = await OrderApi.getOrderPage({
        pageNo: state.value.pagination.pageNo,
        pageSize: state.value.pagination.pageSize,
        status: state.value.currentTab !== 3 ? tabMaps[state.value.currentTab].value : undefined,
        refundStatus: state.value.currentTab === 3 ? tabMaps[state.value.currentTab].value : undefined,
    })

    data.list.forEach((item) => {
        handleOrderButtons(item)
    })
    state.value.pagination.list = _.concat(state.value.pagination.list, data.list)
    state.value.pagination.total = data.total
    let currentPageTotal = state.value.pagination.length
    state.value.loadStatus = currentPageTotal < state.value.pagination.total ? 'more' : 'noMore'
}

onLoad(async (options) => {
    if (options.type) {
        state.value.currentTab = options.type
    }
})

onShow(async () => {
    resetPagination(state.value.pagination)
    await getOrderList()
})

// 加载更多
function loadMore() {
    if (state.value.loadStatus === 'noMore') {
        return
    }
    state.value.pagination.pageNo++
    getOrderList()
}

// 上拉加载更多
onReachBottom(() => {
    loadMore()
})

// 下拉刷新
onPullDownRefresh(() => {
    resetPagination(state.value.pagination)
    getOrderList()
    setTimeout(function () {
        uni.stopPullDownRefresh()
    }, 800)
})
</script>

<style lang="scss" scoped>
.tool-btn {
    width: 160rpx;
    height: 60rpx;
    background: #f6f6f6;
    font-size: 26rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;

    &:last-of-type {
        margin-right: 0;
    }
}

.delete-btn {
    width: 160rpx;
    height: 56rpx;
    color: #ff3000;
    background: #fee;
    border-radius: 28rpx;
    font-size: 26rpx;
    margin-right: 10rpx;
    line-height: normal;

    &:last-of-type {
        margin-right: 0;
    }
}

.apply-btn {
    width: 140rpx;
    height: 50rpx;
    border-radius: 25rpx;
    font-size: 24rpx;
    border: 2rpx solid #dcdcdc;
    line-height: normal;
    margin-left: 16rpx;
}

.order-list-card-box {
    .order-card-header {
        height: 80rpx;

        .order-no {
            font-size: 26rpx;
            font-weight: 500;
        }

        .order-state {
        }
    }

    .pay-box {
        .discounts-title {
            font-size: 24rpx;
            line-height: normal;
            color: #999999;
        }

        .discounts-money {
            font-size: 24rpx;
            line-height: normal;
            color: #999;
            font-family: OPPOSANS;
        }

        .pay-color {
            color: #333;
        }
    }

    .order-card-footer {
        height: 100rpx;

        .more-item-box {
            padding: 20rpx;

            .more-item {
                height: 60rpx;

                .title {
                    font-size: 26rpx;
                }
            }
        }

        .more-btn {
            color: $dark-9;
            font-size: 24rpx;
        }

        .content {
            width: 154rpx;
            color: #333333;
            font-size: 26rpx;
            font-weight: 500;
        }
    }
}

:deep(.uni-tooltip-popup) {
    background: var(--ui-BG);
}

.warning-color {
    color: #faad14;
}

.danger-color {
    color: #ff3000;
}

.success-color {
    color: #52c41a;
}

.info-color {
    color: #999999;
}
</style>
