<template>
    <view class="order-list">
        <!-- 自定义顶部 -->
        <cm-header
            title="订单列表"
            :leftButtonGroup="leftButtonGroup"
            @rightClick="handleRightClick"
            @init="headerNavInit"
        ></cm-header>
        <!-- tabs选项卡 -->
        <tui-tabs
            :tabs="tabs"
            selectedColor="#f83c6c"
            sliderBgColor="#f83c6c"
            :currentTab="currentTab"
            @change="tabChange"
        ></tui-tabs>
        <!-- 协销订单筛选 -->
        <order-dealer-filter @change="onFilterChange"></order-dealer-filter>
        <!-- 页面轮播 -->
        <swiper
            :indicator-dots="false"
            :autoplay="false"
            :duration="400"
            :current="currentTab"
            @change="swiperChange"
            class="swiper"
            :style="[swiperHeight]"
        >
            <swiper-item v-for="(tab, index) in tabs" :key="index">
                <tui-skeleton v-if="isRefresh" :loadingType="3" :isLoading="true"></tui-skeleton>
                <scroll-view scroll-y="true" class="scroll-box" @scrolltolower="onScrollToLower">
                    <!-- 订单列表为空 -->
                    <template v-if="orderList.length <= 0 && !isLoading">
                        <tui-no-data :imgUrl="staticUrl + 'icon-empty-address.png'" :imgHeight="230" :imgWidth="290">
                            <view class="empty-tip">您还没有相关订单哟~~</view>
                        </tui-no-data>
                    </template>
                    <template v-else>
                        <view
                            class="section"
                            v-for="orderInfo in orderList"
                            :key="orderInfo.orderId"
                            @click="handleToDetail(orderInfo)"
                        >
                            <!-- 订单信息 -->
                            <view class="order-info">
                                <view class="order-no">
                                    <text class="label">订单编号：</text> <text>{{ orderInfo.orderNo }}</text>
                                </view>
                                <view class="order-time">
                                    <text class="label">下单时间：</text> <text>{{ orderInfo.orderTime }}</text>
                                </view>
                                <view class="order-status">{{ stateExpFormat(orderInfo.status) }}</view>
                            </view>
                            <tui-divider :height="48"></tui-divider>
                            <!-- 商品列表 -->
                            <view class="shop-list">
                                <view
                                    class="shop-section"
                                    v-for="shopInfo in orderInfo.shopOrderList"
                                    :key="shopInfo.shopOrderId"
                                >
                                    <order-supplier-area :shopInfo="shopInfo"></order-supplier-area>
                                </view>
                            </view>
                            <!-- 商品统计 -->
                            <view class="total">
                                <view class="count">共{{ orderInfo.productCount }}件商品</view>
                                <view class="price">
                                    <template v-if="['31', '32', '33', '81', '82', '83'].includes(orderInfo.status)">
                                        <text class="label">已支付：</text>
                                        <text>￥{{ orderInfo.receiptAmount | priceFormat }}</text>
                                    </template>
                                    <template v-else>
                                        <text class="label">待付总额：</text>
                                        <text>￥{{ orderInfo.pendingPayments | priceFormat }}</text>
                                    </template>
                                </view>
                            </view>
                            <!-- 操作订单 -->
                            <view class="control">
                                <order-contror
                                    v-if="orderInfo.userId == userId"
                                    :orderInfo="orderInfo"
                                    @confirm="handleConfirmClick"
                                ></order-contror>
                            </view>
                        </view>
                    </template>
                    <cm-loadmore :hasMore="hasNextPage" :isLoading="isLoading" :visiable="visiable"></cm-loadmore>
                </scroll-view>
            </swiper-item>
        </swiper>

        <!-- 失效商品列表 -->
        <order-invalid-modal
            :goodsList="invalidList"
            :visible="buyAgainModal"
            @confirm="buyAgainModalClick"
            @cancel="buyAgainModalHide"
        ></order-invalid-modal>

        <!-- 操作弹窗 -->
        <tui-modal :show="modal" :content="modalText" @click="handleModalConfirm"></tui-modal>
    </view>
</template>

