<template>
    <div class="vpn-address-pool">
        <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="addNewPool">新增地址池</el-button>
                        </div>
                    </template>
                    <div class="pool-list">
                        <div 
                            v-for="pool in poolList" 
                            :key="pool.pool_name"
                            class="pool-item"
                            :class="{ active: selectedPool?.pool_name === pool.pool_name }"
                            @click="selectPool(pool)"
                        >
                            <div class="pool-info">
                                <div class="pool-name">{{ pool.pool_name }}</div>
                                <div class="pool-range">
                                    IPv4: {{ pool.config.ipv4_address_pool.start_ip }} - {{ pool.config.ipv4_address_pool.end_ip }}/{{ pool.config.ipv4_address_pool.prefix }}
                                </div>
                                <div class="pool-range">
                                    IPv6: {{ pool.config.ipv6_address_pool.start_ip }} - {{ pool.config.ipv6_address_pool.end_ip }}/{{ pool.config.ipv6_address_pool.prefix }}
                                </div>
                            </div>
                            <div class="pool-actions">
                                <el-button type="danger" size="small" text @click.stop="deletePool(pool.pool_name)">
                                    删除
                                </el-button>
                            </div>
                        </div>
                        <el-empty v-if="poolList.length === 0" description="暂无地址池配置" />
                    </div>
                </el-card>
            </el-col>

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

                        <el-divider content-position="left">IPv4地址池配置</el-divider>
                        
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="起始IP">
                                    <el-input v-model="selectedPool.config.ipv4_address_pool.start_ip" placeholder="请输入起始IPv4地址" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="结束IP">
                                    <el-input v-model="selectedPool.config.ipv4_address_pool.end_ip" placeholder="请输入结束IPv4地址" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="子网前缀">
                                    <el-input-number v-model="selectedPool.config.ipv4_address_pool.prefix" :min="1" :max="32" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="DNS服务器">
                                    <el-select 
                                        v-model="selectedPool.config.ipv4_address_pool.dns_ip" 
                                        placeholder="请选择DNS服务器"
                                        multiple
                                        filterable
                                        allow-create
                                        default-first-option
                                    >
                                        <el-option
                                            v-for="dns in dnsOptions"
                                            :key="dns.value"
                                            :label="dns.label"
                                            :value="dns.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

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

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="起始IP">
                                    <el-input v-model="selectedPool.config.ipv6_address_pool.start_ip" placeholder="请输入起始IPv6地址" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="结束IP">
                                    <el-input v-model="selectedPool.config.ipv6_address_pool.end_ip" placeholder="请输入结束IPv6地址" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="子网前缀">
                                    <el-input-number v-model="selectedPool.config.ipv6_address_pool.prefix" :min="1" :max="128" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="DNS服务器">
                                    <el-select 
                                        v-model="selectedPool.config.ipv6_address_pool.dns_ip" 
                                        placeholder="请选择DNS服务器"
                                        multiple
                                        filterable
                                        allow-create
                                        default-first-option
                                    >
                                        <el-option
                                            v-for="dns in dnsOptions"
                                            :key="dns.value"
                                            :label="dns.label"
                                            :value="dns.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-divider content-position="left">IP绑定配置</el-divider>

                        <el-form-item label="用户IP绑定">
                            <div class="ip-bind-section">
                                <div 
                                    v-for="(bind, index) in selectedPool.config.ipv4_address_pool.ip_bind" 
                                    :key="index"
                                    class="ip-bind-item"
                                >
                                    <el-select v-model="bind.user_id" placeholder="选择用户" filterable>
                                        <el-option
                                            v-for="user in userOptions"
                                            :key="user.value"
                                            :label="user.label"
                                            :value="user.value"
                                        />
                                    </el-select>
                                    <el-input v-model="bind.bind_ip" placeholder="绑定IP地址" style="margin-left: 10px;" />
                                    <el-button type="danger" size="small" text @click="removeIPBind('ipv4', index)" style="margin-left: 10px;">
                                        删除
                                    </el-button>
                                </div>
                                <el-button type="primary" size="small" text @click="addIPBind('ipv4')">
                                    添加IPv4绑定
                                </el-button>
                            </div>
                        </el-form-item>

                        <el-form-item label="IPv6用户绑定">
                            <div class="ip-bind-section">
                                <div 
                                    v-for="(bind, index) in selectedPool.config.ipv6_address_pool.ip_bind" 
                                    :key="index"
                                    class="ip-bind-item"
                                >
                                    <el-select v-model="bind.user_id" placeholder="选择用户" filterable>
                                        <el-option
                                            v-for="user in userOptions"
                                            :key="user.value"
                                            :label="user.label"
                                            :value="user.value"
                                        />
                                    </el-select>
                                    <el-input v-model="bind.bind_ip" placeholder="绑定IPv6地址" style="margin-left: 10px;" />
                                    <el-button type="danger" size="small" text @click="removeIPBind('ipv6', index)" style="margin-left: 10px;">
                                        删除
                                    </el-button>
                                </div>
                                <el-button type="primary" size="small" text @click="addIPBind('ipv6')">
                                    添加IPv6绑定
                                </el-button>
                            </div>
                        </el-form-item>
                    </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 { getAllDefaultUsers } from '@/api/user';
