<template>
  <a-modal
    :visible="visible"
    title="新建告警策略"
    width="800px"
    :mask-closable="false"
    :body-style="{ overflowX: 'hidden' }"
    @cancel="handleCancel"
    @before-ok="handleSubmit"
    @update:visible="handleVisibleChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
      :style="{ marginBottom: '40px' }"
    >
      <a-divider orientation="left">基础信息</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="name" label="策略名称" required>
            <a-input v-model="formData.name" placeholder="请输入策略名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="priority" label="优先级">
            <a-select v-model="formData.priority" placeholder="请选择优先级" allow-clear>
              <a-option :value="1">1 (最高)</a-option>
              <a-option :value="2">2</a-option>
              <a-option :value="3">3</a-option>
              <a-option :value="4">4</a-option>
              <a-option :value="5">5 (最低)</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="description" label="策略描述">
        <a-textarea v-model="formData.description" placeholder="请输入策略描述" :auto-size="{ minRows: 2, maxRows: 4 }" allow-clear />
      </a-form-item>

      <a-form-item field="enabled" label="启用状态">
        <a-switch v-model="formData.enabled" :checked-value="true" :unchecked-value="false">
          <template #checked> 启用 </template>
          <template #unchecked> 禁用 </template>
        </a-switch>
      </a-form-item>

      <a-divider orientation="left">模板与拓展配置</a-divider>

      <a-form-item field="template_id" label="关联模板">
        <a-select
          v-model="formData.template_id"
          placeholder="请选择告警模板（可选）"
          allow-search
          allow-clear
          :loading="templateLoading"
        >
          <a-option v-for="template in templateOptions" :key="template.id" :value="template.id">
            {{ template.name }}
          </a-option>
        </a-select>
      </a-form-item>

      <a-form-item field="labels" label="拓展配置">
        <a-textarea
          v-model="formData.labels"
          placeholder='请输入拓展配置，JSON格式，例如：{"env":"prod","team":"ops"}'
          :auto-size="{ minRows: 2, maxRows: 4 }"
          allow-clear
        />
        <template #extra> 请输入有效的 JSON 格式配置 </template>
      </a-form-item>

      <a-divider orientation="left">自动建单与派单</a-divider>

      <a-form-item field="auto_create_ticket" label="触发时自动建单">
        <a-switch v-model="formData.auto_create_ticket" :checked-value="true" :unchecked-value="false">
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch>
      </a-form-item>

      <a-form-item field="feedback_template_id" label="工单模板">
        <a-select
          v-model="formData.feedback_template_id"
          placeholder="请选择工单模板（可选）"
          allow-search
          allow-clear
          :loading="feedbackTemplateLoading"
          :disabled="!formData.auto_create_ticket"
        >
          <a-option :value="0">不使用特定模板</a-option>
          <a-option v-for="item in feedbackTemplateOptions" :key="item.id" :value="item.id">
            {{ item.template_name }} ({{ item.template_code }})
          </a-option>
        </a-select>
        <template #extra>
          {{ formData.auto_create_ticket ? '建议默认选择可用模板，未选择时将按 0 处理' : '请先开启自动建单后再选择工单模板' }}
        </template>
      </a-form-item>

      <a-form-item label="派单规则">
        <a-table :data="dispatchRuleData" :pagination="false" :bordered="true" size="medium" class="dispatch-table">
          <template #columns>
            <a-table-column title="告警级别" data-index="severity">
              <template #cell="{ record }">
                <a-tag :color="record.color">
                  {{ record.name }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="处理人" data-index="assignee_id">
              <template #cell="{ record }">
                <a-select
                  v-model="record.assignee_id"
                  placeholder="请选择处理人"
                  allow-search
                  allow-clear
                  :filter-option="false"
                  :loading="userLoading"
                  @search="handleUserSearch"
                  :style="{ width: '100%' }"
                  :trigger-props="selectTriggerProps"
                >
                  <a-option v-for="user in userOptions" :key="user.id" :value="user.id">
                    {{ user.name || user.account }} ({{ user.account }})
                  </a-option>
                </a-select>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-form-item>

      <a-form-item label="默认处理人">
        <a-select
          v-model="defaultAssigneeId"
          placeholder="请选择默认处理人"
          allow-search
          allow-clear
          :filter-option="false"
          :loading="userLoading"
          @search="handleUserSearch"
          :trigger-props="selectTriggerProps"
        >
          <a-option v-for="user in userOptions" :key="user.id" :value="user.id">
            {{ user.name || user.account }} ({{ user.account }})
          </a-option>
        </a-select>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="handleSubmit"> 保存 </a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { createPolicy, fetchTemplateList, fetchSeverityOptions, fetchFeedbackTemplateOptions } from '@/api/ops/alertPolicy'
import { fetchUserList } from '@/api/ops/rbac2'

interface Props {
  visible: boolean
}

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

const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const templateLoading = ref(false)
const feedbackTemplateLoading = ref(false)
const userLoading = ref(false)

const formData = reactive({
  name: '',
  description: '',
  enabled: true,
  priority: 3,
  labels: '',
  template_id: undefined as number | undefined,
  auto_create_ticket: false,
  feedback_template_id: undefined as number | undefined,
  dispatch_rule: '',
})

const formRules = {
  name: [{ required: true, message: '请输入策略名称' }],
  labels: [
    {
      validator: (value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        try {
          JSON.parse(value)
          callback()
        } catch (error) {
          callback('拓展配置格式错误，请输入有效的 JSON 格式')
        }
      },
    },
  ],
}

const templateOptions = ref<any[]>([])
const feedbackTemplateOptions = ref<any[]>([])
const userOptions = ref<any[]>([])
const severityList = ref<any[]>([
  { code: 'critical', name: '严重', color: 'red' },
  { code: 'major', name: '重要', color: 'orange' },
  { code: 'warning', name: '警告', color: 'yellow' },
  { code: 'info', name: '信息', color: 'blue' },
  { code: 'minor', name: '次要', color: 'gray' },
])
const dispatchRuleData = ref<any[]>([])
const defaultAssigneeId = ref<number | undefined>(undefined)

const loadTemplateOptions = async () => {
  templateLoading.value = true
  try {
    const res = await fetchTemplateList({ page: 1, page_size: 1000 })
    if (res.code === 0 && res.details?.data) {
      templateOptions.value = res.details.data
    }
  } catch (error) {
    console.error('获取模板列表失败:', error)
  } finally {
    templateLoading.value = false
  }
}

const loadSeverityList = async () => {
  try {
    const res: any = await fetchSeverityOptions({ enabled: 'true' })
    const list = Array.isArray(res?.details)
      ? res.details
      : res?.details?.data || res?.details?.list || res?.data || res
    severityList.value = Array.isArray(list) ? list : []
    initDispatchRuleData()
  } catch (error) {
    console.error('获取告警级别失败:', error)
  }
}

const loadUserOptions = async (keyword = '') => {
  userLoading.value = true
  try {
    const workspace = import.meta.env.VITE_APP_WORKSPACE || ''
    const res = await fetchUserList({
      workspace,
      keyword: keyword || undefined,
      status: 1,
    })
    const rawList = Array.isArray(res?.data?.data)
      ? res.data.data
      : Array.isArray(res?.details?.data)
        ? res.details.data
        : Array.isArray(res?.details)
          ? res.details
          : Array.isArray(res?.data)
            ? res.data
            : []
    userOptions.value = rawList.map((item: any) => ({
      id: Number(item.id),
      name: item.name || '',
      account: item.account || item.username || '',
    }))
  } catch (error) {
    console.error('获取用户下拉选项失败:', error)
    userOptions.value = []
  } finally {
    userLoading.value = false
  }
}

const handleUserSearch = (value: string) => {
  loadUserOptions(value)
}

const getSelectPopupContainer = (triggerNode: HTMLElement) => {
  return triggerNode.closest('.arco-modal') || document.body
}

const selectTriggerProps = {
  updateAtScroll: true,
  autoFitPopupMinWidth: true,
  getPopupContainer: getSelectPopupContainer,
}

const loadFeedbackTemplateOptions = async () => {
  feedbackTemplateLoading.value = true
  try {
    const res = await fetchFeedbackTemplateOptions({ status: 'active' })
    const rawOptions = Array.isArray(res?.data)
      ? res.data
      : Array.isArray(res?.details?.data)
        ? res.details.data
        : Array.isArray(res?.details)
          ? res.details
          : []

    feedbackTemplateOptions.value = rawOptions.map((item: any) => ({
      id: Number(item.id),
      template_name: item.template_name || item.name || `模板-${item.id}`,
      template_code: item.template_code || item.code || '',
      status: item.status,
    }))
  } catch (error) {
    console.error('获取工单模板下拉选项失败:', error)
  } finally {
    feedbackTemplateLoading.value = false
  }
}

const initDispatchRuleData = () => {
  dispatchRuleData.value = severityList.value.map((severity) => ({
    severity_code: severity.code,
    name: severity.name,
    color: severity.color,
    assignee_id: undefined,
  }))
}

const generateDispatchRule = (): string => {
  const by_severity: Record<string, number> = {}
  dispatchRuleData.value.forEach((item) => {
    if (item.assignee_id !== undefined) {
      by_severity[item.severity_code] = item.assignee_id
    }
  })

  const rule: Record<string, any> = {}
  if (Object.keys(by_severity).length > 0) {
    rule.by_severity = by_severity
  }
  if (defaultAssigneeId.value !== undefined) {
    rule.default_assignee_id = defaultAssigneeId.value
  }

  return Object.keys(rule).length > 0 ? JSON.stringify(rule) : ''
}

const resetForm = () => {
  formData.name = ''
  formData.description = ''
  formData.enabled = true
  formData.priority = 3
  formData.labels = ''
  formData.template_id = undefined
  formData.auto_create_ticket = false
  formData.feedback_template_id = undefined
  formData.dispatch_rule = ''
  defaultAssigneeId.value = undefined
  initDispatchRuleData()
}

const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}

