<template>
    <div class="vpn-tunnel">
        <el-row :gutter="20">
            <!-- 左侧隧道列表 -->
            <el-col :span="8">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>隧道列表</span>
                            <el-button type="primary" @click="addNewTunnel">新增隧道</el-button>
                        </div>
                    </template>
                    <div class="tunnel-list">
                        <div 
                            v-for="tunnel in tunnelList" 
                            :key="tunnel.tunnel_name"
                            class="tunnel-item"
                            :class="{ active: selectedTunnel?.tunnel_name === tunnel.tunnel_name }"
                            @click="selectTunnel(tunnel)"
                        >
                            <div class="tunnel-info">
                                <div class="tunnel-name">{{ tunnel.tunnel_name }}</div>
                                <div class="tunnel-ips">
                                    IPv4: {{ tunnel.config.auto_ipv4 ? '自动' : tunnel.config.ipv4_address }}
                                </div>
                                <div class="tunnel-ips">
                                    IPv6: {{ tunnel.config.auto_ipv6 ? '自动' : tunnel.config.ipv6_address }}
                                </div>
                                <div class="tunnel-limits">
                                    上行: {{ tunnel.config.upload_limit }} Kbps | 下行: {{ tunnel.config.download_limit }} Kbps
                                </div>
                            </div>
                            <div class="tunnel-actions">
                                <el-button type="danger" size="small" text @click.stop="deleteTunnel(tunnel.tunnel_name)">
                                    删除
                                </el-button>
                            </div>
                        </div>
                        <el-empty v-if="tunnelList.length === 0" description="暂无隧道配置" />
                    </div>
                </el-card>
            </el-col>

            <!-- 右侧编辑表单 -->
            <el-col :span="16">
                <el-card shadow="hover" v-if="selectedTunnel">
                    <template #header>
                        <div class="card-header">
                            <span>编辑隧道配置</span>
                            <el-button type="success" @click="saveConfig">保存配置</el-button>
                        </div>
                    </template>
                    <el-form :model="selectedTunnel" label-width="120px" size="default">
                        <el-form-item label="隧道名称">
                            <el-input v-model="selectedTunnel.tunnel_name" placeholder="请输入隧道名称" />
                        </el-form-item>

                        <el-divider content-position="left">IPv4配置</el-divider>
                        
                        <el-form-item label="自动分配IPv4">
                            <el-switch v-model="selectedTunnel.config.auto_ipv4" />
                        </el-form-item>

                        <el-form-item label="IPv4地址" v-if="!selectedTunnel.config.auto_ipv4">
                            <el-input v-model="selectedTunnel.config.ipv4_address" placeholder="请输入IPv4地址" />
                        </el-form-item>

                        <el-form-item label="IPv4 MTU">
                            <el-input-number v-model="selectedTunnel.config.ipv4_mtu" :min="68" :max="9000" />
                        </el-form-item>

                        <el-divider content-position="left">IPv6配置</el-divider>

                        <el-form-item label="自动分配IPv6">
                            <el-switch v-model="selectedTunnel.config.auto_ipv6" />
                        </el-form-item>

                        <el-form-item label="IPv6地址" v-if="!selectedTunnel.config.auto_ipv6">
                            <el-input v-model="selectedTunnel.config.ipv6_address" placeholder="请输入IPv6地址" />
                        </el-form-item>

                        <el-form-item label="IPv6 MTU">
                            <el-input-number v-model="selectedTunnel.config.ipv6_mtu" :min="1280" :max="9000" />
                        </el-form-item>

                        <el-divider content-position="left">带宽限制</el-divider>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="上行限制(Kbps)">
                                    <el-input-number 
                                        v-model="selectedTunnel.config.upload_limit" 
                                        :min="0" 
                                        :max="100000" 
                                        :step="1"
                                        placeholder="0表示无限制"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="下行限制(Kbps)">
                                    <el-input-number 
                                        v-model="selectedTunnel.config.download_limit" 
                                        :min="0" 
                                        :max="100000" 
                                        :step="1"
                                        placeholder="0表示无限制"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>

                <el-card shadow="hover" v-else>
                    <el-empty description="请选择要编辑的隧道" />
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { GetVPNTunnelConfigHandler, SetVPNTunnelHandler, DeleteVPNTunnelHandler } from '@/api/vpn';

// IPv4地址验证
const isValidIPv4 = (ip: string): boolean => {
    const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    return ipv4Regex.test(ip);
};

// IPv6地址验证
const isValidIPv6 = (ip: string): boolean => {
    // 简化的IPv6验证，支持标准IPv6格式
    const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,7}:$|^(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}$|^(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}$|^(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}$|^(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}$|^[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})$|^:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)$/;
    return ipv6Regex.test(ip);
};

