<template>
  <a-modal
    :visible="visible"
    :title="`规则管理 - ${policyName}`"
    width="1200px"
    :mask-closable="false"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
  >
    <div class="rule-manage-content">
      <!-- 工具栏 -->
      <div class="toolbar">
        <a-input-search
          v-model="searchKeyword"
          placeholder="请输入规则名称搜索"
          style="width: 300px"
          allow-clear
          @search="handleSearch"
        />
        <a-button type="primary" @click="handleCreateRule">
          <template #icon>
            <icon-plus />
          </template>
          新建规则
        </a-button>
      </div>
      
      <!-- 规则列表 -->
      <a-table
        :data="ruleData"
        :loading="ruleLoading"
        :pagination="rulePagination"
        :bordered="true"
        size="medium"
        @page-change="handlePageChange"
      >
        <template #columns>
          <a-table-column title="规则名称" data-index="name" :width="200" />
          <a-table-column title="规则类型" data-index="rule_type" :width="100">
            <template #cell="{ record }">
              <a-tag>{{ getRuleTypeText(record.rule_type) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="启用状态" data-index="enabled" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.enabled ? 'green' : 'gray'">
                {{ record.enabled ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="指标/表达式" data-index="metric_expr" :width="200">
            <template #cell="{ record }">
              <span :title="record.metric_name || record.query_expr">
                {{ record.metric_name || record.query_expr || '-' }}
              </span>
            </template>
          </a-table-column>
          <a-table-column title="阈值条件" data-index="threshold" :width="120">
            <template #cell="{ record }">
              <span v-if="record.threshold !== undefined">
                {{ getCompareOpText(record.compare_op) }} {{ record.threshold }}
              </span>
              <span v-else>-</span>
            </template>
          </a-table-column>
          <a-table-column title="持续时间" data-index="duration" :width="100">
            <template #cell="{ record }">
              <span v-if="record.duration">{{ formatDuration(record.duration) }}</span>
              <span v-else>-</span>
            </template>
          </a-table-column>
          <a-table-column title="告警级别" data-index="severity" :width="120">
            <template #cell="{ record }">
              <div v-if="record.severity" :style="{ display: 'flex', alignItems: 'center', gap: '8px' }">
                <div
                  :style="{
                    width: '16px',
                    height: '16px',
                    backgroundColor: record.severity.color,
                    border: '1px solid var(--color-border-2)',
                    borderRadius: '3px'
                  }"
                ></div>
                <span>{{ record.severity.name }}</span>
              </div>
              <span v-else>-</span>
            </template>
          </a-table-column>
          <a-table-column title="操作" data-index="actions" :width="150" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="handleEditRule(record)">
                  编辑
                </a-button>
                <a-popconfirm
                  content="确定要删除该规则吗？"
                  @ok="handleDeleteRule(record)"
                >
                  <a-button type="text" size="small" status="danger">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    
    <!-- 新建/编辑规则弹窗 -->
    <rule-form-dialog
      v-model:visible="ruleFormVisible"
      :rule-id="currentRuleId"
      :policy-id="policyId"
      @success="handleRuleFormSuccess"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import { fetchRuleList, deleteRule } from '@/api/ops/alertPolicy'
import RuleFormDialog from './RuleFormDialog.vue'

// Props
interface Props {
  visible: boolean
  policyId?: number
  policyName?: string
}

const props = defineProps<Props>()
const emit = defineEmits(['update:visible', 'success'])

// 状态管理
const ruleLoading = ref(false)
const ruleData = ref<any[]>([])
const searchKeyword = ref('')

// 规则分页
const rulePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

// 规则表单
const ruleFormVisible = ref(false)
const currentRuleId = ref<number | undefined>(undefined)

// 规则类型映射
const ruleTypeMap: Record<string, string> = {
  static: '静态规则',
  dynamic: '动态规则',
  promql: 'PromQL',
}

// 比较操作符映射
const compareOpMap: Record<string, string> = {
  '>': '>',
  '<': '<',
  '>=': '≥',
  '<=': '≤',
  '==': '=',
  '!=': '≠',
}

// 获取规则类型文本
const getRuleTypeText = (type: string) => {
  return ruleTypeMap[type] || type
}

// 获取比较操作符文本
const getCompareOpText = (op: string) => {
  return compareOpMap[op] || op
}

// 格式化持续时间
const formatDuration = (seconds: number) => {
  if (seconds < 60) {
    return `${seconds}秒`
  } else if (seconds < 3600) {
    return `${Math.floor(seconds / 60)}分钟`
  } else {
    return `${Math.floor(seconds / 3600)}小时`
  }
}

// 加载规则列表
const loadRuleList = async () => {
  if (!props.policyId) return
  
  ruleLoading.value = true
  
  try {
    const res = await fetchRuleList({
      policy_id: props.policyId,
      page: rulePagination.current,
      page_size: rulePagination.pageSize,
      keyword: searchKeyword.value || undefined,
    })
    
    ruleData.value = res.details?.data || []
    rulePagination.total = res.details?.total || 0
  } catch (error) {
    console.error('获取规则列表失败:', error)
    Message.error('获取规则列表失败')
    ruleData.value = []
    rulePagination.total = 0
  } finally {
    ruleLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  rulePagination.current = 1
  loadRuleList()
}

// 分页变化
const handlePageChange = (current: number) => {
  rulePagination.current = current
  loadRuleList()
}

// 新建规则
const handleCreateRule = () => {
  if (!props.policyId) {
    Message.warning('请先选择策略')
    return
  }
  currentRuleId.value = undefined
  ruleFormVisible.value = true
}

// 编辑规则
const handleEditRule = (record: any) => {
  currentRuleId.value = record.id
  ruleFormVisible.value = true
}

// 删除规则
const handleDeleteRule = async (record: any) => {
  try {
    await deleteRule(record.id)
    Message.success('规则删除成功')
    
    // 如果当前页只有一条数据，且不是第一页，则跳到上一页
    if (ruleData.value.length === 1 && rulePagination.current > 1) {
      rulePagination.current--
    }
    
    loadRuleList()
  } catch (error) {
    console.error('删除规则失败:', error)
    Message.error('删除规则失败')
  }
}

// 规则表单成功回调
const handleRuleFormSuccess = () => {
  loadRuleList()
  emit('success')
}

// 处理可见性变化
const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 监听 visible 变化
watch(() => props.visible, (visible) => {
  if (visible) {
    searchKeyword.value = ''
    rulePagination.current = 1
    loadRuleList()
  }
})
</script>

<script lang="ts">
export default {
  name: 'RuleManageDialog',
}
</script>

<style scoped lang="less">
.rule-manage-content {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background-color: var(--color-fill-2);
    border-radius: 4px;
  }
}
</style>
