<template>
    <el-dialog class="ba-operate-dialog" :close-on-click-modal="false" :model-value="!!row" :title="t('channel.manage.whitelist')" @close="close">
        <el-scrollbar v-loading="loading" class="ba-table-form-scrollbar">
            <div class="ba-operate-form">
                <div class="ba-ip-white-list">
                    <div class="ba-ip-white-item" v-for="(ip, idx) in ipWhiteList" :key="idx">
                        <el-input v-model="ipWhiteList[idx]" :placeholder="t('channel.manage.ip_placeholder')" clearable />
                        <el-button @click="onDelIpWhite(idx)" size="small" icon="el-icon-Delete" circle />
                    </div>
                    <el-button v-blur class="ba-add-ip-white" @click="onAddIpWhite" icon="el-icon-Plus">{{ t('Add') }}</el-button>
                </div>
            </div>
        </el-scrollbar>
        <template #footer>
            <el-button @click="close">{{ t('Cancel') }}</el-button>
            <el-button v-blur :loading="submitLoading" @click="onSave" type="primary">{{ t('Save') }}</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { baTableApi } from '/@/api/common'

const { t } = useI18n()

const props = defineProps<{
    row: TableRow | null
}>()

const emit = defineEmits<{
    (e: 'update:row', val: TableRow | null): void
    (e: 'saved'): void
}>()

const api = new baTableApi('/admin/channel.Manage/')
const loading = ref(false)
const submitLoading = ref(false)

/** 将后端数据转为 IP 字符串数组（兼容旧格式 [{key,value}] 和新格式 [ip]） */
function normalizeIpWhite(val: unknown): string[] {
    if (!val || !Array.isArray(val)) return []
    return val.map((item) => (typeof item === 'string' ? item : (item?.value ?? '')))
}

const ipWhiteList = ref<string[]>([])

watch(
    () => props.row,
    (val) => {
        ipWhiteList.value = val ? normalizeIpWhite(val.ip_white) : []
    },
    { immediate: true }
)

const onAddIpWhite = () => {
    ipWhiteList.value.push('')
}

const onDelIpWhite = (idx: number) => {
    ipWhiteList.value.splice(idx, 1)
}

const close = () => {
    emit('update:row', null)
}

const onSave = async () => {
    if (!props.row) return
    const ips = ipWhiteList.value.filter((ip) => ip.trim() !== '')
    submitLoading.value = true
    try {
        await api.postData('edit', {
            id: props.row.id,
            ip_white: ips,
        })
        emit('saved')
        close()
    } finally {
        submitLoading.value = false
    }
}
</script>

<style scoped lang="scss">
.ba-ip-white-list {
    .ba-ip-white-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
        .el-input {
            flex: 1;
        }
    }
    .ba-add-ip-white {
        margin-top: 4px;
    }
}
</style>
