<template>
    <view class="apply-page">
        <view class="common-card flex-a flex-j-b mb-20" @click="handleAddress" v-if="defaultAddr.id">
            <image src="../../pages-mine/static/adderss.png" style="width:40rpx;height: 40rpx;"></image>
            <view class="flex-d flex-1 ml-24" style="margin-right: 90rpx;">
                <view class="flex-a flex-j-b  mb-10">
                    <view :style="titleStyle">{{ defaultAddr.name }}</view>
                    <view :style="titleStyle">{{ defaultAddr.mobile }}</view>
                </view>
                <view :style="titleStyle">地址：{{ defaultAddr.fullAddress }}</view>
            </view>
            <u-icon name="arrow-right" :size="28" color="#666" top="4"></u-icon>
        </view>
        <!-- 退回地址 -->
        <view v-else class="common-card flex-a flex-j-b mb-20" @click="handleAddress">
            <view class="flex-a">
                <u-icon name="plus-circle-fill" size="50" color="#38C148"></u-icon>
                <text class="required">退回地址</text>
            </view>
            <view class="flex-a">
                <view class="flex-d mr-10 flex-a-e">
                    <text class="common-text-2 font-28">请添加</text>
                    <text class="common-text font-24">提交后无法修改</text>
                </view>
                <u-icon name="arrow-right" size="32" color="#666666"></u-icon>
            </view>
        </view>

        <view class="common-card flex-a flex-j-b mb-20" style="padding: 30rpx;" @click="selectBooks">
            <text class="required">选择退回书籍</text>
            <view class="flex-a">
                <text class="common-text-2 font-26">{{ length ? `已选择${length}本` : '请选择' }}</text>
                <u-icon name="arrow-right" size="32" color="#666666"></u-icon>
            </view>
        </view>

        <!-- 退回书籍 -->
        <view class="common-card mb-20">
            <view class="common-title mb-20"> <text>订单编号: {{ orderId }}</text></view>

            <!-- 书籍列表 -->
            <select-book-item :book="item" v-for="(item, index) in bookItems" isReturn :key="index" />
        </view>

        <view class="common-card" style="padding: 30rpx;">
            <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">{{ length }}</text>
            </view>
        </view>

        <view class="bottom-fixed-con">
            <u-button type="primary" @click="handleConfirm">确认退回</u-button>
        </view>

        <CommonDialog ref="commonDialog" :title="dialogTitle" :showCancel="false">
            {{ dialogContent }}
        </CommonDialog>

        <CommonDialog ref="returnDialog" title="退回不通过书籍" :showFooter="false" width="88%">
            <view class="flex-a flex-j-b">
                <button class="confirm-btn plain" @click="handleApplyBack">我要取回</button>
                <button class="confirm-btn plain" @click="handleRecycleWare">仓库循环处理</button>
            </view>
            <view class="button-bottom" @click="handleRecycle">
                <text style="font-size: 32rpx;font-weight: bold;">按纸价回收</text>
                <text style="margin-top: 2px;">补贴 ¥{{ orderInfo.basicRecycleMoney || 0 }} 到余额</text>
            </view>
        </CommonDialog>

        <CommonDialog ref="recycleDialog" title="是否按纸价回收" @confirm="handleRecycleConfirm">
            补贴 ¥{{ orderInfo.basicRecycleMoney || 0 }} 到余额
        </CommonDialog>
        <CommonDialog ref="recycleWare" title="是否仓库循环处理" @confirm="handleRecycleWareConfirm">
            感谢您对环保事业的支持，仓库将循环处理
        </CommonDialog>
    </view>
</template>

<script>
import OrderItem from '../components/order-item.vue'
import selectBookItem from '../components/select-book-item.vue';
import commonDialog from '../../components/common-dialog.vue';
import CommonDialog from '../../components/common-dialog.vue';

