<template>
    <ele-modal
        :width="600"
        v-model="visible"
        title="同意退货"
        :body-style="{ padding: '20px 40px' }"
    >
        <div
            class="mb-4 p-3 bg-orange-50 text-orange-500 rounded text-sm flex items-start"
        >
            <el-icon class="mr-2 mt-0.5"><WarningFilled /></el-icon>
            <span
                >如因您提供的退货地址错误，导致买家无法退货或退回商品后无法送达，将由您承担产生的后果。</span
            >
        </div>

        <el-form
            :model="form"
            :rules="rules"
            ref="formRef"
            label-width="80px"
            label-position="top"
        >
            <div class="flex justify-between items-center mb-2">
                <span class="text-red-500"
                    >* <span class="text-gray-700">退货地址</span></span
                >
                <el-button link type="primary" @click="handleManageAddress"
                    >管理退货地址</el-button
                >
            </div>
            <el-form-item prop="refundAddressId" label-width="0">
                <el-popover
                    v-model:visible="addressPickerVisible"
                    trigger="click"
                    placement="bottom-start"
                    :width="520"
                    popper-class="refund-address-popper"
                >
                    <template #reference>
                        <div
                            class="w-full rounded-md border px-3 py-2 flex items-center justify-between cursor-pointer transition"
                            :class="
                                addressPickerVisible
                                    ? 'border-emerald-400 ring-2 ring-emerald-100'
                                    : 'border-gray-200'
                            "
                        >
                            <div class="flex-1 min-w-0">
                                <template v-if="selectedAddress">
                                    <div class="text-sm text-gray-900 truncate">
                                        {{ selectedAddress.name }}
                                        {{ selectedAddress.mobile }}
                                        <el-tag
                                            v-if="
                                                Number(
                                                    selectedAddress.defaultReturnFlag
                                                ) === 1
                                            "
                                            size="small"
                                            type="success"
                                            class="ml-2"
                                            >默认</el-tag
                                        >
                                    </div>
                                    <div
                                        class="text-xs text-gray-500 truncate mt-0.5"
                                    >
                                        {{ selectedAddress.address }}
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="text-sm text-gray-400">
                                        请选择退货地址
                                    </div>
                                </template>
                            </div>
                            <el-icon class="ml-2 text-gray-400"
                                ><ArrowDown
                            /></el-icon>
                        </div>
                    </template>

                    <div class="max-h-72 overflow-auto p-2">
                        <div
                            v-if="addressLoading"
                            class="py-6 flex items-center justify-center text-gray-500 text-sm"
                        >
                            <el-icon class="is-loading mr-2"
                                ><Loading
                            /></el-icon>
                            加载中
                        </div>
                        <div
                            v-else-if="!addressList.length"
                            class="py-6 text-center text-gray-400 text-sm"
                        >
                            暂无可用退货地址
                        </div>
                        <div v-else class="space-y-2">
                            <div
                                v-for="item in addressList"
                                :key="item.id"
                                class="rounded-md border px-3 py-2 cursor-pointer transition"
                                :class="
                                    String(form.refundAddressId) ===
                                    String(item.id)
                                        ? 'border-emerald-400 bg-emerald-50'
                                        : 'border-gray-100 hover:border-gray-200 hover:bg-gray-50'
                                "
                                @click="handleSelectAddress(item)"
                            >
                                <div class="flex items-center">
                                    <div class="font-medium text-gray-900">
                                        {{ item.name }}
                                    </div>
                                    <div class="ml-2 text-sm text-gray-500">
                                        {{ item.mobile }}
                                    </div>
                                    <el-tag
                                        v-if="
                                            Number(item.defaultReturnFlag) === 1
                                        "
                                        size="small"
                                        type="success"
                                        class="ml-2"
                                        >默认</el-tag
                                    >
                                </div>
                                <div class="text-xs text-gray-500 mt-1">
                                    {{ item.address }}
                                </div>
                            </div>
                        </div>
                    </div>
                </el-popover>
            </el-form-item>

            <el-form-item label="退货说明" prop="description">
                <el-input
                    v-model="form.description"
                    type="textarea"
                    :rows="4"
                    placeholder="请填入退货说明"
                    maxlength="200"
                    show-word-limit
                    class="bg-gray-50"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="flex justify-center gap-4">
                <el-button
                    @click="visible = false"
                    class="bg-blue-50 text-blue-500 border-none"
                    >取消并返回</el-button
                >
                <el-button
                    type="primary"
                    :loading="loading"
                    @click="handleSubmit"
                    >同意退货</el-button
                >
            </div>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, computed } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import { ArrowDown, Loading, WarningFilled } from '@element-plus/icons-vue';
    import { useRouter } from 'vue-router';
    import request from '@/utils/request';

    const router = useRouter();
    const visible = ref(false);
    const loading = ref(false);
    const addressLoading = ref(false);
    const addressPickerVisible = ref(false);
    const formRef = ref(null);
    const currentRefundOrderId = ref('');
    const addressList = ref([]);
    const selectedAddress = computed(() => {
        const id = String(form.refundAddressId || '');
        if (!id) return null;
        return addressList.value.find((a) => String(a.id) === id) || null;
    });

    const form = reactive({
        refundAddressId: '',
        description: ''
    });

    const rules = {
        refundAddressId: [
            { required: true, message: '请选择退货地址', trigger: 'change' }
        ]
    };

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

    const fetchAddressList = () => {
        addressLoading.value = true;
        // 使用图2的接口获取退款地址列表
        request
            .get('/shop/shopAddress/getRefundAddressList')
            .then((res) => {
                if (res.data.code === 200) {
                    addressList.value = res.data.data || [];
                    // 自动选择默认退货地址（依据接口文档中的 defaultReturnFlag === 1）
                    if (addressList.value.length > 0 && !form.refundAddressId) {
                        const defaultAddr = addressList.value.find(
                            (a) => Number(a.defaultReturnFlag) === 1
                        );
                        form.refundAddressId = defaultAddr
                            ? defaultAddr.id
                            : addressList.value[0].id;
                    }
                } else {
                    EleMessage.error(res.data.msg || '获取地址列表失败');
                }
            })
            .catch((e) => {
                console.error(e);
                EleMessage.error('获取地址列表失败');
            })
            .finally(() => {
                addressLoading.value = false;
            });
    };

    const handleSelectAddress = (item) => {
        form.refundAddressId = item.id;
        addressPickerVisible.value = false;
        formRef.value?.validateField?.('refundAddressId');
    };

    const open = (refundOrderId) => {
        currentRefundOrderId.value = refundOrderId;
        form.refundAddressId = '';
        form.description = '';
        addressPickerVisible.value = false;
        if (formRef.value) {
            formRef.value.clearValidate();
        }
        fetchAddressList();
        visible.value = true;
    };

    const handleManageAddress = () => {
        // Navigate to address management page if exists
        router.push('/mallLogistics/address');
    };

    const handleSubmit = async () => {
        if (!formRef.value) return;

        await formRef.value.validate((valid) => {
            if (valid) {
                submitData();
            }
        });
    };

    const submitData = () => {
        const params = {
            refundOrderId: currentRefundOrderId.value,
            refundAddressId: form.refundAddressId,
            description: form.description
        };

        loading.value = true;
        request
            .post('/shop/shopOrder/refund/auditAgree', params)
            .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({
        open
    });
</script>

<style scoped>
    :deep(.refund-address-popper) {
        padding: 0;
    }
    :deep(.el-textarea__inner) {
        background-color: #f9fafb;
    }
</style>
