<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑告警级别' : '新建告警级别'"
    width="600px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef" class="level-form">
      <a-alert type="info" show-icon :style="{ marginBottom: '16px' }">
        建议统一使用语义化代码（如 critical、warning、info），便于规则与派单配置复用。
      </a-alert>

      <a-divider orientation="left">基础信息</a-divider>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="级别名称" field="name" :rules="[{ required: true, message: '请输入级别名称' }]">
            <a-input v-model="form.name" placeholder="如：紧急、严重、警告、提示" :max-length="50" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="级别代码（英文）"
            field="code"
            :rules="[{ required: true, message: '请输入级别代码' }, { validator: validateCode }]"
          >
            <a-input
              v-model="form.code"
              placeholder="如：critical、warning、info"
              :max-length="50"
              :disabled="isEdit && level?.is_default"
              allow-clear
            />
            <template v-if="isEdit && level?.is_default">
              <div class="field-tips">默认级别的代码不可修改</div>
            </template>
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">显示配置</a-divider>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="颜色" field="color" :rules="[{ required: true, message: '请选择颜色' }]">
            <div class="color-row">
              <input type="color" v-model="form.color" class="color-picker" />
              <a-input v-model="form.color" placeholder="如：#FF5722" allow-clear />
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="图标" field="icon">
            <a-input v-model="form.icon" placeholder="可选，输入图标名称或类名" :max-length="100" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="是否启用" field="enabled">
        <a-space>
          <a-switch v-model="form.enabled">
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </a-switch>
          <span class="field-tips">禁用后不会参与告警展示与匹配</span>
        </a-space>
      </a-form-item>

      <a-form-item label="描述" field="description">
        <a-textarea
          v-model="form.description"
          placeholder="补充该级别的使用场景或说明（可选）"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          :max-length="500"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createAlertLevel, updateAlertLevel } from '@/api/ops/alertLevel'

interface AlertLevel {
  id?: number
  name?: string
  code?: string
  description?: string
  color?: string
  icon?: string
  priority?: number
  enabled?: boolean
  is_default?: boolean
  config?: string
}

interface Props {
  visible: boolean
  level: AlertLevel | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const submitting = ref(false)

// 验证器函数：验证级别代码格式
const validateCode = (value: string, callback: (error?: string) => void) => {
  if (!/^[a-z0-9_-]+$/.test(value)) {
    callback('级别代码只能包含小写字母、数字、下划线和短横线')
  } else {
    callback()
  }
}

// 表单数据
const form = ref({
  name: '',
  code: '',
  description: '',
  color: '#FF5722',
  icon: '',
  enabled: true,
  priority: 0,
})

// 是否为编辑模式
const isEdit = computed(() => !!props.level?.id)

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.level && isEdit.value) {
        // 编辑模式：填充表单
        form.value = {
          name: props.level.name || '',
          code: props.level.code || '',
          description: props.level.description || '',
          color: props.level.color || '#FF5722',
          icon: props.level.icon || '',
          enabled: props.level.enabled !== undefined ? props.level.enabled : true,
          priority: props.level.priority || 0,
        }
      } else {
        // 新建模式：重置表单
        form.value = {
          name: '',
          code: '',
          description: '',
          color: '#FF5722',
          icon: '',
          enabled: true,
          priority: 0,
        }
      }
    }
  }
)

// 确认提交
const handleOk = async () => {
  const valid = await formRef.value?.validate()
  if (valid) return

  submitting.value = true
  try {
    const data: any = {
      name: form.value.name,
      code: form.value.code,
      description: form.value.description,
      color: form.value.color,
      icon: form.value.icon,
      enabled: form.value.enabled,
    }

    let res
    if (isEdit.value && props.level?.id) {
      // 编辑告警级别
      data.id = props.level.id
      res = await updateAlertLevel(data)
    } else {
      // 新建告警级别
      res = await createAlertLevel(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '编辑成功' : '创建成功')
      emit('success')
      emit('update:visible', false)
    } else {
      Message.error(res.message || (isEdit.value ? '编辑失败' : '创建失败'))
    }
  } catch (error) {
    Message.error(isEdit.value ? '编辑失败' : '创建失败')
    console.error(error)
  } finally {
    submitting.value = false
  }
}

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

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

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

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

  .color-row {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .color-picker {
    width: 60px;
    height: 32px;
    cursor: pointer;
    border: 1px solid var(--color-border-2);
    border-radius: 4px;
    background: transparent;
    padding: 0;
  }
}
</style>
