<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? `编辑工单模板 - ${form.template_name}` : '新建工单模板'"
    :width="800"
    :footer="false"
    @update:visible="handleVisibleChange"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical" @submit="handleSubmit">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="模板名称" field="template_name">
            <a-input v-model="form.template_name" placeholder="请输入模板名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="模板编码" field="template_code">
            <a-input v-model="form.template_code" placeholder="请输入模板编码" :disabled="isEdit" />
            <template v-if="isEdit" #extra>
              <span style="color: var(--color-text-3); font-size: 12px">模板编码创建后不可修改</span>
            </template>
          </a-form-item>
        </a-col>
      </a-row>

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

      <a-divider orientation="left">工单默认值</a-divider>

      <a-form-item label="默认标题" field="title">
        <a-input v-model="form.title" placeholder="请输入工单默认标题" />
      </a-form-item>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="类型" field="type">
            <a-select v-model="form.type" placeholder="请选择类型" allow-clear>
              <a-option value="incident">事件</a-option>
              <a-option value="request">请求</a-option>
              <a-option value="change">变更</a-option>
              <a-option value="problem">问题</a-option>
              <a-option value="consultation">咨询</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="优先级" field="priority">
            <a-select v-model="form.priority" placeholder="请选择优先级" allow-clear>
              <a-option value="low">低</a-option>
              <a-option value="medium">中</a-option>
              <a-option value="high">高</a-option>
              <a-option value="critical">紧急</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="默认分类ID" field="category_id">
            <a-input-number v-model="form.category_id" placeholder="请输入分类ID" :min="0" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="默认处理人ID" field="assignee_id">
            <a-input-number v-model="form.assignee_id" placeholder="请输入处理人ID" :min="0" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="默认内容" field="content">
        <a-textarea v-model="form.content" placeholder="请输入工单默认内容" :auto-size="{ minRows: 3, maxRows: 6 }" />
      </a-form-item>

      <a-divider orientation="left">触发配置</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="触发类型" field="trigger_type">
            <a-select v-model="form.trigger_type" placeholder="请选择触发类型" allow-clear>
              <a-option value="manual">手动</a-option>
              <a-option value="scheduled">定时</a-option>
              <a-option value="event">事件</a-option>
              <a-option value="api">API</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="定时表达式" field="cron_expression" :disabled="form.trigger_type !== 'scheduled'">
            <a-input v-model="form.cron_expression" placeholder="请输入Cron表达式" :disabled="form.trigger_type !== 'scheduled'" />
            <template v-if="form.trigger_type === 'scheduled'" #extra>
              <span style="color: var(--color-text-3); font-size: 12px">示例: 0 0 * * *</span>
            </template>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="触发规则" field="trigger_rule">
        <a-textarea
          v-model="form.trigger_rule"
          placeholder='请输入JSON格式的触发规则，例如: {"key": "value"}'
          :auto-size="{ minRows: 2, maxRows: 4 }"
        />
      </a-form-item>

      <a-divider orientation="left">自动化配置</a-divider>

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="自动分配" field="auto_assign">
            <a-switch v-model="form.auto_assign" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="自动接单" field="auto_accept">
            <a-switch v-model="form.auto_accept" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="SLA(分钟)" field="sla_duration">
            <a-input-number v-model="form.sla_duration" placeholder="请输入SLA" :min="0" style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="分配规则" field="assign_rule">
        <a-textarea
          v-model="form.assign_rule"
          placeholder='请输入JSON格式的分配规则，例如: {"rule": "value"}'
          :auto-size="{ minRows: 2, maxRows: 4 }"
        />
      </a-form-item>

      <a-divider orientation="left">表单与通知配置</a-divider>

      <a-form-item label="字段配置" field="field_config">
        <a-textarea
          v-model="form.field_config"
          placeholder='请输入JSON格式的字段配置，例如: {"fields": []}'
          :auto-size="{ minRows: 2, maxRows: 4 }"
        />
      </a-form-item>

      <a-form-item label="通知配置" field="notify_config">
        <a-textarea
          v-model="form.notify_config"
          placeholder='请输入JSON格式的通知配置，例如: {"channels": []}'
          :auto-size="{ minRows: 2, maxRows: 4 }"
        />
      </a-form-item>

      <a-divider orientation="left">扩展配置</a-divider>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="标签" field="tags">
            <a-textarea
              v-model="form.tags"
              placeholder='请输入JSON格式的标签，例如: ["tag1", "tag2"]'
              :auto-size="{ minRows: 2, maxRows: 3 }"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="元数据" field="metadata">
            <a-textarea
              v-model="form.metadata"
              placeholder='请输入JSON格式的元数据，例如: {"key": "value"}'
              :auto-size="{ minRows: 2, maxRows: 3 }"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" :loading="loading">
            {{ isEdit ? '更新' : '创建' }}
          </a-button>
          <a-button @click="handleCancel">取消</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { createTemplate, updateTemplate, fetchTemplateDetail } from '@/api/ops/template'

