<template>
  <div class="system-settings-container">
    <el-card shadow="hover" class="settings-card">
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 钉钉配置 -->
        <el-tab-pane label="钉钉免密登录" name="dingtalk">
          <div class="tab-content">
            <el-alert
              title="钉钉免密登录配置说明"
              type="info"
              :closable="false"
              show-icon
              style="margin-bottom: 20px;"
            >
              <template #default>
                <p>配置后，员工可以通过钉钉客户端直接登录系统，无需输入用户名密码。</p>
                <p style="margin-top: 8px;">
                  <a href="https://open-dev.dingtalk.com" target="_blank" class="link">
                    前往钉钉开放平台获取配置 →
                  </a>
                </p>
              </template>
            </el-alert>

            <el-form 
              ref="dingtalkFormRef" 
              :model="dingtalkForm" 
              :rules="dingtalkRules" 
              label-width="140px"
              v-loading="loading"
            >
              <el-form-item label="启用钉钉登录">
                <el-switch 
                  v-model="dingtalkForm.enabled" 
                  active-text="已启用"
                  inactive-text="已禁用"
                />
              </el-form-item>

              <el-divider content-position="left">钉钉应用配置</el-divider>

              <el-form-item label="AppKey" prop="app_key">
                <el-input 
                  v-model="dingtalkForm.app_key" 
                  placeholder="请输入钉钉应用的AppKey"
                  style="width: 400px;"
                />
              </el-form-item>

              <el-form-item label="AppSecret" prop="app_secret">
                <el-input 
                  v-model="dingtalkForm.app_secret" 
                  type="password"
                  show-password
                  :placeholder="dingtalkForm.app_secret_masked || '请输入钉钉应用的AppSecret'"
                  style="width: 400px;"
                />
                <span class="form-tip" v-if="dingtalkForm.app_secret_masked && !dingtalkForm.app_secret">
                  当前值: {{ dingtalkForm.app_secret_masked }}（如需修改请重新输入）
                </span>
              </el-form-item>

              <el-form-item label="AgentId" prop="agent_id">
                <el-input 
                  v-model="dingtalkForm.agent_id" 
                  placeholder="请输入钉钉应用的AgentId"
                  style="width: 400px;"
                />
              </el-form-item>

              <el-form-item label="CorpId" prop="corp_id">
                <el-input 
                  v-model="dingtalkForm.corp_id" 
                  placeholder="请输入钉钉企业的CorpId"
                  style="width: 400px;"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="saveDingtalkConfig" :loading="saving">
                  保存配置
                </el-button>
                <el-button @click="loadDingtalkConfig">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 其他设置（预留） -->
        <el-tab-pane label="其他设置" name="other" disabled>
          <div class="tab-content">
            <el-empty description="暂无其他设置项" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { request } from '@/api/request'

const activeTab = ref('dingtalk')
const loading = ref(false)
const saving = ref(false)
const dingtalkFormRef = ref<FormInstance>()

// 钉钉配置表单
const dingtalkForm = reactive({
  enabled: false,
  app_key: '',
  app_secret: '',
  app_secret_masked: '',  // 用于显示脱敏后的值
  agent_id: '',
  corp_id: '',
})

// 表单验证规则
const dingtalkRules = reactive<FormRules>({
  app_key: [
    { required: false, message: '请输入AppKey', trigger: 'blur' }
  ],
  agent_id: [
    { required: false, message: '请输入AgentId', trigger: 'blur' }
  ],
  corp_id: [
    { required: false, message: '请输入CorpId', trigger: 'blur' }
  ]
})

/**
 * 加载钉钉配置
 */
const loadDingtalkConfig = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/v1/settings/dingtalk')
    if (response.code === 200 && response.data) {
      dingtalkForm.enabled = response.data.enabled || false
      dingtalkForm.app_key = response.data.app_key || ''
      dingtalkForm.app_secret = ''  // 不回显密钥
      dingtalkForm.app_secret_masked = response.data.app_secret_masked || ''
      dingtalkForm.agent_id = response.data.agent_id || ''
      dingtalkForm.corp_id = response.data.corp_id || ''
    }
  } catch (error: any) {
    console.error('加载钉钉配置失败:', error)
    ElMessage.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

/**
 * 保存钉钉配置
 */
const saveDingtalkConfig = async () => {
  if (!dingtalkFormRef.value) return
  
  await dingtalkFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        // 构建更新数据，只发送有值的字段
        const updateData: any = {
          enabled: dingtalkForm.enabled,
        }
        
        if (dingtalkForm.app_key) {
          updateData.app_key = dingtalkForm.app_key
        }
        if (dingtalkForm.app_secret) {
          updateData.app_secret = dingtalkForm.app_secret
        }
        if (dingtalkForm.agent_id) {
          updateData.agent_id = dingtalkForm.agent_id
        }
        if (dingtalkForm.corp_id) {
          updateData.corp_id = dingtalkForm.corp_id
        }
        
        const response = await request.put('/api/v1/settings/dingtalk', updateData)
        if (response.code === 200) {
          ElMessage.success('配置保存成功')
          // 重新加载配置
          await loadDingtalkConfig()
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error: any) {
        console.error('保存钉钉配置失败:', error)
        ElMessage.error('保存配置失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 页面加载时获取配置
onMounted(() => {
  loadDingtalkConfig()
})
</script>

<style lang="scss" scoped>
.system-settings-container {
  padding: 20px;

  .settings-card {
    .card-header {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .tab-content {
    padding: 20px;
    min-height: 400px;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-left: 12px;
  }

  .link {
    color: #409eff;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }

  :deep(.el-divider__text) {
    font-size: 14px;
    color: #606266;
  }
}
</style>
