<template>
    <view class="my-footprint">
        <!-- 顶部操作栏 -->
        <view class="header" v-if="bookList.length">
            <view class="left">
                <u-checkbox v-if="isEditMode" class="checkbox-item" v-model="isAllSelected" @change="toggleSelectAll"
                    shape="circle" active-color="#38C148"></u-checkbox>
                <text v-if="isEditMode" class="select-text">全选</text>
            </view>
            <view class="right">
                <text v-if="!isEditMode" @tap="toggleEditMode">管理</text>
                <text v-else @tap="handleDelete">清除浏览记录</text>
            </view>
        </view>

        <!-- 书籍列表 -->
        <page-scroll :page-size="12" url="/token/shop/user/lookLogList" @updateList="handleUpdateList" ref="pageRef" slotEmpty emptyText="您暂无浏览记录">
            <view class="list-container">
                <view class="date-group" v-for="group in groupedList" :key="group.date">
                    <view class="date-header">{{ group.date }}</view>
                    <view class="book-list">
                        <BookListItem v-for="book in group.books" :key="book.id" :book="book" :isEditMode="isEditMode"
                            @click="handleBookClick" @checked="handleChecked" />
                    </view>
                </view>
            </view>
        </page-scroll>

        <!-- 删除确认弹窗 -->
        <common-dialog ref="deleteDialog" title="温馨提示" @confirm="confirmDelete">
            <text>确定清除选中的浏览记录吗？</text>
        </common-dialog>
    </view>
</template>

<script>
import BookListItem from '../components/book-list-item.vue'
import commonDialog from '@/components/common-dialog.vue'
import pageScroll from '@/components/pageScroll/index.vue'

export default {
    components: {
        BookListItem,
        commonDialog,
        pageScroll
    },
    data() {
        return {
            isEditMode: false,
            bookList: [],
            isAllSelected: false
        }
    },
    computed: {
        groupedList() {
            const groups = {};
            this.bookList.forEach(book => {
                // "2026-04-19T15:16:42.827Z" -> "2026-04-19" 或者直接使用截取
                let date = '未知日期';
                if (book.createTime) {
                    if (book.createTime.includes('T')) {
                        date = book.createTime.split('T')[0];
                    } else {
                        date = book.createTime.split(' ')[0];
                    }
                }
                
                if (!groups[date]) {
                    groups[date] = [];
                }
                groups[date].push(book);
            });
            
            // 按日期倒序排列
            const sortedDates = Object.keys(groups).sort((a, b) => new Date(b) - new Date(a));
            return sortedDates.map(date => {
                return {
                    date,
                    books: groups[date]
                };
            });
        }
    },
    // #ifdef MP-ALIPAY
    onPullDownRefresh() {
        this.$refs.pageRef?.loadData(true)
    },
    // #endif
    onShow() {
        this.$refs.pageRef?.loadData(true)
    },
    methods: {
        handleChecked({ book, checked }) {
            this.$nextTick(() => {
                let item = this.bookList.find(item => item.id === book.id)
                let index = this.bookList.findIndex(item => item.id === book.id)
                if (item) {
                    item.selected = checked
                    this.$set(this.bookList, index, item)
                    this.isAllSelected = this.bookList.every(item => item.selected)
                }
            })
        },
        handleBookClick(book) {
             uni.navigateTo({
                url: '/pages-sell/pages/detail?isbn=' + book.isbn
            });
        },
        handleUpdateList(data) {
            const oldSelectedIds = new Set(this.bookList.filter(v => v.selected).map(v => v.id));
            
            this.bookList = data.map(v => {
                return {
                    ...v,
                    selected: oldSelectedIds.has(v.id),
                    // BookListItem 显示组件使用 price 作为售价，producePrice 作为原价
                    // 足迹接口返回的是 sellPrice (售价) 和 price (原价)
                    price: v.sellPrice,
                    producePrice: v.price
                }
            })
            // 更新全选状态
            if (this.bookList.length > 0) {
                this.isAllSelected = this.bookList.every(item => item.selected);
            } else {
                this.isAllSelected = false;
            }
        },

        // 切换编辑模式
        toggleEditMode() {
            this.isEditMode = !this.isEditMode
            if (!this.isEditMode) {
                this.bookList.forEach(book => book.selected = false)
            } else {
                // 进入编辑模式不默认全选
                this.isAllSelected = false
                this.bookList.forEach(book => book.selected = false)
            }
        },

        // 切换全选
        toggleSelectAll() {
            const newValue = !this.isAllSelected
            this.bookList.forEach(book => book.selected = newValue)
        },

        // 处理删除
        handleDelete() {
            let deleteIds = this.bookList.filter(book => book.selected)
            if (deleteIds.length === 0) {
                uni.showToast({
                    title: '请选择要清除的记录',
                    icon: 'none'
                })
                return
            }
            this.$refs.deleteDialog.openPopup()
        },

        // 确认删除
        confirmDelete() {
            let deleteIds = this.bookList.filter(book => book.selected).map(v => v.id)
            this.$u.api.clearLookLogAjax(deleteIds).then(res => {
                if (res.code === 200) {
                    uni.showToast({
                        title: '清除成功',
                        icon: 'success'
                    })
                    this.$refs.pageRef?.loadData(true)
                    this.isEditMode = false;
                }
            })
        }
    }
}
</script>

<style lang="scss">
.my-footprint {
    min-height: 100vh;
    background: #F5F5F5;

    ::v-deep .checkbox-item {
        .u-checkbox__label {
            margin: 0 !important;
        }
    }

    .header {
        position: sticky;
        top: 0;
        left: 0;
        right: 0;
        z-index: 100;
        height: 88rpx;
        background: #FFFFFF;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 30rpx;
        font-size: 28rpx;
        border-bottom: 1rpx solid #EEEEEE;

        .left {
            display: flex;
            align-items: center;

            .select-text {
                margin-left: 12rpx;
                color: #333333;
            }
        }

        .right {
            text {
                color: #333333;

                &.delete-btn {
                    color: #FF5B5B;
                }
            }
        }
    }

    .scroll-view {
        height: calc(100vh - 88rpx);
    }

    .list-container {
        padding: 20rpx;
        
        .date-group {
            margin-bottom: 30rpx;
            
            .date-header {
                font-size: 32rpx;
                color: #333333;
                font-weight: bold;
                margin-bottom: 20rpx;
                padding-left: 10rpx;
            }
            
            .book-list {
                display: flex;
                flex-wrap: wrap;
                justify-content: flex-start;
                gap: 20rpx;
            }
        }
    }
}
</style>
