<template>
    <view class="order-detail">
        <!-- 书籍列表组件 -->
        <view class="book-list">
            <view class="header-info flex-a flex-j-b mb-20">
                <text class="common-title">卖书编号：{{ orderInfo.orderId }}</text>
            </view>

            <select-book-item :book="item" v-for="(item, index) in bookList" :key="index"
                @select="handleSelectBook"></select-book-item>
        </view>

        <!-- 收入信息区块 -->
        <view class="common-card" style="padding: 30rpx;margin: 30rpx;" @click="selectBooks">
            <view class="flex-a flex-j-b mb-20">
                <text class="common-text-2 font-30">退回邮费：</text>
                <text class="common-title" style="color: #FF0000;">{{ returnFee }}</text>
            </view>
            <view class="common-card flex-a flex-j-b" style="background: #fafafa;">
                <text class="common-text-2">书籍数量</text>
                <text class="common-text-2">{{ selectedBooks.length }}</text>
            </view>
        </view>

        <!-- 底部操作栏 -->
        <view class="bottom-fixed-con detail-bottom flex-d">
            <view class="flex-a" style="width: 100%;padding: 0 30rpx;">
                <u-checkbox v-model="isAllSelected" @change="handleSelectAll">全选</u-checkbox>
                <button class="confirm-btn" style="width:400rpx;margin-left: 100rpx;"
                    @click="handleConfirm">确认选择</button>
            </view>
        </view>
    </view>
</template>

<script>
import OrderTimeline from '../components/order-timeline.vue'
import BookList from '../components/book-list.vue'
import CommonDialog from '@/components/common-dialog.vue';
import selectBookItem from '../components/select-book-item.vue';

export default {
    components: {
        OrderTimeline,
        BookList,
        CommonDialog,
        selectBookItem
    },
    data() {
        return {
            bookList: [],
            orderInfo: {},
            isAllSelected: false
        }
    },
    computed: {
        selectedBooks() {
            // 计算选中的书籍列表
            let selected = [];
            this.bookList.forEach(book => {
                book.auditCommentList.forEach(audit => {
                    if (audit.isSelected) {
                        selected.push({ ...book, selectedAudit: audit });
                    }
                });
            });
            return selected;
        },
        returnFee() {
            // 如果是首单，显示免费退回
            if (this.orderInfo.firstOrder == 1) {
                return '首次免费退回';
            }

            const bookCount = this.selectedBooks.length;
            // 如果没有选择书籍，返回0
            if (bookCount === 0) {
                return '￥0.00';
            }

            // 5本以内收费4元，超过5本每本加收1元
            const baseFee = 5;
            const extraBooks = Math.max(0, bookCount - 4);
            const totalFee = baseFee + extraBooks;

            return `￥${totalFee.toFixed(2)}`;
        }
    },
    onLoad(options) {
        if (options.orderId) {
            this.getOrderInfo(options.orderId)
        }
    },
    methods: {
        copyOrderNo() {
            uni.setClipboardData({
                data: this.orderInfo.orderId.toString(),
                success: () => {
                    uni.$u.toast('复制成功')
                }
            })
        },
        //获取订单信息
        getOrderInfo(orderId) {
            uni.$u.http.get('/token/order/getOrderDetail?orderId=' + orderId).then(res => {
                if (res.code === 200) {
                    this.orderInfo = res.data
                    let selectedReturnBooks = uni.getStorageSync('selectedReturnBooks')
                    let selectedBooks = selectedReturnBooks.selectedBooks || []

                    this.bookList = res.data.detailVoList.filter(book => {
                        let selectedBook = selectedBooks.find(selectedBook => selectedBook.isbn === book.isbn)

                        let list = book.auditCommentList.filter(audit => audit.sts === 3)
                            .sort((a, b) => {
                                if (a.com === '无此书' && b.com !== '无此书') return 1;
                                if (a.com !== '无此书' && b.com === '无此书') return -1;
                                return 0;
                            });
                        list.forEach((audit, index) => {
                            audit.isSelected = selectedBook?.auditCommentList[index]?.isSelected || false
                        })
                        book.auditCommentList = list
                        return list.length > 0
                    })
                    this.isAllSelected = this.bookList.every(book =>
                        book.auditCommentList.every(audit => audit.isSelected)
                    );
                }
            })
        },
        //选择书籍
        handleSelectBook({ checked, index, isbn }) {
            let found = false;
            let updatedBook = null;

            this.bookList = this.bookList.map(book => {
                if (book.isbn === isbn) {
                    const updatedAuditList = book.auditCommentList.map((audit, idx) => {
                        if (idx === index) {
                            found = true;
                            return { ...audit, isSelected: checked };
                        }
                        return audit;
                    });
                    updatedBook = { ...book, auditCommentList: updatedAuditList };
                    return updatedBook;
                }
                return book;
            });

            if (found) {
                // 检查是否所有书籍都被选中
                this.isAllSelected = this.bookList.every(book =>
                    book.auditCommentList.every(audit => audit.isSelected)
                );
            }
        },
        //全选
        handleSelectAll({ value }) {
            this.isAllSelected = value;
            this.bookList = this.bookList.map(book => ({
                ...book,
                auditCommentList: book.auditCommentList.map(audit => ({
                    ...audit,
                    isSelected: value
                }))
            }));
        },
        //确认选择
        handleConfirm() {
            if (this.selectedBooks.length === 0) {
                uni.$u.toast('请选择要退回的书籍');
                return;
            }
            //筛选出来选中的书籍
            let selectedBooks = this.bookList.filter(book => {
                let list = book.auditCommentList.filter(audit => audit.isSelected)
                if (list.length > 0) {
                    book.auditCommentList = list
                    return book
                }
            })
            console.log(selectedBooks, 'xxxx');
            // 存储选中的书籍到本地
            uni.setStorageSync('selectedReturnBooks', { selectedBooks, returnFee: this.returnFee, length: this.selectedBooks.length });

            // 返回上一页
            uni.navigateBack({
                delta: 1
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.order-detail {
    min-height: 100vh;
    background: #f8f8f8;
    padding-bottom: 230rpx;

    .desc-bg {
        background: #fafafa;
        padding: 20rpx 30rpx;
        border-radius: 10rpx;
        margin-top: 20rpx;
    }

    .info-block {
        background: #FFFFFF;
        padding: 30rpx;
        margin: 30rpx;
        border-radius: 10rpx;
    }

    .detail-bottom {
        flex-direction: column;
        padding-left: 0;
        padding-right: 0;
        padding-top: 0;
    }
}

.button-bottom {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 30rpx 0;
    background-color: #38C148;
    color: #ffffff;
    font-size: 24rpx;
    line-height: 32rpx;
    padding: 16rpx 0;
    border-radius: 10rpx;
}

.book-list {
    background: #FFFFFF;
    padding: 20rpx 30rpx;
    margin: 30rpx;
    border-radius: 10rpx;
    box-sizing: border-box;
}
</style>