<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="employee_sync">
          <div class="tab-content">
            <el-alert
              title="员工同步配置说明"
              type="info"
              :closable="false"
              show-icon
              style="margin-bottom: 20px;"
            >
              <template #default>
                <p>通过钉钉开放 API 自动同步组织架构和员工信息（姓名、手机号、部门、岗位等）。</p>
                <p style="margin-top: 8px;">同步的员工将自动创建系统账号，初始密码为 123456。</p>
                <p style="margin-top: 8px; color: #E6A23C;">注意：员工同步复用「钉钉免密登录」的 API 凭证配置。</p>
              </template>
            </el-alert>

            <el-form 
              ref="syncFormRef" 
              :model="syncForm" 
              label-width="140px"
              v-loading="syncLoading"
            >
              <el-form-item label="启用自动同步">
                <el-switch 
                  v-model="syncForm.enabled" 
                  active-text="已启用"
                  inactive-text="已禁用"
                />
                <span class="form-tip">启用后将每日自动从钉钉同步员工数据</span>
              </el-form-item>

              <el-form-item label="钉钉 API 状态">
                <el-tag :type="syncForm.configured ? 'success' : 'warning'">
                  {{ syncForm.configured ? '已配置' : '未配置' }}
                </el-tag>
                <span class="form-tip" v-if="!syncForm.configured">
                  请先在「钉钉免密登录」页签配置 API 凭证
                </span>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="saveSyncConfig" :loading="syncSaving">
                  保存配置
                </el-button>
                <el-button @click="testSyncConnection" :loading="syncTesting" :disabled="!syncForm.configured">
                  测试连接
                </el-button>
                <el-button 
                  type="success" 
                  @click="triggerSync" 
                  :loading="syncing" 
                  :disabled="!syncForm.configured"
                >
                  立即同步
                </el-button>
              </el-form-item>
            </el-form>
          </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 syncLoading = ref(false)
const syncSaving = ref(false)
const syncTesting = ref(false)
const syncing = ref(false)
const syncFormRef = ref<FormInstance>()

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

// 员工同步配置表单（复用钉钉免密登录配置）
const syncForm = reactive({
  enabled: false,
  configured: false,  // 钉钉 API 是否已配置
})

// 表单验证规则
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 syncRules = reactive<FormRules>({})

/**
 * 加载钉钉配置
 */
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
      }
    }
  })
}

/**
 * 加载员工同步配置（复用钉钉免密登录配置）
 */
const loadSyncConfig = async () => {
  syncLoading.value = true
  try {
    const response = await request.get('/api/v1/settings/employee-sync')
    if (response.code === 200 && response.data) {
      syncForm.enabled = response.data.enabled || false
      syncForm.configured = response.data.configured || false
    }
  } catch (error: any) {
    console.error('加载员工同步配置失败:', error)
  } finally {
    syncLoading.value = false
  }
}

/**
 * 保存员工同步配置（仅开关）
 */
const saveSyncConfig = async () => {
  syncSaving.value = true
  try {
    const response = await request.put('/api/v1/settings/employee-sync', {
      enabled: syncForm.enabled,
    })
    if (response.code === 200) {
      ElMessage.success('配置保存成功')
      await loadSyncConfig()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存员工同步配置失败:', error)
    ElMessage.error('保存配置失败')
  } finally {
    syncSaving.value = false
  }
}

/**
 * 测试员工同步数据库连接
 */
const testSyncConnection = async () => {
  syncTesting.value = true
  try {
    const response = await request.post('/api/v1/settings/employee-sync/test')
    if (response.code === 200) {
      ElMessage.success(response.message || '连接成功')
    } else {
      ElMessage.error(response.message || '连接失败')
    }
  } catch (error: any) {
    console.error('测试连接失败:', error)
    ElMessage.error('测试连接失败')
  } finally {
    syncTesting.value = false
  }
}

/**
 * 立即执行员工同步
 */
const triggerSync = async () => {
  syncing.value = true
  try {
    const response = await request.post('/api/v1/employee-sync/sync')
    if (response.success) {
      const data = response.data
      const created = data.users_created || 0
      const existing = data.users_existing || 0
      const restored = data.users_restored || 0
      const departed = data.users_departed || 0
      const skipped = data.users_skipped || 0
      
      let msg = `同步完成！钉钉在职 ${data.total_employees || 0} 人`
      if (created > 0) msg += `，新增 ${created} 人`
      if (existing > 0) msg += `，已存在 ${existing} 人`
      if (restored > 0) msg += `，恢复 ${restored} 人`
      if (departed > 0) msg += `，离职 ${departed} 人`
      if (skipped > 0) msg += `，跳过 ${skipped} 人`
      
      ElMessage.success(msg)
    } else {
      ElMessage.error(response.message || '同步失败')
    }
  } catch (error: any) {
    console.error('员工同步失败:', error)
    ElMessage.error(error?.response?.data?.detail || '员工同步失败')
  } finally {
    syncing.value = false
  }
}

// 页面加载时获取配置
onMounted(() => {
  loadDingtalkConfig()
  loadSyncConfig()
})
</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>
