<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="输入为空系统自动生成 host:port:database"
              :disabled="isEdit"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="name" label="服务名称" required>
            <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="数据库类型" required>
            <a-select v-model="formData.type" placeholder="请选择数据库类型">
              <a-option value="MySQL">MySQL</a-option>
              <a-option value="PostgreSQL">PostgreSQL</a-option>
              <a-option value="Redis">Redis</a-option>
              <a-option value="MongoDB">MongoDB</a-option>
              <a-option value="DM">DM（达梦）</a-option>
              <a-option value="KingBase">KingBase（人大金仓）</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="host" label="主机地址" required>
            <a-input v-model="formData.host" placeholder="请输入主机地址" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="port" label="端口" required>
            <a-input-number
              v-model="formData.port"
              placeholder="请输入端口"
              :min="1"
              :max="65535"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="username" label="用户名">
            <a-input v-model="formData.username" placeholder="请输入用户名" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="password" label="密码">
            <a-input-password
              v-model="formData.password"
              placeholder="请输入密码"
            />
            <template #extra v-if="isEdit">
              <span style="color: rgb(var(--warning-6))">编辑时密码不回显，如需修改请输入新密码</span>
            </template>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="database" label="数据库名">
            <a-input v-model="formData.database" placeholder="请输入数据库名" />
          </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-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="enabled" label="启用监控">
            <a-switch v-model="formData.enabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="collect_on" label="启用进程内采集">
            <a-switch v-model="formData.collect_on" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20" v-if="formData.collect_on">
        <a-col :span="12">
          <a-form-item field="collect_interval" label="进程内采集间隔(秒)">
            <a-input-number
              v-model="formData.collect_interval"
              placeholder="默认60秒"
              :min="10"
              :max="3600"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="collect_args" label="采集参数">
            <a-input v-model="formData.collect_args" placeholder="采集参数配置" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="extra" label="额外配置(JSON)">
        <a-textarea
          v-model="formData.extra"
          placeholder='JSON格式，如：{"charset":"utf8mb4"}'
          :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 {
  createDatabase,
  updateDatabase,
  type CreateDatabaseParams,
  type UpdateDatabaseParams,
  type DatabaseType,
} from '@/api/ops/database'

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: 'database',
  type: '' as DatabaseType | '',
  host: '',
  port: 3306,
  username: '',
  password: '',
  database: '',
  description: '',
  enabled: true,
  interval: 60,
  extra: '',
  tags: '',
  collect_on: true,
  collect_args: '',
  collect_interval: 60,
})

const rules = {
  name: [{ required: true, message: '请输入服务名称' }],
  type: [{ required: true, message: '请选择数据库类型' }],
  host: [{ required: true, message: '请输入主机地址' }],
  port: [{ required: true, message: '请输入端口' }],
  category: [{ required: true, message: '分类必须为database' }],
}

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 || 'database',
          type: props.record.type || '',
          host: props.record.host || '',
          port: props.record.port || 3306,
          username: props.record.username || '',
          password: '', // 编辑时密码不回显
          database: props.record.database || '',
          description: props.record.description || '',
          enabled: props.record.enabled ?? true,
          interval: props.record.interval || 60,
          extra: props.record.extra || '',
          tags: props.record.tags || '',
          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: 'database',
          type: '',
          host: '',
          port: 3306,
          username: '',
          password: '',
          database: '',
          description: '',
          enabled: true,
          interval: 60,
          extra: '',
          tags: '',
          collect_on: true,
          collect_args: '',
          collect_interval: 60,
        })
      }
    }
  }
)

const handleOk = async () => {
  try {
    await formRef.value?.validate()

    confirmLoading.value = true

    if (isEdit.value) {
      const updateData: UpdateDatabaseParams = {
        service_identity: formData.service_identity,
        server_identity: formData.server_identity,
        name: formData.name,
        category: formData.category,
        type: formData.type as DatabaseType,
        host: formData.host,
        port: formData.port,
        username: formData.username,
        database: formData.database,
        description: formData.description,
        enabled: formData.enabled,
        interval: formData.interval,
        extra: formData.extra,
        tags: formData.tags,
        collect_on: formData.collect_on,
        collect_args: formData.collect_args,
        collect_interval: formData.collect_interval,
      }
      // 只有在编辑时输入了密码才传递
      if (formData.password) {
        updateData.password = formData.password
      }
      await updateDatabase(props.record.id, updateData)
      Message.success('更新成功')
    } else {
      const createData: CreateDatabaseParams = {
        service_identity: formData.service_identity,
        server_identity: formData.server_identity,
        name: formData.name,
        category: formData.category,
        type: formData.type as DatabaseType,
        host: formData.host,
        port: formData.port,
        username: formData.username,
        password: formData.password,
        database: formData.database,
        description: formData.description,
        enabled: formData.enabled,
        interval: formData.interval,
        extra: formData.extra,
        tags: formData.tags,
        collect_on: formData.collect_on,
        collect_args: formData.collect_args,
        collect_interval: formData.collect_interval,
      }
      await createDatabase(createData)
      Message.success('创建成功')
    }

    emit('success')
    handleCancel()
  } catch (error: any) {
    console.error('操作失败:', error)
    if (error?.response?.data?.message) {
      Message.error(error.response.data.message)
    } else {
      Message.error('操作失败')
    }
  } finally {
    confirmLoading.value = false
  }
}

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

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