interface Props {
  visible: boolean
  templateId?: number
}

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

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

const formRef = ref()
const loading = ref(false)

const isEdit = computed(() => !!props.templateId)

const form = reactive({
  template_name: '',
  template_code: '',
  description: '',
  title: '',
  type: '',
  priority: '',
  category_id: undefined as number | undefined,
  assignee_id: undefined as number | undefined,
  content: '',
  trigger_type: '',
  trigger_rule: '',
  cron_expression: '',
  sla_duration: undefined as number | undefined,
  field_config: '',
  auto_assign: false,
  auto_accept: false,
  assign_rule: '',
  notify_config: '',
  tags: '',
  metadata: '',
})

const rules = {
  template_name: [{ required: true, message: '请输入模板名称' }],
  template_code: [{ required: true, message: '请输入模板编码' }],
  title: [{ required: true, message: '请输入默认标题' }],
}

// 监听弹窗显示状态，如果是编辑模式则加载详情
watch(
  () => props.visible,
  async (val) => {
    if (val && props.templateId) {
      await loadTemplateDetail()
    } else if (val && !props.templateId) {
      resetForm()
    }
  }
)

// 加载模板详情
const loadTemplateDetail = async () => {
  try {
    loading.value = true
    const res = await fetchTemplateDetail(props.templateId!)
    if (res.code === 0 && res.details) {
      const data = res.details
      Object.assign(form, {
        template_name: data.template_name || '',
        template_code: data.template_code || '',
        description: data.description || '',
        title: data.title || '',
        type: data.type || '',
        priority: data.priority || '',
        category_id: data.category_id,
        assignee_id: data.assignee_id,
        content: data.content || '',
        trigger_type: data.trigger_type || '',
        trigger_rule: data.trigger_rule || '',
        cron_expression: data.cron_expression || '',
        sla_duration: data.sla_duration,
        field_config: data.field_config || '',
        auto_assign: data.auto_assign || false,
        auto_accept: data.auto_accept || false,
        assign_rule: data.assign_rule || '',
        notify_config: data.notify_config || '',
        tags: data.tags || '',
        metadata: data.metadata || '',
      })
    }
  } catch (error) {
    console.error('加载模板详情失败:', error)
    Message.error('加载模板详情失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    template_name: '',
    template_code: '',
    description: '',
    title: '',
    type: '',
    priority: '',
    category_id: undefined,
    assignee_id: undefined,
    content: '',
    trigger_type: '',
    trigger_rule: '',
    cron_expression: '',
    sla_duration: undefined,
    field_config: '',
    auto_assign: false,
    auto_accept: false,
    assign_rule: '',
    notify_config: '',
    tags: '',
    metadata: '',
  })
}

// 验证JSON格式
const validateJSON = (value: string) => {
  if (!value || value.trim() === '') return true
  try {
    JSON.parse(value)
    return true
  } catch {
    return false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) return

    // 验证JSON字段
    const jsonFields = ['trigger_rule', 'field_config', 'assign_rule', 'notify_config', 'tags', 'metadata']
    for (const field of jsonFields) {
      const value = form[field as keyof typeof form] as string
      if (value && value.trim() !== '' && !validateJSON(value)) {
        Message.error(`${field} 必须是合法的 JSON 格式`)
        return
      }
    }

    loading.value = true

    // 编辑时不包含 template_code
    const submitData: any = { ...form }
    if (isEdit.value) {
      delete submitData.template_code
    }

    const res = isEdit.value ? await updateTemplate(props.templateId!, submitData) : await createTemplate(submitData)

    if (res.code === 0) {
      Message.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      handleCancel()
    } else {
      Message.error(res.msg || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    Message.error(error.msg || '提交失败')
  } finally {
    loading.value = false
  }
}

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

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

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