<template>
    <view class="order-search">
        <!-- 搜索区域 -->
        <view class="order-top sticky-top">
            <cm-search
                v-model="listQuery.searchWord"
                @search="handleSearch"
                placeholder="请输入搜索关键字"
                :keywordVisible="keywordVisible"
                :keywordList="keywordList"
                @focus="keywordVisible = true"
                @clear="keywordVisible = true"
                @remove="removeKeywordModal = true"
            ></cm-search>
        </view>
        <view class="order-list">
            <!-- 订单列表为空 -->
            <template v-if="orderList.length <= 0 && !isLoading">
                <tui-no-data :imgUrl="emptyInfo.image" :imgHeight="230" :imgWidth="290">
                    <view class="empty-tip" v-text="emptyInfo.message"></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>
                <cm-loadmore :hasMore="hasNextPage" :isLoading="isLoading" :visiable="visiable"></cm-loadmore>
            </template>
        </view>

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

        <!-- 操作弹窗 -->
        <tui-modal :show="removeKeywordModal" content="确认清空搜索历史记录？" @click="clearSearchRecord"></tui-modal>
    </view>
</template>

<script>
import { searchOrderList, fetchOrderSearchHistory, clearOrderSearchHistory } from '@/services/api/order.js'
import { debounce } from '@/common/utils.js'
import { mapGetters } from 'vuex'
import orderList from '@/pages/views/order/mixins/orderList.js'
import wechatPay from '@/pages/views/order/mixins/wechatPay.js'
export default {
    mixins: [orderList, wechatPay],
    data() {
        return {
            isLoading: false,
            keywordVisible: true,
            removeKeywordModal: false,
            keywordList: [],
            listQuery: {
                searchWord: '',
                userId: 0,
                pageNum: 1,
                pageSize: 10
            },
            orderList: [],
            total: 0,
            hasNextPage: true,
            isRefresh: true
        }
    },
    watch: {
        keywordVisible(nVal) {
            if (!nVal) return
            this.fetchSearchHistory()
            this.orderList = []
        }
    },
    computed: {
        ...mapGetters(['userId']),
        // 列表为空
        emptyInfo() {
            const info = {}
            info.image = `${this.staticUrl}icon-empty-address.png`
            info.message = '未找到相关订单~_~'

            if (this.keywordList.length <= 0) {
                info.message = '暂无任何搜索历史记录~_~'
            }

            return info
        },
        visiable() {
            return this.orderList.length > this.listQuery.pageSize
        }
    },
    onReachBottom() {
        this.fetchOrderList()
    },
    onLoad() {
        this.fetchSearchHistory()
    },
    methods: {
        handleSearch() {
            this.keywordVisible = false
            this.isRefresh = true
            this.hasNextPage = true
            this.listQuery.pageNum = 1
            this.listQuery.userId = this.userId
            this.fetchOrderList()
        },

        // 获取订单列表
        fetchOrderList: debounce(async function() {
            if (!this.hasNextPage) return
            this.isLoading = true
            try {
                const res = await searchOrderList(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++
            } catch (e) {
                console.log(e)
            } finally {
                this.isLoading = false
                this.isRefresh = false
            }
        }),

        // 获取搜索历史记录
        async fetchSearchHistory() {
            try {
                const res = await fetchOrderSearchHistory({ userId: this.userId })
                this.keywordList = res.data
                return res
            } catch (e) {
                console.log(e)
            }
        },
        // 清空搜索历史记录
        async clearSearchRecord(e) {
            if (!e.index) return (this.removeKeywordModal = false)
            try {
                await clearOrderSearchHistory({ userId: this.userId })
                await this.fetchSearchHistory()
                this.removeKeywordModal = false
                this.$toast('已清空搜索历史记录')
            } catch (e) {
                console.log(e)
            }
        },

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

<style lang="scss" scoped>
.order-list {
    .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>
