<template>
    <ele-modal
        :width="800"
        v-model="visible"
        title="缺货退款"
        @open="handleOpen"
        :body-style="{ padding: '20px' }"
    >
        <div class="refund-container">
            <div class="section-title">选择要退款的商品及数量</div>

            <el-table
                ref="tableRef"
                :data="order?.detailList || []"
                style="
                    width: 100%;
                    border: 1px solid #ebeef5;
                    border-bottom: none;
                "
                @selection-change="handleSelectionChange"
                header-row-class-name="custom-header"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column label="商品信息">
                    <template #default="{ row }">
                        <div class="product-info">
                            <el-image
                                :src="row.cover"
                                class="product-img"
                                fit="cover"
                            />
                            <span class="product-title"
                                >{{ row.bookName }} {{ row.isbn }}</span
                            >
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="150">
                    <template #default="{ row }">
                        <el-input-number
                            v-model="row.refundQty"
                            :min="1"
                            :max="row.num"
                            size="small"
                            controls-position="right"
                            style="width: 100px"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="单价" width="120">
                    <template #default="{ row }">
                        <span>¥{{ row.price }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <div class="refund-summary mt-4">
                <div class="summary-item">
                    <span class="label">退还商品：</span>
                    <span class="value"
                        >{{ productRefundAmount.toFixed(2) }} 元</span
                    >
                    <span class="sub-text">（共{{ selectedCount }}件）</span>
                </div>
                <div class="summary-item items-center">
                    <span class="label">退还运费：</span>
                    <el-input
                        v-model="shippingRefund"
                        style="width: 100px; margin-right: 10px"
                        placeholder="请输入"
                    />
                    <span class="label">元</span>
                    <span class="warning-text"
                        >（不超过{{ maxShippingFee }}元）</span
                    >
                </div>
                <div class="summary-item">
                    <span class="label">退款总额：</span>
                    <span class="total-amount"
                        >{{ totalRefundAmount.toFixed(2) }} 元</span
                    >
                    <span class="sub-text"
                        >（原订单总额{{ originalTotal.toFixed(2) }}元
                        新订单总额{{ newTotal.toFixed(2) }}元）</span
                    >
                </div>
                <div class="summary-item mt-2">
                    <el-checkbox v-model="sendCoupon">
                        <span class="font-bold">发送“缺货退款购书红包”</span>
                    </el-checkbox>
                </div>
            </div>
        </div>

        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading"
                >确定并退款</el-button
            >
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, computed, watch } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import request from '@/utils/request';

    const visible = defineModel({ type: Boolean });
    const order = ref(null);
    const selectedRows = ref([]);
    const shippingRefund = ref(0);
    const sendCoupon = ref(true);
    const maxShippingFee = ref(5);
    const loading = ref(false);

    const emit = defineEmits(['success']);

    const handleOpen = (row) => {
        // Deep copy to avoid mutating original list directly until save
        if (row) {
            order.value = JSON.parse(JSON.stringify(row));
            // Initialize refundQty for each product
            if (order.value.detailList) {
                order.value.detailList.forEach((p) => {
                    p.refundQty = p.num; // Default to max qty
                });
            }
            shippingRefund.value = order.value.expressMoney || 0;
            maxShippingFee.value = order.value.expressMoney || 0;
            sendCoupon.value = true;
            selectedRows.value = [];
        }
        visible.value = true;
    };

    const handleSelectionChange = (val) => {
        selectedRows.value = val;
    };

    const isAllSelected = computed(() => {
        if (!order.value?.detailList) return false;
        const totalItems = order.value.detailList.reduce(
            (sum, item) => sum + item.num,
            0
        );
        const selectedItems = selectedRows.value.reduce(
            (sum, item) => sum + (item.refundQty || 0),
            0
        );
        return totalItems > 0 && totalItems === selectedItems;
    });

    // Computed
    const productRefundAmount = computed(() => {
        if (isAllSelected.value) {
            // 如果全部退款，商品退款金额 = 订单实付金额 - 订单运费
            // 避免因单价精度导致的 1 分钱差值
            const originalProductTotal =
                originalTotal.value - maxShippingFee.value;
            return originalProductTotal > 0 ? originalProductTotal : 0;
        }

        const totalCents = selectedRows.value.reduce((sum, item) => {
            const price = parseFloat(item.payPrice || item.price) || 0;
            const amountCents = Math.round(price * (item.refundQty || 0) * 100);
            return sum + amountCents;
        }, 0);
        return totalCents / 100;
    });

    const selectedCount = computed(() => {
        return selectedRows.value.reduce((sum, item) => {
            return sum + (item.refundQty || 0);
        }, 0);
    });

    const totalRefundAmount = computed(() => {
        const shippingCents = Math.round(
            (parseFloat(shippingRefund.value) || 0) * 100
        );
        const productCents = Math.round(productRefundAmount.value * 100);
        return (productCents + shippingCents) / 100;
    });

    const originalTotal = computed(() => {
        return parseFloat(order.value?.payMoney) || 0;
    });

    const newTotal = computed(() => {
        const originalCents = Math.round(originalTotal.value * 100);
        const refundCents = Math.round(totalRefundAmount.value * 100);
        const newCents = originalCents - refundCents;
        return newCents > 0 ? newCents / 100 : 0;
    });

    const handleSubmit = () => {
        if (
            selectedRows.value.length === 0 &&
            parseFloat(shippingRefund.value) <= 0
        ) {
            EleMessage.warning('请选择退款商品或输入退款运费');
            return;
        }

        const shipping = parseFloat(shippingRefund.value) || 0;
        if (shipping > maxShippingFee.value) {
            EleMessage.error(`退还运费不能超过${maxShippingFee.value}元`);
            return;
        }

        loading.value = true;
        const detailList = selectedRows.value.map((item) => ({
            isbn: item.isbn,
            conditionType: item.conditionType,
            num: item.refundQty
        }));

        request
            .post('/shop/shopOrder/refundOutOfStock', {
                orderId: order.value.orderId,
                refundExpressMoney: shipping,
                sendCoupon: sendCoupon.value ? 1 : 0,
                detailList: detailList
            })
            .then((res) => {
                if (res.data.code === 200) {
                    EleMessage.success('退款申请已提交');
                    visible.value = false;
                    emit('success');
                } else {
                    EleMessage.error(res.data.msg || '提交失败');
                }
            })
            .catch((e) => {
                console.error(e);
                EleMessage.error('网络错误');
            })
            .finally(() => {
                loading.value = false;
            });
    };

    defineExpose({
        handleOpen
    });
</script>

<style scoped lang="scss">
    .refund-container {
        .section-title {
            font-weight: bold;
            margin-bottom: 10px;
            font-size: 14px;
            color: #303133;
        }

        .product-info {
            display: flex;
            align-items: center;

            .product-img {
                width: 50px;
                height: 50px;
                margin-right: 10px;
                border-radius: 4px;
            }

            .product-title {
                font-size: 13px;
                line-height: 1.4;
            }
        }

        .refund-summary {
            font-size: 14px;
            color: #606266;

            .summary-item {
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                line-height: 24px;

                .label {
                    font-weight: bold;
                    color: #303133;
                }

                .value {
                    color: #303133;
                    font-weight: bold;
                }

                .total-amount {
                    color: #f56c6c;
                    font-weight: bold;
                    font-size: 16px;
                }

                .sub-text {
                    color: #909399;
                    margin-left: 5px;
                    font-size: 13px;
                }

                .warning-text {
                    color: #303133;
                    font-weight: bold;
                }
            }
        }
    }

    :deep(.custom-header) th {
        background-color: #f5f7fa !important;
        color: #606266;
        font-weight: normal;
    }
</style>
