<template>
    <ele-modal
        :width="1000"
        v-model="visible"
        :title="title"
        :body-style="{ paddingBottom: '20px' }"
    >
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
            <el-form-item label="模板名称" prop="templeteName">
                <el-input
                    v-model="form.templeteName"
                    placeholder="请输入模板名称"
                />
            </el-form-item>

            <!-- Table for Rules -->
            <div class="px-4">
                <el-table
                    :data="form.shippingTempleteDetailList"
                    border
                    style="width: 100%"
                >
                    <el-table-column label="选择地区" min-width="250">
                        <template #default="{ row, $index }">
                            <div class="flex items-center justify-between">
                                <span
                                    v-if="
                                        !row.shippingProvinceList ||
                                        row.shippingProvinceList.length === 0
                                    "
                                    class="text-gray-400"
                                    >未选择地区</span
                                >
                                <span
                                    v-else
                                    class="truncate pr-2"
                                    :title="
                                        row.shippingProvinceList
                                            .map((p) => p.provinceName)
                                            .join('、')
                                    "
                                >
                                    {{
                                        row.shippingProvinceList
                                            .map((p) => p.provinceName)
                                            .join('、')
                                    }}
                                </span>
                                <el-button
                                    type="primary"
                                    link
                                    @click="openAreaSelector($index)"
                                    >编辑</el-button
                                >
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="设置包邮条件" width="220">
                        <template #default="{ row }">
                            <div class="flex items-center">
                                <span class="mr-2">满</span>
                                <el-input-number
                                    v-model="row.minMoney"
                                    :min="0"
                                    :precision="2"
                                    :controls="false"
                                    style="width: 80px"
                                />
                                <span class="ml-2">元包邮</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="基础运费" width="150">
                        <template #default="{ row }">
                            <el-input-number
                                v-model="row.shippingMoney"
                                :min="0"
                                :precision="2"
                                :controls="false"
                                style="width: 100%"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                        <template #default="{ $index }">
                            <el-button
                                type="danger"
                                link
                                @click="removeRule($index)"
                                :disabled="
                                    $index === 0 &&
                                    form.shippingTempleteDetailList.length === 1
                                "
                            >
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="mt-2">
                    <el-button type="primary" link :icon="Plus" @click="addRule"
                        >添加规则</el-button
                    >
                </div>
            </div>
        </el-form>

        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="submit">确定</el-button>
        </template>

        <AreaSelector
            v-model="areaSelectorVisible"
            ref="areaSelectorRef"
            @confirm="handleAreaConfirm"
        />
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, nextTick, defineEmits, defineExpose } from 'vue';
    import { Delete, Plus } from '@element-plus/icons-vue';
    import { ElMessage } from 'element-plus';
    import request from '@/utils/request';
    import AreaSelector from './area-selector.vue';

    const visible = defineModel({ type: Boolean });
    const emit = defineEmits(['success']);

    const title = ref('新增运费模板');
    const formRef = ref(null);
    const areaSelectorRef = ref(null);
    const areaSelectorVisible = ref(false);
    const currentRuleIndex = ref(-1);

    const form = reactive({
        id: undefined,
        templeteName: '',
        shippingTempleteDetailList: [
            {
                tempKey: '',
                shippingProvinceList: [],
                minMoney: 0,
                shippingMoney: 0
            }
        ]
    });

    const rules = {
        templeteName: [
            { required: true, message: '请输入模板名称', trigger: 'blur' }
        ]
    };

    const generateTempKey = () => {
        return (
            'tk_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        );
    };

    const handleOpen = (row) => {
        visible.value = true;
        nextTick(() => {
            formRef.value?.resetFields();
            if (row && row.id) {
                title.value = '编辑运费模板';
                form.id = row.id;
                form.templeteName = row.templeteName;
                // Map templeteList to shippingTempleteDetailList
                form.shippingTempleteDetailList = (row.templeteList || []).map(
                    (item) => ({
                        tempKey: item.tempKey || generateTempKey(),
                        minMoney: item.minMoney,
                        shippingMoney: item.shippingMoney,
                        shippingProvinceList: item.shippingProvinceList || []
                    })
                );
            } else {
                title.value = '新增运费模板';
                form.id = undefined;
                form.templeteName = '';
                form.shippingTempleteDetailList = [
                    {
                        tempKey: generateTempKey(),
                        shippingProvinceList: [],
                        minMoney: 0,
                        shippingMoney: 0
                    }
                ];
            }
        });
    };

    const addRule = () => {
        form.shippingTempleteDetailList.push({
            tempKey: generateTempKey(),
            shippingProvinceList: [],
            minMoney: 0,
            shippingMoney: 0
        });
    };

    const removeRule = (index) => {
        form.shippingTempleteDetailList.splice(index, 1);
    };

    const openAreaSelector = (index) => {
        currentRuleIndex.value = index;
        areaSelectorVisible.value = true;
        nextTick(() => {
            areaSelectorRef.value?.handleOpen(
                form.shippingTempleteDetailList[index].shippingProvinceList
            );
        });
    };

    const handleAreaConfirm = (selectedRegions) => {
        if (currentRuleIndex.value !== -1) {
            form.shippingTempleteDetailList[
                currentRuleIndex.value
            ].shippingProvinceList = selectedRegions;
        }
    };

    const submit = () => {
        formRef.value.validate(async (valid) => {
            if (valid) {
                // Validate rules
                for (
                    let i = 0;
                    i < form.shippingTempleteDetailList.length;
                    i++
                ) {
                    const rule = form.shippingTempleteDetailList[i];
                    if (
                        !rule.shippingProvinceList ||
                        rule.shippingProvinceList.length === 0
                    ) {
                        ElMessage.warning(`第 ${i + 1} 行未选择地区`);
                        return;
                    }
                    if (
                        rule.shippingMoney === undefined ||
                        rule.shippingMoney === null
                    ) {
                        ElMessage.warning(`第 ${i + 1} 行未设置基础运费`);
                        return;
                    }
                }

                try {
                    const res = await request.post(
                        '/shipping/templete/add',
                        form
                    );
                    if (res.data.code === 200) {
                        ElMessage.success('保存成功');
                        emit('success');
                        visible.value = false;
                    } else {
                        ElMessage.error(res.data.msg || '保存失败');
                    }
                } catch (error) {
                    console.error(error);
                    ElMessage.error('保存失败');
                }
            }
        });
    };

    defineExpose({
        handleOpen
    });
</script>