import { GetVPNAddressPoolHandler, SetVPNAddressPoolHandler, DeleteVPNAddressPoolHandler } 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 StringValue {
    value: string;
}

interface UserIDBindIP {
    user_id: number;
    bind_ip: string;
}

interface AddressPool {
    start_ip: string;
    end_ip: string;
    prefix: number;
    dns_ip: StringValue[] | string[];
    ip_bind: UserIDBindIP[];
}

interface AddressPoolConfig {
    ipv4_address_pool: AddressPool;
    ipv6_address_pool: AddressPool;
}

interface AddressPoolRequest {
    pool_name: string;
    config: AddressPoolConfig;
}

const poolList = ref<AddressPoolRequest[]>([]);
const selectedPool = ref<AddressPoolRequest | null>(null);
const userOptions = ref<Array<{value: number, label: string}>>([]);
const dnsOptions = ref<Array<{value: string, label: string}>>([
    { value: '8.8.8.8', label: '8.8.8.8 (Google DNS)' },
    { value: '8.8.4.4', label: '8.8.4.4 (Google DNS)' },
    { value: '1.1.1.1', label: '1.1.1.1 (Cloudflare DNS)' },
    { value: '1.0.0.1', label: '1.0.0.1 (Cloudflare DNS)' },
    { value: '208.67.222.222', label: '208.67.222.222 (OpenDNS)' },
    { value: '2001:4860:4860::8888', label: '2001:4860:4860::8888 (Google IPv6)' },
    { value: '2001:4860:4860::8844', label: '2001:4860:4860::8844 (Google IPv6)' },
    { value: '2606:4700:4700::1111', label: '2606:4700:4700::1111 (Cloudflare IPv6)' },
    { value: '2606:4700:4700::1001', label: '2606:4700:4700::1001 (Cloudflare IPv6)' }
]);

// 创建默认的地址池配置
const createDefaultPool = (): AddressPoolRequest => {
    return {
        pool_name: '',
        config: {
            ipv4_address_pool: {
                start_ip: '',
                end_ip: '',
                prefix: 24,
                dns_ip: [],
                ip_bind: []
            },
            ipv6_address_pool: {
                start_ip: '',
                end_ip: '',
                prefix: 64,
                dns_ip: [],
                ip_bind: []
            }
        }
    };
};

// 获取地址池列表
const getPools = async () => {
    try {
        const response = await GetVPNAddressPoolHandler();
        poolList.value = response.data;
    } catch (error) {
        ElMessage.error('获取地址池列表失败');
        console.error(error);
    }
};

// 获取用户列表
const getUsers = async () => {
    try {
        const response = await getAllDefaultUsers();
        if (response['code'] !== 0) {
            console.error('获取用户失败:', response["message"]);
            return;
        }
        userOptions.value = response.data
            .filter((user: any) => user.type === 0)
            .map((user: any) => ({
                value: user.id,
                label: user.name
            }));
    } catch (error) {
        console.error('获取用户失败:', error);
    }
};

// 选择地址池
const selectPool = (pool: AddressPoolRequest) => {
    selectedPool.value = JSON.parse(JSON.stringify(pool)); // 深拷贝避免直接修改
    let dns_ip = selectedPool.value.config.ipv4_address_pool.dns_ip.map(item => item.value);
    let dns_ip_v6 = selectedPool.value.config.ipv6_address_pool.dns_ip.map(item => item.value);
    selectedPool.value.config.ipv4_address_pool.dns_ip = dns_ip;
    selectedPool.value.config.ipv6_address_pool.dns_ip = dns_ip_v6;
};

// 新增地址池
const addNewPool = () => {
    selectedPool.value = createDefaultPool();
};

