<template>
    <ele-modal
        :width="600"
        v-model="visible"
        title="新增额外包裹"
        @closed="handleClosed"
        :body-style="{ padding: '20px' }"
    >
        <el-form ref="formRef" :model="form" label-width="110px">
            <el-form-item label="订单编号">
                <el-input :model-value="orderData.orderId" disabled />
            </el-form-item>
            <el-form-item label="发货运单号">
                <span class="text-gray-700">{{
                    orderData.waybillCode || '-'
                }}</span>
            </el-form-item>
            <el-form-item
                label="额外包裹类型"
                prop="type"
                :rules="[{ required: true, message: '请选择额外包裹类型' }]"
            >
                <el-radio-group v-model="form.type">
                    <el-radio :label="1">补寄</el-radio>
                    <el-radio :label="2">分包发货</el-radio>
                </el-radio-group>
            </el-form-item>

            <div class="package-list-container bg-gray-50 p-4 rounded mt-4">
                <div
                    v-for="(pkg, index) in form.expressList"
                    :key="index"
                    class="package-item relative mb-4 p-3 border border-gray-200 bg-white rounded"
                >
                    <el-button
                        v-if="form.expressList.length > 1"
                        type="danger"
                        link
                        class="absolute right-2 top-2 z-10"
                        @click="removePackage(index)"
                        >删除</el-button
                    >

                    <el-form-item
                        :label="`额外运单号`"
                        :prop="`expressList.${index}.waybillCode`"
                        :rules="[
                            { required: true, message: '请输入额外运单号' }
                        ]"
                        class="mb-4 mt-2"
                    >
                        <el-input
                            v-model="pkg.waybillCode"
                            placeholder="请输入物流单号"
                            clearable
                        />
                    </el-form-item>

                    <el-form-item
                        :label="`快递公司`"
                        :prop="`expressList.${index}.expressName`"
                        :rules="[{ required: true, message: '请选择快递公司' }]"
                        class="mb-0"
                    >
                        <dict-data
                            code="shop_order_express_name"
                            v-model="pkg.expressName"
                            type="select"
                            placeholder="请选择快递公司"
                            class="w-full"
                        />
                    </el-form-item>
                </div>

                <div class="text-right mt-2">
                    <el-button type="success" plain @click="addPackage"
                        >添加多个包裹</el-button
                    >
                </div>
            </div>
        </el-form>
        <template #footer>
            <div class="flex justify-between items-center w-full">
                <div class="text-green-500 text-sm"
                    >额外运单号添加后不支持修改，请仔细核对</div
                >
                <div>
                    <el-button @click="visible = false">取消</el-button>
                    <el-button
                        type="primary"
                        @click="handleSubmit"
                        :loading="loading"
                        >确认</el-button
                    >
                </div>
            </div>
        </template>
    </ele-modal>
</template>

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

    const visible = defineModel({ type: Boolean });
    const formRef = ref(null);
    const loading = ref(false);
    const orderData = ref({});

    const form = reactive({
        type: 1,
        expressList: [{ waybillCode: '', expressName: '' }]
    });

    const handleOpen = (order) => {
        orderData.value = order || {};
        visible.value = true;
    };

    const handleClosed = () => {
        if (formRef.value) {
            formRef.value.resetFields();
        }
        form.type = 1;
        form.expressList = [{ waybillCode: '', expressName: '' }];
        orderData.value = {};
    };

    const addPackage = () => {
        form.expressList.push({ waybillCode: '', expressName: '' });
    };

    const removePackage = (index) => {
        form.expressList.splice(index, 1);
    };

    const handleSubmit = () => {
        formRef.value.validate((valid) => {
            if (valid) {
                loading.value = true;
                request
                    .post('/shop/shopOrder/addExpress', {
                        orderId: orderData.value.orderId,
                        type: form.type,
                        expressList: form.expressList.map((pkg) => ({
                            expressName: pkg.expressName,
                            waybillCode: pkg.waybillCode
                        }))
                    })
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success('添加成功');
                            visible.value = false;
                        } else {
                            EleMessage.error(res.data.msg || '添加失败');
                        }
                    })
                    .catch((e) => {
                        console.error(e);
                        EleMessage.error('网络错误');
                    })
                    .finally(() => {
                        loading.value = false;
                    });
            }
        });
    };

    defineExpose({
        handleOpen
    });
</script>

<style scoped>
    .bg-gray-50 {
        background-color: #f9fafc;
    }
    .border-gray-200 {
        border-color: #ebeef5;
    }
    .text-gray-700 {
        color: #606266;
    }
    .text-green-500 {
        color: #67c23a;
    }
    .w-full {
        width: 100%;
    }
</style>