export default {
    components: {
        OrderItem,
        selectBookItem,
        commonDialog,
        CommonDialog
    },
    onLoad(options) {
        this.isOnLoad = true
        if (options.orderId) {
            this.orderId = options.orderId
            this.getOrderInfo(this.orderId)
        }
    },
    data() {
        return {
            defaultAddr: {},
            orderId: '',
            bookItems: [],
            returnFee: 0,
            length: 0,
            isOnLoad: true,
            orderInfo: {},
            dialogTitle: '提示',
            dialogContent: '无此书或品相良好的书籍不需要退回。'
        }
    },

    methods: {
        //确认退回
        handleConfirm() {
            // 检查是否有"无此书"的审核原因
            const hasNoSuchBook = this.bookItems.some(book =>
                book.auditCommentList.some(audit => audit.com === '无此书')
            );

            if (hasNoSuchBook) {
                this.dialogContent = '无此书或品相良好的书籍不需要退回。';
                this.$refs.commonDialog.openPopup();
                return;
            }

            // 验证地址是否已选择
            if (!this.defaultAddr.id) {
                uni.showToast({
                    title: '请选择退回地址',
                    icon: 'none'
                });
                return;
            }

            // 验证是否选择了书籍
            if (!this.bookItems.length) {
                uni.showToast({
                    title: '请选择需要退回的书籍',
                    icon: 'none'
                });
                return;
            }

            // 打开退回选项对话框
            this.$refs.returnDialog?.openPopup();
        },

        //我要取回 - 提交退回申请
        handleApplyBack() {
            // 构建请求参数
            const detailList = this.bookItems.map(book => ({
                isbn: book.isbn,
                num: book.auditCommentList.length
            }));

            const params = {
                orderId: this.orderId,
                addressId: this.defaultAddr.id,
                detailList: detailList
            };

            // 发起请求
            uni.showLoading({
                title: '提交中...'
            });

            uni.$u.http.post('/token/order/submitRefundOrder', params)
                .then(res => {
                    if (res.code === 200) {
                        if (res.data.firstOrder == 1) {
                            // 提交成功后
                            this.dialogContent = '提交成功'
                            this.$refs.commonDialog.openPopup()
                            uni.removeStorageSync('selectAddr')
                        } else {
                            //跳转去付款页面
                            uni.navigateTo({
                                url: `/pages-mine/pages/cashier-desk?id=${res.data.refundOrderId}`
                            })
                        }
                    } else {
                        uni.showToast({
                            title: res.msg || '提交失败',
                            icon: 'none'
                        });
                    }
                })
                .finally(() => {
                    uni.hideLoading();
                });
        },

        //仓库循环处理
        handleRecycleWare() {
            this.$refs.recycleWare?.openPopup()
        },

        //仓库循环处理确认
        handleRecycleWareConfirm() {
            uni.$u.http.post('/token/order/notNeed', {
                orderId: this.orderId
            }).then(res => {
                if (res.code === 200) {
                    uni.$u.toast(`已补贴 ${this.orderInfo.basicRecycleMoney || 0} 到余额`)
                    uni.navigateBack()
                }
            })
        },

        //纸价回收
        handleRecycle() {
            this.$refs.recycleDialog?.openPopup()
        },

        //纸价回收确认
        handleRecycleConfirm() {
            uni.$u.http.post('/token/order/basicRecycle', {
                orderId: this.orderId
            }).then(res => {
                if (res.code === 200) {
                    uni.$u.toast('纸价回收成功')
                    uni.navigateBack()
                }
            })
        },

        // 选择书籍页面
        selectBooks() {
            uni.navigateTo({
                url: `/pages-mine/pages/return-select?orderId=${this.orderId}`
            })
        },

        //添加或者选择地址
        handleAddress() {
            uni.navigateTo({
                url: `/pages-mine/pages/address/list?id=${this.defaultAddr.id}&isSelect=1`
            })
        },

        //计算退回邮费
        calculateReturnFee() {
            // 如果是首单，显示免费退回
            if (this.orderInfo.firstOrder == 1) {
                return '首次免费退回';
            }

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

            // 小于4本是5元，超出4本的，在5元的基础上一本加1
            const baseFee = 5;
            const extraBooks = Math.max(0, bookCount - 4);
            const totalFee = baseFee + extraBooks;

            return `￥${totalFee.toFixed(2)}`;
        },

        //获取订单信息
        getOrderInfo(orderId) {
            if (!this.isOnLoad) {
                return
            }
            uni.$u.http.get('/token/order/getOrderDetail?orderId=' + orderId).then(res => {
                if (res.code === 200) {
                    this.isOnLoad = false
                    this.orderInfo = res.data

                    let length = 0
                    // 过滤出已审核不良的书籍，作为默认选择的书籍
                    this.bookItems = res.data.detailVoList.filter(book => {
                        let list = book.auditCommentList.filter(audit => audit.sts === 3 && audit.com !== '无此书')
                        list.forEach((audit, index) => {
                            audit.isSelected = true
                        })
                        book.auditCommentList = list
                        length += list.length
                        return list.length > 0
                    })

                    this.length = length
                    this.returnFee = this.calculateReturnFee()

                    uni.setStorageSync('selectedReturnBooks', {
                        selectedBooks: this.bookItems,
                        returnFee: this.returnFee,
                        length: this.length
                    })
                }
            })
        },
        //获取选中的书籍
        getSelectedBooks() {
            let selectedReturnBooks = uni.getStorageSync('selectedReturnBooks')
            if (selectedReturnBooks) {
                this.bookItems = selectedReturnBooks.selectedBooks || []
                this.returnFee = selectedReturnBooks.returnFee || 0
                this.length = selectedReturnBooks.length || 0
            }
        },
    },
    onShow() {
        if (!this.isOnLoad) {
            this.getSelectedBooks()
        }

        //选择的地址信息
        this.defaultAddr = uni.getStorageSync('selectAddr') || {}
    },
}
</script>

<style lang="scss" scoped>
.apply-page {
    min-height: 100vh;
    background: #f5f7fa;
    padding: 20rpx;
    padding-bottom: calc(env(safe-area-inset-bottom) + 130rpx);

    .required {
        font-size: 32rpx;
        color: #333;
        font-weight: 400;
        position: relative;
        margin-left: 10rpx;

        &::after {
            content: '*';
            color: #fa3534;
            margin-left: 4rpx;
        }
    }
}
.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;
}
</style>