interface TunnelConfig {
    tunnel_name: string;
    auto_ipv4: boolean;
    auto_ipv6: boolean;
    ipv4_address: string;
    ipv6_address: string;
    ipv4_mtu: number;
    ipv6_mtu: number;
    upload_limit: number;
    download_limit: number;
}

interface TunnelRequestAndResponse {
    tunnel_name: string;
    config: TunnelConfig;
}

const tunnelList = ref<TunnelRequestAndResponse[]>([]);
const selectedTunnel = ref<TunnelRequestAndResponse | null>(null);

// 创建默认的隧道配置
const createDefaultTunnel = (): TunnelRequestAndResponse => {
    return {
        tunnel_name: '',
        config: {
            tunnel_name: '',
            auto_ipv4: true,
            auto_ipv6: true,
            ipv4_address: '',
            ipv6_address: '',
            ipv4_mtu: 1420,
            ipv6_mtu: 1420,
            upload_limit: 0,
            download_limit: 0
        }
    };
};

// 获取隧道列表
const getTunnels = async () => {
    try {
        const response = await GetVPNTunnelConfigHandler();
        tunnelList.value = response.data;
    } catch (error) {
        ElMessage.error('获取隧道列表失败');
        console.error(error);
    }
};

// 选择隧道
const selectTunnel = (tunnel: TunnelRequestAndResponse) => {
    selectedTunnel.value = JSON.parse(JSON.stringify(tunnel)); // 深拷贝避免直接修改
    selectedTunnel.value.config.tunnel_name = selectedTunnel.value.tunnel_name;
};

// 新增隧道
const addNewTunnel = () => {
    selectedTunnel.value = createDefaultTunnel();
};

// 删除隧道
const deleteTunnel = async (tunnelName: string) => {
    try {
        await ElMessageBox.confirm('确定要删除此隧道吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        
        await DeleteVPNTunnelHandler({ tunnel_name: tunnelName });
        
        const index = tunnelList.value.findIndex(tunnel => tunnel.tunnel_name === tunnelName);
        if (index > -1) {
            tunnelList.value.splice(index, 1);
            if (selectedTunnel.value?.tunnel_name === tunnelName) {
                selectedTunnel.value = null;
            }
            ElMessage.success('删除成功');
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
            console.error(error);
        }
    }
};

// 保存配置
const saveConfig = async () => {
    if (!selectedTunnel.value) return;
    
    if (!selectedTunnel.value.tunnel_name.trim()) {
        ElMessage.error('请输入隧道名称');
        return;
    }
    
    // 如果不是自动分配，需要验证IP地址格式
    if (!selectedTunnel.value.config.auto_ipv4) {
        if (!selectedTunnel.value.config.ipv4_address.trim()) {
            ElMessage.error('请输入IPv4地址');
            return;
        }
        if (!isValidIPv4(selectedTunnel.value.config.ipv4_address.trim())) {
            ElMessage.error('IPv4地址格式不正确');
            return;
        }
    }
    
    if (!selectedTunnel.value.config.auto_ipv6) {
        if (!selectedTunnel.value.config.ipv6_address.trim()) {
            ElMessage.error('请输入IPv6地址');
            return;
        }
        if (!isValidIPv6(selectedTunnel.value.config.ipv6_address.trim())) {
            ElMessage.error('IPv6地址格式不正确');
            return;
        }
    }
    
    // 设置tunnel_name到config中
    selectedTunnel.value.config.tunnel_name = selectedTunnel.value.tunnel_name;

    try {
        const response = await SetVPNTunnelHandler(selectedTunnel.value);
        if (response["code"] !== 0) {
            ElMessage.error(response["message"]);
            return;
        }
        ElMessage.success('配置保存成功');
        getTunnels(); // 重新获取最新数据
    } catch (error) {
        ElMessage.error('保存配置失败');
        console.error(error);
    }
};

// 组件挂载时获取数据
onMounted(() => {
    getTunnels();
});
</script>

<style scoped>
.vpn-tunnel {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
}

.tunnel-list {
    max-height: 600px;
    overflow-y: auto;
}

.tunnel-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    margin-bottom: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.tunnel-item:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
}

.tunnel-item.active {
    background-color: #ecf5ff;
    border-color: #409eff;
}

.tunnel-info {
    flex: 1;
}

.tunnel-name {
    font-weight: bold;
    margin-bottom: 4px;
}

.tunnel-ips {
    font-size: 12px;
    color: #909399;
    margin-bottom: 2px;
}

.tunnel-limits {
    font-size: 12px;
    color: #606266;
    margin-top: 4px;
}

.tunnel-actions {
    margin-left: 10px;
}

.el-form {
    padding: 20px 0;
}

.el-divider {
    margin: 20px 0;
}
</style>