<!--
  页面名称：Settings.vue
  页面描述：系统配置页面（钉钉对接配置）
  路径：/system/settings

  @author czj
  @date 2026-08-13
-->
<template>
  <div class="settings-page">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>钉钉对接配置</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="140px"
        label-position="right"
        style="max-width: 600px"
      >
        <el-form-item label="AppKey" prop="app_key">
          <el-input
            v-model="form.app_key"
            type="password"
            show-password
            placeholder="请输入钉钉应用 AppKey"
            clearable
          />
        </el-form-item>

        <el-form-item label="AppSecret" prop="app_secret">
          <el-input
            v-model="form.app_secret"
            type="password"
            show-password
            placeholder="请输入钉钉应用 AppSecret"
            clearable
          />
        </el-form-item>

        <el-form-item label="AgentId" prop="agent_id">
          <el-input-number
            v-model="form.agent_id"
            :min="0"
            :max="999999999"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="saving" @click="handleSave">
            {{ saving ? '保存中...' : '保存配置' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
/**
 * 系统配置页面
 *
 * 功能：
 * 1. 加载时自动获取当前钉钉对接配置（从数据库 / 环境变量回退）
 * 2. 修改后保存到数据库，重启后持久化
 */

import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { systemApi } from '@/api/system'

// ==================== 类型定义 ====================

interface DingTalkConfigForm {
  app_key: string
  app_secret: string
  agent_id: number
}

// ==================== 响应式数据 ====================

const formRef = ref()
const saving = ref(false)

const form = reactive<DingTalkConfigForm>({
  app_key: '',
  app_secret: '',
  agent_id: 0,
})

/** 原始数据快照，用于重置 */
let originalSnapshot = ''

// ==================== 表单校验规则 ====================

const rules = {
  app_key: [{ required: true, message: '请输入钉钉 AppKey', trigger: 'blur' }],
  app_secret: [{ required: true, message: '请输入钉钉 AppSecret', trigger: 'blur' }],
  agent_id: [{ required: true, message: '请输入钉钉 AgentId', trigger: 'blur' }],
}

// ==================== 方法 ====================

/** 加载配置 */
async function loadConfig() {
  try {
    const res = await systemApi.getDingTalkConfig()
    Object.assign(form, res)
    originalSnapshot = JSON.stringify(res)
  } catch (err: any) {
    ElMessage.error('加载钉钉配置失败：' + (err?.message || '未知错误'))
  }
}

/** 保存配置 */
async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  saving.value = true
  try {
    await systemApi.updateDingTalkConfig({
      app_key: form.app_key,
      app_secret: form.app_secret,
      agent_id: form.agent_id,
    })
    ElMessage.success('钉钉配置已保存')
    originalSnapshot = JSON.stringify({ ...form })
  } catch (err: any) {
    ElMessage.error('保存钉钉配置失败：' + (err?.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

/** 重置表单到加载时的值 */
function handleReset() {
  const snapshot = JSON.parse(originalSnapshot)
  Object.assign(form, snapshot)
  formRef.value?.clearValidate()
}

// ==================== 生命周期 ====================

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

<style scoped>
.settings-page {
  max-width: 800px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
}
</style>