<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑中间件' : '新增中间件'"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
    :confirm-loading="confirmLoading"
    width="800px"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="service_identity" label="服务唯一标识">
            <a-input
              v-model="formData.service_identity"
              placeholder="输入为空系统自动生成 ULID"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="name" label="服务名称">
            <a-input v-model="formData.name" placeholder="请输入服务名称" />
          </a-form-item>
        </a-col>
      </a-row>
      
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="server_identity" label="服务器标识">
            <a-input v-model="formData.server_identity" placeholder="关联服务器唯一标识" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="type" label="中间件类型">
            <a-select v-model="formData.type" placeholder="请选择中间件类型">
              <a-option value="nginx">Nginx</a-option>
              <a-option value="apache">Apache</a-option>
              <a-option value="tomcat">Tomcat</a-option>
              <a-option value="redis">Redis</a-option>
              <a-option value="kafka">Kafka</a-option>
              <a-option value="rabbitmq">RabbitMQ</a-option>
              <a-option value="elasticsearch">Elasticsearch</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="description" label="描述信息">
        <a-textarea
          v-model="formData.description"
          placeholder="请输入描述信息"
          :rows="2"
        />
      </a-form-item>

      <a-form-item field="tags" label="标签">
        <a-input v-model="formData.tags" placeholder="多个标签，逗号间隔" />
      </a-form-item>
      
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="status_url" label="状态检查URL">
            <a-input v-model="formData.status_url" placeholder="Nginx/Apache状态检查URL" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="agent_config" label="Agent配置URL">
            <a-input v-model="formData.agent_config" placeholder="完整 http(s) GET URL" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="enabled" label="启用监控">
            <a-switch v-model="formData.enabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="interval" label="采集间隔(秒)">
            <a-input-number
              v-model="formData.interval"
              placeholder="默认60秒"
              :min="10"
              :max="3600"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="collect_on" label="参与周期采集">
            <a-switch v-model="formData.collect_on" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item v-if="formData.collect_on" field="collect_interval" label="采集间隔(秒)">
            <a-input-number
              v-model="formData.collect_interval"
              placeholder="为0时使用interval"
              :min="0"
              :max="3600"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="extra" label="额外配置(JSON)">
        <a-textarea
          v-model="formData.extra"
          placeholder='JSON格式，如：{"config_path":"/etc/nginx/nginx.conf"}'
          :rows="2"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import {
  createMiddleware,
  updateMiddleware,
  type MiddlewareCreateData,
  type MiddlewareUpdateData,
} from '@/api/ops/middleware'

interface Props {
  visible: boolean
  record?: any
}

const props = withDefaults(defineProps<Props>(), {
  record: () => ({}),
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref<FormInstance>()
const confirmLoading = ref(false)

const isEdit = computed(() => !!props.record?.id)

const formData = reactive({
  service_identity: '',
  server_identity: '',
  name: '',
  category: 'middleware',
  type: '',
  description: '',
  enabled: true,
  interval: 60,
  extra: '',
  tags: '',
  status_url: '',
  agent_config: '',
  collect_on: true,
  collect_args: '',
  collect_interval: 60,
})

const rules = {
  name: [{ required: true, message: '请输入服务名称' }],
  type: [{ required: true, message: '请选择中间件类型' }],
  category: [{ required: true, message: '分类必须为middleware' }],
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (isEdit.value && props.record) {
        Object.assign(formData, {
          service_identity: props.record.service_identity || '',
          server_identity: props.record.server_identity || '',
          name: props.record.name || '',
          category: props.record.category || 'middleware',
          type: props.record.type || '',
          description: props.record.description || '',
          enabled: props.record.enabled ?? true,
          interval: props.record.interval || 60,
          extra: props.record.extra || '',
          tags: props.record.tags || '',
          status_url: props.record.status_url || '',
          agent_config: props.record.agent_config || '',
          collect_on: props.record.collect_on ?? true,
          collect_args: props.record.collect_args || '',
          collect_interval: props.record.collect_interval || 60,
        })
      } else {
        Object.assign(formData, {
          service_identity: '',
          server_identity: '',
          name: '',
          category: 'middleware',
          type: '',
          description: '',
          enabled: true,
          interval: 60,
          extra: '',
          tags: '',
          status_url: '',
          agent_config: '',
          collect_on: true,
          collect_args: '',
          collect_interval: 60,
        })
      }
    }
  }
)

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    
    confirmLoading.value = true
    
    if (isEdit.value) {
      const updateData: MiddlewareUpdateData = {
        service_identity: formData.service_identity,
        server_identity: formData.server_identity,
        name: formData.name,
        category: formData.category,
        type: formData.type,
        description: formData.description,
        enabled: formData.enabled,
        interval: formData.interval,
        extra: formData.extra,
        tags: formData.tags,
        status_url: formData.status_url,
        agent_config: formData.agent_config,
        collect_on: formData.collect_on,
        collect_args: formData.collect_args,
        collect_interval: formData.collect_interval,
      }
      await updateMiddleware(props.record.id, updateData)
      Message.success('更新成功')
    } else {
      const createData: MiddlewareCreateData = {
        service_identity: formData.service_identity,
        server_identity: formData.server_identity,
        name: formData.name,
        category: formData.category,
        type: formData.type,
        description: formData.description,
        enabled: formData.enabled,
        interval: formData.interval,
        extra: formData.extra,
        tags: formData.tags,
        status_url: formData.status_url,
        agent_config: formData.agent_config,
        collect_on: formData.collect_on,
        collect_args: formData.collect_args,
        collect_interval: formData.collect_interval,
      }
      await createMiddleware(createData)
      Message.success('创建成功')
    }
    
    emit('success')
    handleCancel()
  } catch (error) {
    console.error('操作失败:', error)
    Message.error('操作失败')
  } finally {
    confirmLoading.value = false
  }
}

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

const handleCancel = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}
</script>
