<template>
    <div>
        <FireRouter />

        <div v-loading="loading">
            <FireStatus
                ref="fireStatusRef"
                @search="search"
                v-model:loading="loading"
                v-model:name="fireName"
                v-model:mask-show="maskShow"
                v-model:is-active="isActive"
                v-model:is-bind="isBind"
                current-tab="base"
            />

            <div v-if="fireName !== '-'">
                <el-card v-if="!isActive && maskShow" class="mask-prompt">
                    <span>{{ $t('firewall.firewallNotStart') }}</span>
                </el-card>
                <el-card v-if="!isBind && maskShow" class="mask-prompt">
                    <span>{{ $t('firewall.basicStatus', ['1PANEL_BASIC']) }}</span>
                </el-card>

                <LayoutContent :title="$t('firewall.ipRule', 2)" :class="{ mask: !isActive || !isBind }">
                    <template #prompt>
                        <div v-if="fireName !== 'iptables'">
                            <el-alert :closable="false" :title="$t('firewall.iptablesHelper', [fireName])" />
                        </div>
                    </template>
                    <template #leftToolBar>
                        <el-button v-permission v-node-admin type="primary" @click="onOpenDialog('create')">
                            {{ $t('commons.button.create') }}
                        </el-button>
                        <el-button
                            v-permission
                            v-node-admin
                            @click="onDelete(null)"
                            plain
                            :disabled="selects.length === 0"
                        >
                            {{ $t('commons.button.delete') }}
                        </el-button>
                        <el-button-group>
                            <el-button v-permission v-node-admin @click="onImport">
                                {{ $t('commons.button.import') }}
                            </el-button>
                            <el-button v-permission v-node-admin :disabled="selects.length === 0" @click="onExport">
                                {{ $t('commons.button.export') }}
                            </el-button>
                        </el-button-group>
                    </template>
                    <template #rightToolBar>
                        <el-select v-model="searchStrategy" @change="search()" clearable class="p-w-200">
                            <template #prefix>{{ $t('firewall.strategy') }}</template>
                            <el-option :label="$t('commons.table.all')" value=""></el-option>
                            <el-option :label="$t('firewall.allow')" value="accept"></el-option>
                            <el-option :label="$t('firewall.deny')" value="drop"></el-option>
                        </el-select>
                        <TableSearch @search="search()" v-model:searchName="searchName" />
                        <TableRefresh @search="search()" />
                        <TableSetting title="firewall-ip-refresh" @search="search()" />
                    </template>
                    <template #main>
                        <ComplexTable
                            :pagination-config="paginationConfig"
                            v-model:selects="selects"
                            @search="search"
                            :data="data"
                            :heightDiff="400"
                        >
                            <el-table-column type="selection" fix />
                            <el-table-column :min-width="120" :label="$t('firewall.address')" prop="address">
                                <template #default="{ row }">
                                    <span v-if="row.address && row.address !== 'Anywhere'">{{ row.address }}</span>
                                    <span v-else>{{ $t('firewall.allIP') }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column :min-width="80" :label="$t('firewall.strategy')" prop="strategy">
                                <template #default="{ row }">
                                    <el-button
                                        v-if="row.strategy === 'accept'"
                                        v-permission
                                        v-node-admin
                                        @click="onChangeStatus(row, 'drop')"
                                        link
                                        type="success"
                                    >
                                        {{ $t('firewall.allow') }}
                                    </el-button>
                                    <el-button
                                        v-else
                                        link
                                        type="danger"
                                        v-permission
                                        v-node-admin
                                        @click="onChangeStatus(row, 'accept')"
                                    >
                                        {{ $t('firewall.deny') }}
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column
                                :min-width="120"
                                :label="$t('commons.table.description')"
                                prop="description"
                                show-overflow-tooltip
                            >
                                <template #default="{ row }">
                                    <fu-input-rw-switch
                                        v-model="row.description"
                                        v-permission
                                        v-node-admin
                                        @enter="onChange(row)"
                                        @blur="onChange(row)"
                                    />
                                </template>
                            </el-table-column>
                            <fu-table-operations
                                width="200px"
                                :buttons="buttons"
                                :ellipsis="10"
                                :label="$t('commons.table.operate')"
                                fix
                            />
                        </ComplexTable>
                    </template>
                </LayoutContent>
            </div>
        </div>

        <OpDialog ref="opRef" @search="search" />
        <OperateDialog @search="search" ref="dialogRef" />
        <ImportDialog @search="search" ref="dialogImportRef" />
    </div>
</template>

<script lang="ts" setup>
import OperateDialog from '@/views/host/firewall/ip/operate/index.vue';
import ImportDialog from '@/views/host/firewall/ip/import/index.vue';
import FireRouter from '@/views/host/firewall/index.vue';
import FireStatus from '@/views/host/firewall/status/index.vue';
import { onMounted, reactive, ref } from 'vue';
import { batchOperateRule, searchFireRule, updateAddrRule, updateFirewallDescription } from '@/api/modules/host';
import { Host } from '@/api/interface/host';
import { ElMessageBox } from 'element-plus';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message';
import { downloadWithContent } from '@/utils/file';
import { getCurrentDateFormatted } from '@/utils/date';
const loading = ref();
const activeTag = ref('address');
const selects = ref<any>([]);
const searchName = ref();
const searchStrategy = ref('');
const fireName = ref();

const maskShow = ref(true);
const isActive = ref(false);
const isBind = ref(false);
const fireStatusRef = ref();

const opRef = ref();
const dialogImportRef = ref();

const data = ref();
const paginationConfig = reactive({
    cacheSizeKey: 'firewall-ip-page-size',
    currentPage: 1,
    pageSize: Number(localStorage.getItem('firewall-ip-page-size')) || 20,
    total: 0,
});

const search = async () => {
    if (!isActive.value) {
        loading.value = false;
        data.value = [];
        paginationConfig.total = 0;
        return;
    }
    let params = {
        type: activeTag.value,
        strategy: searchStrategy.value,
        info: searchName.value,
        page: paginationConfig.currentPage,
        pageSize: paginationConfig.pageSize,
    };
    loading.value = true;
    await searchFireRule(params)
        .then((res) => {
            loading.value = false;
            data.value = res.data.items || [];
            paginationConfig.total = res.data.total;
        })
        .catch(() => {
            loading.value = false;
        });
};

const dialogRef = ref();
const onOpenDialog = async (
    title: string,
    rowData: Partial<Host.RuleIP> = {
        strategy: 'accept',
    },
) => {
    let params = {
        title,
        fireName: fireName.value,
        rowData: { ...rowData },
    };
    dialogRef.value!.acceptParams(params);
};

const onChange = async (row: any) => {
    let params = {
        type: 'address',
        chain: fireName.value === 'iptables' ? '1PANEL_BASIC' : '',
        srcIP: row.address,
        dstIP: '',
        srcPort: '',
        dstPort: '',
        protocol: '',
        strategy: row.strategy,

        description: row.description,
    };
    await updateFirewallDescription(params);
    MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
};

const onChangeStatus = async (row: Host.RuleInfo, status: string) => {
    let operation =
        status === 'accept'
            ? i18n.global.t('firewall.changeStrategyIPHelper2')
            : i18n.global.t('firewall.changeStrategyIPHelper1');
    ElMessageBox.confirm(operation, i18n.global.t('firewall.changeStrategy', [' IP ']), {
        confirmButtonText: i18n.global.t('commons.button.confirm'),
        cancelButtonText: i18n.global.t('commons.button.cancel'),
    }).then(async () => {
        let params = {
            oldRule: {
                operation: 'remove',
                address: row.address,
                strategy: row.strategy,
                description: row.description,
            },
            newRule: {
                operation: 'add',
                address: row.address,
                strategy: status,
                description: row.description,
            },
        };
        loading.value = true;
        await updateAddrRule(params)
            .then(() => {
                loading.value = false;
                MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
                search();
            })
            .catch(() => {
                loading.value = false;
            });
    });
};

const onDelete = async (row: Host.RuleIP | null) => {
    let names = [];
    let rules = [];
    if (row) {
        rules.push({
            operation: 'remove',
            address: row.address,
            port: '',
            source: '',
            protocol: '',
            strategy: row.strategy,
        });
        names = [row.address];
    } else {
        for (const item of selects.value) {
            rules.push({
                operation: 'remove',
                address: item.address,
                port: '',
                source: '',
                protocol: '',
                strategy: item.strategy,
            });
            names.push(item.address);
        }
    }
    opRef.value.acceptParams({
        title: i18n.global.t('commons.button.delete'),
        names: names,
        msg: i18n.global.t('commons.msg.operatorHelper', [
            i18n.global.t('firewall.ipRule'),
            i18n.global.t('commons.button.delete'),
        ]),
        api: batchOperateRule,
        params: { type: 'address', rules: rules },
    });
};

const onImport = () => {
    dialogImportRef.value.acceptParams();
};

const onExport = () => {
    ElMessageBox.confirm(
        i18n.global.t('firewall.exportHelper', [selects.value.length]),
        i18n.global.t('commons.button.export'),
        {
            confirmButtonText: i18n.global.t('commons.button.confirm'),
            cancelButtonText: i18n.global.t('commons.button.cancel'),
        },
    ).then(async () => {
        const exportData = selects.value.map((item: Host.RuleInfo) => ({
            family: item.family,
            address: item.address,
            strategy: item.strategy,
            description: item.description,
        }));
        const content = JSON.stringify(exportData, null, 2);
        const fileName = `1panel-firewall-ip-${getCurrentDateFormatted()}.json`;
        downloadWithContent(content, fileName);
    });
};

const buttons = [
    {
        label: i18n.global.t('commons.button.edit'),
        permission: true,
        nodeAdmin: true,
        click: (row: Host.RuleIP) => {
            onOpenDialog('edit', row);
        },
    },
    {
        label: i18n.global.t('commons.button.delete'),
        permission: true,
        nodeAdmin: true,
        click: (row: Host.RuleIP) => {
            onDelete(row);
        },
    },
];

onMounted(() => {
    if (fireName.value !== '-') {
        loading.value = true;
        fireStatusRef.value.acceptParams();
    }
});
</script>