const handleCancel = () => {
  emit('update:visible', false)
  resetForm()
}

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

  submitLoading.value = true
  try {
    formData.dispatch_rule = generateDispatchRule()
    const data = {
      name: formData.name,
      description: formData.description || undefined,
      enabled: !!formData.enabled,
      priority: formData.priority ?? undefined,
      labels: formData.labels || undefined,
      template_id: formData.template_id ?? undefined,
      auto_create_ticket: !!formData.auto_create_ticket,
      feedback_template_id: formData.feedback_template_id ?? 0,
      dispatch_rule: formData.dispatch_rule || undefined,
    }

    const res = await createPolicy(data)
    // 后端是业务 code 约定；接口返回失败时不应继续展示成功提示
    if (res?.code !== 0) {
      throw new Error(res?.message || '创建策略失败')
    }
    Message.success('策略创建成功')
    emit('success')
    handleCancel()
  } catch (error: any) {
    console.error('创建策略失败:', error)
    Message.error(error.message || '创建策略失败')
  } finally {
    submitLoading.value = false
  }
}

watch(
  () => formData.auto_create_ticket,
  (enabled) => {
    if (!enabled) {
      formData.feedback_template_id = undefined
    }
  }
)

loadTemplateOptions()
loadSeverityList()
loadFeedbackTemplateOptions()
loadUserOptions()
initDispatchRuleData()
</script>

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

<style scoped lang="less">
.dispatch-table {
  width: 100%;
}
</style>
