<template>
  <div class="behavior-rules-tab">
    <div class="tab-header">
      <div class="filter-section">
        <el-select v-model="filterCategory" placeholder="按类别筛选" clearable style="width: 140px;">
          <el-option v-for="opt in BEHAVIOR_CATEGORY_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </div>
      <div class="action-section">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          添加规则
        </el-button>
      </div>
    </div>

    <el-table :data="rules" v-loading="loading" stripe>
      <el-table-column prop="description" label="规则描述" min-width="300">
        <template #default="{ row }">
          <div class="rule-description">
            {{ row.description }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="类别" width="120">
        <template #default="{ row }">
          <el-tag :type="getCategoryTagType(row.category)" size="small">
            {{ getCategoryLabel(row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="is_enabled" label="状态" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.is_enabled"
            @change="handleToggleEnabled(row)"
            size="small"
          />
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑规则' : '添加规则'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="类别" prop="category">
          <el-select v-model="formData.category" placeholder="请选择类别" style="width: 100%;">
            <el-option v-for="opt in BEHAVIOR_CATEGORY_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="5"
            placeholder="请输入规则描述，例如：&#10;- 不承诺具体价格或优惠&#10;- 不评价竞品&#10;- 保持专业、友好的语气"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  listBehaviorRules,
  createBehaviorRule,
  updateBehaviorRule,
  deleteBehaviorRule
} from '@/api/guardrail'
import { BEHAVIOR_CATEGORY_OPTIONS } from '@/types/guardrail'
import type { BehaviorRule, BehaviorRuleCreate, BehaviorRuleUpdate } from '@/types/guardrail'

const loading = ref(false)
const rules = ref<BehaviorRule[]>([])
const filterCategory = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref()
const currentEditId = ref('')

const defaultFormData = (): BehaviorRuleCreate => ({
  description: '',
  category: 'compliance',
  is_enabled: true
})

const formData = ref<BehaviorRuleCreate>(defaultFormData())

const formRules = {
  category: [{ required: true, message: '请选择类别', trigger: 'change' }],
  description: [{ required: true, message: '请输入规则描述', trigger: 'blur' }]
}

const getCategoryLabel = (category: string) => {
  const opt = BEHAVIOR_CATEGORY_OPTIONS.find(o => o.value === category)
  return opt?.label || category
}

const getCategoryTagType = (category: string): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const colorMap: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    compliance: 'danger',
    tone: 'warning',
    boundary: '',
    custom: 'info'
  }
  return colorMap[category] || 'info'
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadRules = async () => {
  loading.value = true
  try {
    const res = await listBehaviorRules({
      category: filterCategory.value || undefined
    })
    rules.value = res.data || []
  } catch (error) {
    ElMessage.error('加载规则列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  isEdit.value = false
  currentEditId.value = ''
  formData.value = defaultFormData()
  dialogVisible.value = true
}

const handleEdit = (row: BehaviorRule) => {
  isEdit.value = true
  currentEditId.value = row.id
  formData.value = {
    description: row.description,
    category: row.category,
    is_enabled: row.is_enabled
  }
  dialogVisible.value = true
}

const handleDelete = async (row: BehaviorRule) => {
  try {
    await ElMessageBox.confirm('确定要删除该规则吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteBehaviorRule(row.id)
    ElMessage.success('删除成功')
    loadRules()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleEnabled = async (row: BehaviorRule) => {
  try {
    await updateBehaviorRule(row.id, { is_enabled: row.is_enabled })
    ElMessage.success(row.is_enabled ? '已启用' : '已禁用')
  } catch (error) {
    row.is_enabled = !row.is_enabled
    ElMessage.error('操作失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    if (isEdit.value) {
      const updateData: BehaviorRuleUpdate = {
        description: formData.value.description,
        category: formData.value.category,
        is_enabled: formData.value.is_enabled
      }
      await updateBehaviorRule(currentEditId.value, updateData)
      ElMessage.success('保存成功')
    } else {
      await createBehaviorRule(formData.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadRules()
  } catch (error) {
    ElMessage.error(isEdit.value ? '保存失败' : '添加失败')
  } finally {
    submitting.value = false
  }
}

watch(filterCategory, () => {
  loadRules()
})

onMounted(() => {
  loadRules()
})
</script>

<style scoped>
.behavior-rules-tab {
  min-height: 300px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-section {
  display: flex;
  gap: 12px;
}

.action-section {
  display: flex;
  gap: 12px;
}

.rule-description {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}
</style>
