<template>
  <div class="changes-tab">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="IP变更记录"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #change_type="{ record }">
        <a-tag :color="getChangeTypeColor(record.change_type)" bordered>
          {{ getChangeTypeText(record.change_type) }}
        </a-tag>
      </template>

      <template #changed_at="{ record }">
        {{ formatDateTime(record.changed_at) }}
      </template>

      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">详情</a-button>
      </template>
    </search-table>

    <a-modal v-model:visible="showDetailDialog" title="变更详情" :width="800" :footer="false">
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="IP地址">{{ currentDetail?.ip_address }}</a-descriptions-item>
        <a-descriptions-item label="所属子网">{{ currentDetail?.subnet_name }}</a-descriptions-item>
        <a-descriptions-item label="变更类型">
          <a-tag :color="getChangeTypeColor(currentDetail?.change_type)" bordered>
            {{ getChangeTypeText(currentDetail?.change_type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="变更人">{{ currentDetail?.changed_by || '-' }}</a-descriptions-item>
        <a-descriptions-item label="变更时间" :span="2">{{ formatDateTime(currentDetail?.changed_at) }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">{{ currentDetail?.remark || '-' }}</a-descriptions-item>
      </a-descriptions>
      <div v-if="currentDetail?.before_json || currentDetail?.after_json" class="diff-section">
        <a-row :gutter="16">
          <a-col :span="12">
            <div class="diff-title">变更前</div>
            <pre class="diff-content before">{{ formatJson(currentDetail?.before_json) }}</pre>
          </a-col>
          <a-col :span="12">
            <div class="diff-title">变更后</div>
            <pre class="diff-content after">{{ formatJson(currentDetail?.after_json) }}</pre>
          </a-col>
        </a-row>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import SearchTable from '@/components/search-table/index.vue'
import {
  fetchIPChangeList,
  fetchIPSubnetList,
  type IPChangeItem,
  type IPChangeListParams,
  type IPSubnetItem,
} from '@/api/ops/ipam'
import type { FormItem } from '@/components/search-form/types'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'

const loading = ref(false)
const tableData = ref<IPChangeItem[]>([])
const subnets = ref<IPSubnetItem[]>([])
const showDetailDialog = ref(false)
const currentDetail = ref<IPChangeItem | null>(null)

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

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

const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入IP地址',
    span: 8,
  },
  {
    field: 'subnet_id',
    label: '子网',
    type: 'select',
    placeholder: '全部子网',
    options: subnets.value.map((s) => ({ label: `${s.name} (${s.cidr})`, value: s.id })),
    span: 8,
  },
  {
    field: 'change_type',
    label: '变更类型',
    type: 'select',
    placeholder: '全部类型',
    options: [
      { label: '分配', value: 'allocate' },
      { label: '释放', value: 'release' },
      { label: '修改', value: 'modify' },
      { label: '状态变更', value: 'status_change' },
    ],
    span: 8,
  },
])

const columns: TableColumnData[] = [
  { title: 'IP地址', dataIndex: 'ip_address', width: 150 },
  { title: '变更类型', dataIndex: 'change_type', slotName: 'change_type', width: 120, align: 'center' },
  { title: '所属子网', dataIndex: 'subnet_name', width: 150 },
  { title: '变更人', dataIndex: 'changed_by', width: 120 },
  { title: '变更时间', dataIndex: 'changed_at', slotName: 'changed_at', width: 180 },
  { title: '备注', dataIndex: 'remark', width: 200 },
  { title: '操作', dataIndex: 'actions', slotName: 'actions', width: 80, fixed: 'right' },
]

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

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

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

    const response = await fetchIPChangeList(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 changes:', 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: '',
    subnet_id: '',
    change_type: '',
  })
  pagination.current = 1
  loadData()
}

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

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

const handleDetail = (record: IPChangeItem) => {
  currentDetail.value = record
  showDetailDialog.value = true
}

const getChangeTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    allocate: 'green',
    release: 'orange',
    modify: 'blue',
    status_change: 'purple',
  }
  return colorMap[type || ''] || 'gray'
}

const getChangeTypeText = (type?: string) => {
  const textMap: Record<string, string> = {
    allocate: '分配',
    release: '释放',
    modify: '修改',
    status_change: '状态变更',
  }
  return textMap[type || ''] || type || '-'
}

const formatDateTime = (datetime?: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

const formatJson = (jsonStr?: string) => {
  if (!jsonStr) return '{}'
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

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

<style scoped lang="less">
.diff-section {
  margin-top: 16px;
}

.diff-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: var(--color-text-1);
}

.diff-content {
  background: var(--color-fill-1);
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
  word-break: break-all;

  &.before {
    border-left: 3px solid #f53f3f;
  }

  &.after {
    border-left: 3px solid #00b42a;
  }
}
</style>