<script>
import { fetchUserOrderList, fetchDealerOrderList } from '@/services/api/order.js'
import { debounce } from '@/common/utils.js'
import orderList from '@/pages/views/order/mixins/orderList.js'
import wechatPay from '@/pages/views/order/mixins/wechatPay.js'
import { mapGetters } from 'vuex'
export default {
    mixins: [wechatPay, orderList],
    data() {
        return {
            // 布局
            headerNavHeight: 0,
            leftButtonGroup: [
                {
                    icon: 'icon-daohangfanhui',
                    color: '#333'
                }
            ],
            // tab栏目配置
            tabs: [
                {
                    name: '全部',
                    state: 0,
                    mum: '',
                    isDot: false,
                    disabled: false
                },
                {
                    name: '待付款',
                    state: 1,
                    mum: '',
                    isDot: false,
                    disabled: false
                },
                {
                    name: '待分享',
                    state: 5,
                    mum: '',
                    isDot: false,
                    disabled: false
                },
                {
                    name: '待发货',
                    state: 2,
                    mum: '',
                    isDot: false,
                    disabled: false
                },
                {
                    name: '已发货',
                    state: 3,
                    mum: '',
                    isDot: false,
                    disabled: false
                },
                {
                    name: '退货/款',
                    state: 4,
                    mum: '',
                    isDot: false,
                    disabled: false
                }
            ],
            currentTab: -1,

            // 查询参数
            listQuery: {
                orderState: 0,
                userId: 0,
                orderType: 0,
                pageNum: 1,
                pageSize: 10
            },

            orderList: [],
            total: 0,
            hasNextPage: true,
            isLoading: true,
            isRefresh: true
        }
    },
    computed: {
        ...mapGetters(['userId', 'userIdentity']),
        visiable() {
            return this.orderList.length > this.listQuery.pageSize
        },
        isDealer() {
            return this.userIdentity === 2
        },
        // 布局
        swiperHeight() {
            let offset = 44
            if (this.isDealer) {
                offset = 84
            }
            return {
                height: `calc(100vh - ${offset}px - ${this.headerNavHeight}px);`
            }
        }
    },
    onLoad(options) {
        this.currentTab = options.current
        this.init()
    },
    onShow() {
        if (this.currentTab !== -1) {
            this.initOrderList()
        }
    },
    methods: {
        init() {
            // 订单操作回调
            this.$on('orderAction', () => {
                this.initOrderList()
            })
            // 订单支付回调
            this.$on('orderPaySuccess', orderInfo => {
                this.initOrderList()
                if (orderInfo.collageFlag) {
                    this.$router.navigateTo('share-buy/share-buy-detail?collageId=' + orderInfo.collageId)
                } else {
                    uni.setStorageSync('PAY_ORDER_INFO', orderInfo)
                    this.$router.navigateTo('order/pay-success')
                }
            })
        },

        // 初始化订单列表
        initOrderList() {
            this.listQuery.orderState = this.tabs[this.currentTab].state
            this.listQuery.userId = this.userId
            this.listQuery.pageNum = 1
            this.isRefresh = true
            this.hasNextPage = true
            this.fetchOrderList()
        },

        // 获取订单列表
        fetchOrderList: debounce(async function() {
            if (!this.hasNextPage) return
            this.isLoading = true
            if (this.isDealer) {
                this.fetchDealerOrderList()
            } else {
                this.fetchUserOrderList()
            }
        }),

        // 获取普通用户订单列表
        async fetchUserOrderList() {
            try {
                const res = await fetchUserOrderList(this.listQuery)
                if (this.isRefresh) {
                    this.orderList = res.data.list
                } else {
                    this.orderList = [...this.orderList, ...res.data.list]
                }
                this.total = res.data.total
                this.hasNextPage = res.data.hasNextPage
                this.listQuery.pageNum++
                this.isLoading = false
                this.isRefresh = false
            } catch (e) {
                console.log(e)
            }
        },

        // 获取分销者用户订单列表
        async fetchDealerOrderList() {
            try {
                const res = await fetchDealerOrderList(this.listQuery)
                if (this.isRefresh) {
                    this.orderList = res.data.list
                } else {
                    this.orderList = [...this.orderList, ...res.data.list]
                }
                this.total = res.data.total
                this.hasNextPage = res.data.hasNextPage
                this.listQuery.pageNum++
                this.isLoading = false
                this.isRefresh = false
            } catch (e) {
                console.log(e)
            }
        },

        // tab切换
        tabChange(e) {
            this.currentTab = e.index
        },

        // 轮播切换
        swiperChange(e) {
            this.currentTab = e.detail.current
            this.initOrderList()
        },
        // 协销筛选订单
        onFilterChange(id) {
            this.listQuery.orderType = id
            this.initOrderList()
        },

        // 搜索按钮点击
        handleRightClick() {
            this.$router.navigateTo('order/order-search')
        },

        // 订单详情
        handleToDetail(order) {
            this.$router.navigateTo('order/order-detail?orderId=' + order.orderId)
        },

        // 加载更多
        onScrollToLower() {
            this.fetchOrderList()
        },

        //自定义导航初始化
        headerNavInit(info) {
            this.headerNavHeight = info.height
        }
    }
}
</script>

<style lang="scss" scoped>
.scroll-box {
    height: 100%;
    box-sizing: border-box;
}

.section {
    padding: 24rpx;
    margin-bottom: 24rpx;
    background-color: #fff;
    .order-info {
        position: relative;
        line-height: 1.6;

        .order-no,
        .order-time {
            font-size: 26rpx;
            color: #333333;

            .label {
                color: #999999;
            }
        }

        .order-status {
            position: absolute;
            font-size: 26rpx;
            color: #ff457b;
            right: 0;
            bottom: 0;
        }
    }

    .shop-list {
        .shop-section {
            margin-bottom: 24rpx;

            &:last-child {
                margin-bottom: 0;
            }
        }
    }

    .total {
        display: flex;
        justify-content: space-between;
        align-items: center;

        margin-top: 24rpx;

        font-size: 26rpx;
        color: #333333;

        .count {
            font-weight: bold;
        }

        .price {
            color: #ff457b;

            .label {
                color: #333333;
            }
        }
    }

    .control {
        margin-top: 32rpx;
    }
}
</style>
