<template>
    <ele-modal
        :width="600"
        v-model="visible"
        title="与买家协商"
        :body-style="{ padding: '20px 40px' }"
    >
        <div
            class="mb-4 p-3 bg-emerald-50 text-emerald-600 rounded text-sm flex items-start"
        >
            <el-icon class="mr-2 mt-0.5 text-emerald-500"
                ><WarningFilled
            /></el-icon>
            <span
                >提示：与买家协商退货退款，买家接受后将自动同意退款申请，请选择退货地址</span
            >
        </div>

        <el-form
            :model="form"
            :rules="rules"
            ref="formRef"
            label-width="100px"
            label-position="right"
        >
            <el-form-item label="退款原因：">
                <span class="text-gray-700">{{ refundReason }}</span>
            </el-form-item>

            <el-form-item label="退款金额：">
                <div v-if="!isEditingMoney" class="flex items-center">
                    <span class="text-gray-700 mr-2"
                        >￥{{ form.disposeMoney }}</span
                    >
                    <el-button link type="success" @click="startEditMoney">
                        <el-icon class="mr-1"><Edit /></el-icon>修改
                    </el-button>
                </div>
                <div v-else class="flex items-center">
                    <el-input-number
                        v-model="form.disposeMoney"
                        :min="0.01"
                        :max="maxRefundAmount"
                        :precision="2"
                        :step="0.01"
                        controls-position="right"
                        style="width: 150px"
                        class="mr-2"
                    />
                    <el-button
                        link
                        type="primary"
                        @click="isEditingMoney = false"
                        >确认</el-button
                    >
                </div>
            </el-form-item>

            <el-form-item label="退货地址：" prop="receiverAddressId">
                <el-popover
                    v-model:visible="addressPickerVisible"
                    trigger="click"
                    placement="bottom-start"
                    :width="520"
                    popper-class="refund-address-popper"
                >
                    <template #reference>
                        <div
                            class="w-full flex items-start flex-col cursor-pointer"
                        >
                            <div
                                v-if="selectedAddress"
                                class="text-gray-700 mb-2 leading-relaxed"
                            >
                                {{ selectedAddress.name }}，{{
                                    selectedAddress.mobile
                                }}，{{ selectedAddress.address }}
                            </div>
                            <div v-else class="text-gray-400 mb-2">
                                请选择退货地址
                            </div>
                            <el-button link type="success">
                                <el-icon class="mr-1"><Switch /></el-icon
                                >切换地址
                            </el-button>
                        </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.receiverAddressId) ===
                                    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>

        <template #footer>
            <div class="flex justify-center gap-4">
                <el-button
                    type="success"
                    :loading="loading"
                    @click="handleSubmit"
                    >提交</el-button
                >
                <el-button @click="visible = false">取消</el-button>
            </div>
        </template>
    </ele-modal>
</template>

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

    const visible = ref(false);
    const loading = ref(false);
    const addressLoading = ref(false);
    const addressPickerVisible = ref(false);
    const formRef = ref(null);
    const currentRefundOrderId = ref('');
    const refundReason = ref('');
    const maxRefundAmount = ref(0);
    const isEditingMoney = ref(false);

    const addressList = ref([]);
    const selectedAddress = computed(() => {
        const id = String(form.receiverAddressId || '');
        if (!id) return null;
        return addressList.value.find((a) => String(a.id) === id) || null;
    });

    const form = reactive({
        receiverAddressId: '',
        disposeMoney: 0
    });

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

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

    const fetchAddressList = () => {
        addressLoading.value = true;
        request
            .get('/shop/shopAddress/getRefundAddressList')
            .then((res) => {
                if (res.data.code === 200) {
                    addressList.value = res.data.data || [];
                    if (
                        addressList.value.length > 0 &&
                        !form.receiverAddressId
                    ) {
                        const defaultAddr = addressList.value.find(
                            (a) => Number(a.defaultReturnFlag) === 1
                        );
                        form.receiverAddressId = 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.receiverAddressId = item.id;
        addressPickerVisible.value = false;
        formRef.value?.validateField?.('receiverAddressId');
    };

    const open = (data) => {
        currentRefundOrderId.value = data.refundOrderId;
        refundReason.value = data.refundReason;
        maxRefundAmount.value = Number(data.refundMoney) || 0;

        form.disposeMoney = maxRefundAmount.value;
        form.receiverAddressId = '';
        isEditingMoney.value = false;
        addressPickerVisible.value = false;

        if (formRef.value) {
            formRef.value.clearValidate();
        }
        fetchAddressList();
        visible.value = true;
    };

    const startEditMoney = () => {
        isEditingMoney.value = true;
    };

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

        await formRef.value.validate((valid) => {
            if (valid) {
                if (
                    form.disposeMoney === undefined ||
                    form.disposeMoney === null
                ) {
                    EleMessage.warning('请输入退款金额');
                    return;
                }
                submitData();
            }
        });
    };

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

        loading.value = true;
        request
            .post('/shop/shopOrder/refund/disposeRefundType', 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;
    }
</style>