// 删除地址池
const deletePool = async (poolName: string) => {
    try {
        await ElMessageBox.confirm('确定要删除此地址池吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        
        await DeleteVPNAddressPoolHandler({ pool_name: poolName });
        
        const index = poolList.value.findIndex(pool => pool.pool_name === poolName);
        if (index > -1) {
            poolList.value.splice(index, 1);
            if (selectedPool.value?.pool_name === poolName) {
                selectedPool.value = null;
            }
            ElMessage.success('删除成功');
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
            console.error(error);
        }
    }
};

// 添加IP绑定
const addIPBind = (type: 'ipv4' | 'ipv6') => {
    if (!selectedPool.value) return;
    
    const bind: UserIDBindIP = {
        user_id: 0,
        bind_ip: ''
    };
    if (selectedPool.value.config.ipv4_address_pool.ip_bind == null){
        selectedPool.value.config.ipv4_address_pool.ip_bind = [];
    }
    if (selectedPool.value.config.ipv6_address_pool.ip_bind == null){
        selectedPool.value.config.ipv6_address_pool.ip_bind = [];
    }
    
    if (type === 'ipv4') {
        selectedPool.value.config.ipv4_address_pool.ip_bind.push(bind);
    } else {
        selectedPool.value.config.ipv6_address_pool.ip_bind.push(bind);
    }
};

// 删除IP绑定
const removeIPBind = (type: 'ipv4' | 'ipv6', index: number) => {
    if (!selectedPool.value) return;
    
    if (type === 'ipv4') {
        selectedPool.value.config.ipv4_address_pool.ip_bind.splice(index, 1);
    } else {
        selectedPool.value.config.ipv6_address_pool.ip_bind.splice(index, 1);
    }
};

// 保存配置
const saveConfig = async () => {
    if (!selectedPool.value) return;
    
    if (!selectedPool.value.pool_name.trim()) {
        ElMessage.error('请输入地址池名称');
        return;
    }
    
    if (!selectedPool.value.config.ipv4_address_pool.start_ip || !selectedPool.value.config.ipv4_address_pool.end_ip) {
        ElMessage.error('请输入完整的IPv4地址范围');
        return;
    }
    
    if (!selectedPool.value.config.ipv6_address_pool.start_ip || !selectedPool.value.config.ipv6_address_pool.end_ip) {
        ElMessage.error('请输入完整的IPv6地址范围');
        return;
    }
    
    // 验证IPv4用户绑定
    for (let i = 0; i < selectedPool.value.config.ipv4_address_pool.ip_bind.length; i++) {
        const bind = selectedPool.value.config.ipv4_address_pool.ip_bind[i];
        if (!bind.user_id || bind.user_id === 0) {
            ElMessage.error(`IPv4绑定第${i + 1}行：请选择用户`);
            return;
        }
        if (!bind.bind_ip || bind.bind_ip.trim() === '') {
            ElMessage.error(`IPv4绑定第${i + 1}行：请输入正确的IP地址`);
            return;
        }
        // 验证IPv4地址格式
        if (!isValidIPv4(bind.bind_ip.trim())) {
            ElMessage.error(`IPv4绑定第${i + 1}行：IP地址格式不正确`);
            return;
        }
    }
    
    // 验证IPv6用户绑定
    for (let i = 0; i < selectedPool.value.config.ipv6_address_pool.ip_bind.length; i++) {
        const bind = selectedPool.value.config.ipv6_address_pool.ip_bind[i];
        if (!bind.user_id || bind.user_id === 0) {
            ElMessage.error(`IPv6绑定第${i + 1}行：请选择用户`);
            return;
        }
        if (!bind.bind_ip || bind.bind_ip.trim() === '') {
            ElMessage.error(`IPv6绑定第${i + 1}行：请输入正确的IPv6地址`);
            return;
        }
        // 验证IPv6地址格式
        if (!isValidIPv6(bind.bind_ip.trim())) {
            ElMessage.error(`IPv6绑定第${i + 1}行：IPv6地址格式不正确`);
            return;
        }
    }
    
    let dns_ip = [];
    for(let value_ of selectedPool.value.config.ipv4_address_pool.dns_ip){
        dns_ip.push({value:value_})
    }
    let dns_ip_v6 = [];
    for(let value_ of selectedPool.value.config.ipv6_address_pool.dns_ip){
        dns_ip_v6.push({value:value_})
    }
    selectedPool.value.config.ipv6_address_pool.dns_ip = dns_ip_v6;
    selectedPool.value.config.ipv4_address_pool.dns_ip = dns_ip;

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

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

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

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

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

.pool-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;
}

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

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

.pool-info {
    flex: 1;
}

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

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

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

.ip-bind-section {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background-color: #fafafa;
}

.ip-bind-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.ip-bind-item:last-child {
    margin-bottom: 0;
}

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

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