<template>
  <div class="subnet-list-tab">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="子网管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增子网
        </a-button>
      </template>

      <template #usage="{ record }">
        <a-progress
          :percent="Math.round((record.used / record.total) * 100)"
          :stroke-width="8"
          :show-text="false"
          :color="getUsageColor((record.used / record.total) * 100)"
        />
        <div class="usage-text">{{ record.used }} / {{ record.total }} ({{ Math.round((record.used / record.total) * 100) }}%)</div>
      </template>

      <template #status="{ record }">
        <a-tag :color="getUsageStatusColor(record.used, record.total)" bordered>
          {{ getUsageStatusText(record.used, record.total) }}
        </a-tag>
      </template>

      <template #actions="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleEdit(record)">编辑</a-button>
          <a-popconfirm content="确定删除该子网吗？" @ok="handleDelete(record)">
            <a-button type="text" size="small" status="danger">删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </search-table>

    <SubnetFormDialog v-model="showFormDialog" :edit-data="currentEditData" :groups="groups" @success="handleFormSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import SearchTable from '@/components/search-table/index.vue'
import SubnetFormDialog from './SubnetFormDialog.vue'
import { subnetColumns } from '../config/columns'
import {
  fetchIPSubnetList,
  deleteIPSubnet,
  fetchIPGroupList,
  type IPSubnetItem,
  type IPSubnetListParams,
  type IPGroupItem,
} from '@/api/ops/ipam'
import type { FormItem } from '@/components/search-form/types'

const loading = ref(false)
const tableData = ref<IPSubnetItem[]>([])
const groups = ref<IPGroupItem[]>([])
const showFormDialog = ref(false)
const currentEditData = ref<IPSubnetItem | null>(null)

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const formModel = reactive({
  keyword: '',
  group_id: '',
})

const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入子网CIDR、名称',
    span: 8,
  },
  {
    field: 'group_id',
    label: '分组',
    type: 'select',
    placeholder: '全部分组',
    options: groups.value.map((g) => ({ label: g.name, value: g.id })),
    span: 8,
  },
])

const columns = subnetColumns

const loadGroups = async () => {
  try {
    const response = await fetchIPGroupList()
    if (response && response.code === 0) {
      groups.value = response.details?.data || response.data || []
    }
  } catch (error) {
    console.error('Failed to load groups:', error)
  }
}

const loadData = async () => {
  loading.value = true
  try {
    const params: IPSubnetListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formModel,
    }

    Object.keys(params).forEach((key) => {
      if (!params[key as keyof IPSubnetListParams]) {
        delete params[key as keyof IPSubnetListParams]
      }
    })

    const response = await fetchIPSubnetList(params)
    if (response && response.code === 0) {
      tableData.value = response.details?.data || response.data || []
      pagination.total = response.details?.total || response.total || 0
    }
  } catch (error) {
    console.error('Failed to load subnets:', error)
  } finally {
    loading.value = false
  }
}

const handleFormModelUpdate = (model: typeof formModel) => {
  Object.assign(formModel, model)
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(formModel, {
    keyword: '',
    group_id: '',
  })
  pagination.current = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadData()
}

const handleRefresh = () => {
  loadData()
}

const handleAdd = () => {
  currentEditData.value = null
  showFormDialog.value = true
}

const handleEdit = (record: IPSubnetItem) => {
  currentEditData.value = record
  showFormDialog.value = true
}

const handleDelete = async (record: IPSubnetItem) => {
  try {
    await deleteIPSubnet(record.id)
    Message.success('删除成功')
    loadData()
  } catch (error) {
    Message.error('删除失败')
  }
}

const handleFormSuccess = () => {
  loadData()
}

const getUsageColor = (percent: number) => {
  if (percent >= 80) return '#F53F3F'
  if (percent >= 70) return '#FF7D00'
  return '#165DFF'
}

const getUsageStatusColor = (used: number, total: number) => {
  const percent = (used / total) * 100
  if (percent >= 80) return 'red'
  if (percent >= 70) return 'orange'
  return 'green'
}

const getUsageStatusText = (used: number, total: number) => {
  const percent = (used / total) * 100
  if (percent >= 80) return '严重'
  if (percent >= 70) return '警告'
  return '正常'
}

onMounted(() => {
  loadGroups()
  loadData()
})
</script>

<style scoped lang="less">
.usage-text {
  font-size: 12px;
  color: var(--color-text-3);
  margin-top: 4px;
}
</style>
