<template>
    <div class="mt-1.5">
        <el-row :gutter="20" v-for="(port, index) in exposedPorts" :key="index">
            <el-col :span="6">
                <el-form-item :prop="`exposedPorts.${index}.hostPort`" :rules="rules.port">
                    <el-input v-model.number="port.hostPort" :placeholder="$t('runtime.externalPort')" />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item :prop="`exposedPorts.${index}.containerPort`" :rules="rules.port">
                    <el-input v-model.number="port.containerPort" :placeholder="$t('runtime.appPort')" />
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item>
                    <el-select v-model="port.protocol" :placeholder="$t('commons.table.protocol')">
                        <el-option label="tcp" value="tcp" />
                        <el-option label="udp" value="udp" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-text>{{ $t('app.allowPort') }}</el-text>
                <el-switch
                    class="ml-1"
                    :model-value="port.hostIP === ''"
                    @update:model-value="handleSwitchChange($event, index)"
                />
            </el-col>
            <el-col :span="2">
                <el-form-item>
                    <el-button v-permission type="primary" @click="removePort(index)" link class="mt-1">
                        {{ $t('commons.button.delete') }}
                    </el-button>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="4">
                <el-button v-permission @click="addPort">{{ $t('commons.button.add') }}</el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { Rules, checkNumberRange } from '@/global/form-rules';
import { FormRules } from 'element-plus';
import { Runtime } from '@/api/interface/runtime';

const props = defineProps({
    exposedPorts: {
        type: Array<Runtime.ExposedPort>,
        required: true,
    },
});

const rules = reactive<FormRules>({
    port: [Rules.requiredInput, Rules.paramPort, checkNumberRange(1, 65535)],
});

const handleSwitchChange = (value: boolean, index: number) => {
    props.exposedPorts[index].hostIP = value ? '' : '127.0.0.1';
};

const addPort = () => {
    props.exposedPorts.push({
        hostPort: undefined,
        containerPort: undefined,
        hostIP: '',
        protocol: 'tcp',
    });
};

const removePort = (index: number) => {
    props.exposedPorts.splice(index, 1);
};
</script>
