<template>
  <div class="security-settings-page">
    <div class="settings-container">
      <Card title="安全设置" :loading="loading">
        <Tabs v-model:activeKey="activeTab" type="card">
          <!-- 密码策略 -->
          <TabPane key="password" tab="密码策略">
            <BasicForm
              ref="passwordFormRef"
              :schemas="passwordSchemas"
              :model="passwordForm"
              :label-width="120"
              :action-col-options="{ span: 24 }"
              :submit-button-options="{ text: '保存设置', loading: saveLoading }"
              :reset-button-options="{ text: '重置设置' }"
              @submit="handleSavePassword"
              @reset="handleResetPassword"
            />
          </TabPane>

          <!-- 登录安全 -->
          <TabPane key="login" tab="登录安全">
            <BasicForm
              ref="loginFormRef"
              :schemas="loginSchemas"
              :model="loginForm"
              :label-width="120"
              :action-col-options="{ span: 24 }"
              :submit-button-options="{ text: '保存设置', loading: saveLoading }"
              :reset-button-options="{ text: '重置设置' }"
              @submit="handleSaveLogin"
              @reset="handleResetLogin"
            />
          </TabPane>

          <!-- IP访问控制 -->
          <TabPane key="ip" tab="IP访问控制">
            <BasicForm
              ref="ipFormRef"
              :schemas="ipSchemas"
              :model="ipForm"
              :label-width="120"
              :action-col-options="{ span: 24 }"
              :submit-button-options="{ text: '保存设置', loading: saveLoading }"
              :reset-button-options="{ text: '重置设置' }"
              @submit="handleSaveIp"
              @reset="handleResetIp"
            >
              <template #testIpAction>
                <Button type="primary" :loading="testIpLoading" @click="handleTestIp">
                  测试当前IP
                </Button>
              </template>
            </BasicForm>
          </TabPane>

          <!-- 操作审计 -->
          <TabPane key="audit" tab="操作审计">
            <BasicForm
              ref="auditFormRef"
              :schemas="auditSchemas"
              :model="auditForm"
              :label-width="120"
              :action-col-options="{ span: 24 }"
              :submit-button-options="{ text: '保存设置', loading: saveLoading }"
              :reset-button-options="{ text: '重置设置' }"
              @submit="handleSaveAudit"
              @reset="handleResetAudit"
            >
              <template #auditLogAction>
                <Button type="default" @click="handleViewAuditLog">
                  查看审计日志
                </Button>
              </template>
            </BasicForm>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Card, Tabs, TabPane, Button, message } from 'ant-design-vue';
import { BasicForm, FormSchema } from '@/components/Form';
import {
  getSecurityConfigApi,
  updateSecurityConfigApi,
  resetSecurityConfigApi,
  testIpAccessApi,
  type SecurityConfig,
} from '@/api/common/security';

// 响应式数据
const loading = ref(false);
const saveLoading = ref(false);
const testIpLoading = ref(false);
const activeTab = ref('password');

// 表单引用
const passwordFormRef = ref();
const loginFormRef = ref();
const ipFormRef = ref();
const auditFormRef = ref();

// 表单数据
const passwordForm = reactive({
  enablePasswordStrength: true,
  minPasswordLength: 8,
  requireLowercase: true,
  requireUppercase: true,
  requireNumbers: true,
  requireSpecialChars: true,
  forbidCommonPasswords: true,
  passwordExpireDays: 90,
  passwordHistoryLimit: 5,
  forcePasswordChange: false,
});

const loginForm = reactive({
  maxLoginAttempts: 5,
  lockoutDuration: 30,
  enableLoginCaptcha: true,
  captchaTriggerAttempts: 3,
  enableTwoFactor: false,
  forceTwoFactor: false,
  sessionTimeout: 120,
  enableSingleSignOn: false,
  recordLoginLog: true,
});

const ipForm = reactive({
  enableIpControl: false,
  accessMode: 'whitelist',
  ipWhitelist: [''],
  ipBlacklist: [''],
  adminIpWhitelist: [''],
});

const auditForm = reactive({
  enableAudit: true,
  auditLoginLogout: true,
  auditUserManagement: true,
  auditRoleManagement: true,
  auditPermissionManagement: true,
  auditSystemConfig: true,
  auditDataExport: true,
  auditFileUpload: true,
  auditSensitiveOperations: true,
  auditLogRetention: 365,
  enableSecondaryConfirm: true,
  confirmDeleteUser: true,
  confirmResetPassword: true,
  confirmModifyRole: true,
  confirmSystemBackup: true,
  confirmSystemRestore: true,
  confirmClearData: true,
  enableAnomalyDetection: true,
});

// 表单配置
const passwordSchemas: FormSchema[] = [
  {
    field: 'enablePasswordStrength',
    label: '启用密码强度检查',
    component: 'Switch',
    helpMessage: '开启后将检查密码复杂度',
  },
  {
    field: 'minPasswordLength',
    label: '最小密码长度',
    component: 'InputNumber',
    componentProps: {
      min: 6,
      max: 32,
      placeholder: '请输入最小密码长度',
    },
    rules: [
      { required: true, message: '请输入最小密码长度' },
      { type: 'number', min: 6, max: 32, message: '密码长度范围为 6-32 位' },
    ],
  },
  {
    field: 'requireLowercase',
    label: '要求小写字母',
    component: 'Switch',
    helpMessage: '密码必须包含小写字母',
  },
  {
    field: 'requireUppercase',
    label: '要求大写字母',
    component: 'Switch',
    helpMessage: '密码必须包含大写字母',
  },
  {
    field: 'requireNumbers',
    label: '要求数字',
    component: 'Switch',
    helpMessage: '密码必须包含数字',
  },
  {
    field: 'requireSpecialChars',
    label: '要求特殊字符',
    component: 'Switch',
    helpMessage: '密码必须包含特殊字符',
  },
  {
    field: 'forbidCommonPasswords',
    label: '禁止常见密码',
    component: 'Switch',
    helpMessage: '禁止使用常见的弱密码',
  },
  {
    field: 'passwordExpireDays',
    label: '密码有效期（天）',
    component: 'InputNumber',
    componentProps: {
      min: 0,
      max: 365,
      placeholder: '请输入密码有效期',
    },
    helpMessage: '0表示永不过期',
    rules: [
      { required: true, message: '请输入密码有效期' },
      { type: 'number', min: 0, max: 365, message: '密码有效期范围为 0-365 天' },
    ],
  },
  {
    field: 'passwordHistoryLimit',
    label: '密码重复使用限制',
    component: 'InputNumber',
    componentProps: {
      min: 0,
      max: 20,
      placeholder: '请输入历史密码限制数量',
    },
    helpMessage: '禁止重复使用最近N个密码，0表示不限制',
    rules: [
      { type: 'number', min: 0, max: 20, message: '历史密码限制范围为 0-20 个' },
    ],
  },
  {
    field: 'forcePasswordChange',
    label: '强制定期修改密码',
    component: 'Switch',
    helpMessage: '强制用户在密码过期前修改密码',
  },
];

const loginSchemas: FormSchema[] = [
  {
    field: 'maxLoginAttempts',
    label: '最大登录失败次数',
    component: 'InputNumber',
    componentProps: {
      min: 3,
      max: 20,
      placeholder: '请输入最大登录失败次数',
    },
    rules: [
      { required: true, message: '请输入最大登录失败次数' },
      { type: 'number', min: 3, max: 20, message: '登录失败次数范围为 3-20 次' },
    ],
  },
  {
    field: 'lockoutDuration',
    label: '账户锁定时间（分钟）',
    component: 'InputNumber',
    componentProps: {
      min: 5,
      max: 1440,
      placeholder: '请输入账户锁定时间',
    },
    rules: [
      { required: true, message: '请输入账户锁定时间' },
      { type: 'number', min: 5, max: 1440, message: '锁定时间范围为 5-1440 分钟' },
    ],
  },
  {
    field: 'enableLoginCaptcha',
    label: '启用登录验证码',
    component: 'Switch',
    helpMessage: '登录时显示验证码',
  },
  {
    field: 'captchaTriggerAttempts',
    label: '验证码触发条件',
    component: 'InputNumber',
    componentProps: {
      min: 1,
      max: 10,
      placeholder: '请输入触发验证码的失败次数',
    },
    helpMessage: '登录失败多少次后显示验证码',
    rules: [
      { type: 'number', min: 1, max: 10, message: '触发条件范围为 1-10 次' },
    ],
  },
  {
    field: 'enableTwoFactor',
    label: '启用双因子认证',
    component: 'Switch',
    helpMessage: '启用短信或邮箱二次验证',
  },
  {
    field: 'forceTwoFactor',
    label: '强制双因子认证',
    component: 'Switch',
    helpMessage: '强制所有用户启用双因子认证',
  },
  {
    field: 'sessionTimeout',
    label: '会话超时时间（分钟）',
    component: 'InputNumber',
    componentProps: {
      min: 30,
      max: 1440,
      placeholder: '请输入会话超时时间',
    },
    rules: [
      { required: true, message: '请输入会话超时时间' },
      { type: 'number', min: 30, max: 1440, message: '会话超时时间范围为 30-1440 分钟' },
    ],
  },
  {
    field: 'enableSingleSignOn',
    label: '启用单点登录',
    component: 'Switch',
    helpMessage: '同一账户只能在一个地方登录',
  },
  {
    field: 'recordLoginLog',
    label: '记录登录日志',
    component: 'Switch',
    helpMessage: '记录用户登录和登出日志',
  },
];

const ipSchemas: FormSchema[] = [
  {
    field: 'enableIpControl',
    label: '启用IP访问控制',
    component: 'Switch',
    helpMessage: '启用后将根据IP地址控制访问权限',
  },
  {
    field: 'accessMode',
    label: '访问控制模式',
    component: 'RadioGroup',
    componentProps: {
      options: [
        { label: '白名单模式', value: 'whitelist' },
        { label: '黑名单模式', value: 'blacklist' },
      ],
    },
    helpMessage: '白名单：仅允许列表中的IP访问；黑名单：禁止列表中的IP访问',
  },
  {
    field: 'ipWhitelist',
    label: 'IP白名单',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 4,
      placeholder: '请输入IP地址，每行一个\n支持格式：192.168.1.1 或 192.168.1.0/24',
    },
    helpMessage: '每行一个IP地址或IP段，支持CIDR格式',
    show: ({ model }) => model.accessMode === 'whitelist',
  },
  {
    field: 'ipBlacklist',
    label: 'IP黑名单',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 4,
      placeholder: '请输入IP地址，每行一个\n支持格式：192.168.1.1 或 192.168.1.0/24',
    },
    helpMessage: '每行一个IP地址或IP段，支持CIDR格式',
    show: ({ model }) => model.accessMode === 'blacklist',
  },
  {
    field: 'adminIpWhitelist',
    label: '管理员IP白名单',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 4,
      placeholder: '请输入管理员IP地址，每行一个\n支持格式：192.168.1.1 或 192.168.1.0/24',
    },
    helpMessage: '管理员专用IP白名单，优先级高于普通IP控制',
  },
  {
    field: 'testIpAction',
    label: '',
    component: 'Input',
    slot: 'testIpAction',
  },
];

const auditSchemas: FormSchema[] = [
  {
    field: 'enableAudit',
    label: '启用操作审计',
    component: 'Switch',
    helpMessage: '记录用户的重要操作行为',
  },
  {
    field: 'auditEvents',
    label: '审计事件类型',
    component: 'CheckboxGroup',
    componentProps: {
      options: [
        { label: '登录登出', value: 'loginLogout' },
        { label: '用户管理', value: 'userManagement' },
        { label: '角色管理', value: 'roleManagement' },
        { label: '权限管理', value: 'permissionManagement' },
        { label: '系统配置', value: 'systemConfig' },
        { label: '数据导出', value: 'dataExport' },
        { label: '文件上传', value: 'fileUpload' },
        { label: '敏感操作', value: 'sensitiveOperations' },
      ],
    },
    helpMessage: '选择需要审计的事件类型',
  },
  {
    field: 'auditLogRetention',
    label: '审计日志保留期（天）',
    component: 'InputNumber',
    componentProps: {
      min: 30,
      max: 3650,
      placeholder: '请输入日志保留期',
    },
    rules: [
      { required: true, message: '请输入审计日志保留期' },
      { type: 'number', min: 30, max: 3650, message: '日志保留期范围为 30-3650 天' },
    ],
  },
  {
    field: 'enableSecondaryConfirm',
    label: '敏感操作二次确认',
    component: 'Switch',
    helpMessage: '敏感操作需要二次确认',
  },
  {
    field: 'sensitiveOperations',
    label: '敏感操作类型',
    component: 'CheckboxGroup',
    componentProps: {
      options: [
        { label: '删除用户', value: 'deleteUser' },
        { label: '重置密码', value: 'resetPassword' },
        { label: '修改角色', value: 'modifyRole' },
        { label: '系统备份', value: 'systemBackup' },
        { label: '系统恢复', value: 'systemRestore' },
        { label: '清除数据', value: 'clearData' },
      ],
    },
    helpMessage: '选择需要二次确认的敏感操作',
    show: ({ model }) => model.enableSecondaryConfirm,
  },
  {
    field: 'enableAnomalyDetection',
    label: '异常行为检测',
    component: 'Switch',
    helpMessage: '检测并记录异常的用户行为',
  },
  {
    field: 'auditLogAction',
    label: '',
    component: 'Input',
    slot: 'auditLogAction',
  },
];

// 方法
const loadSettings = async () => {
  loading.value = true;
  try {
    const config = await getSecurityConfigApi();
    
    // 更新表单数据
    Object.assign(passwordForm, config.password || {});
    Object.assign(loginForm, config.login || {});
    Object.assign(ipForm, {
      ...config.ip,
      ipWhitelist: config.ip?.ipWhitelist?.join('\n') || '',
      ipBlacklist: config.ip?.ipBlacklist?.join('\n') || '',
      adminIpWhitelist: config.ip?.adminIpWhitelist?.join('\n') || '',
    });
    
    // 处理审计事件类型
    const auditEvents = [];
    if (config.audit?.auditLoginLogout) auditEvents.push('loginLogout');
    if (config.audit?.auditUserManagement) auditEvents.push('userManagement');
    if (config.audit?.auditRoleManagement) auditEvents.push('roleManagement');
    if (config.audit?.auditPermissionManagement) auditEvents.push('permissionManagement');
    if (config.audit?.auditSystemConfig) auditEvents.push('systemConfig');
    if (config.audit?.auditDataExport) auditEvents.push('dataExport');
    if (config.audit?.auditFileUpload) auditEvents.push('fileUpload');
    if (config.audit?.auditSensitiveOperations) auditEvents.push('sensitiveOperations');
    
    const sensitiveOperations = [];
    if (config.audit?.confirmDeleteUser) sensitiveOperations.push('deleteUser');
    if (config.audit?.confirmResetPassword) sensitiveOperations.push('resetPassword');
    if (config.audit?.confirmModifyRole) sensitiveOperations.push('modifyRole');
    if (config.audit?.confirmSystemBackup) sensitiveOperations.push('systemBackup');
    if (config.audit?.confirmSystemRestore) sensitiveOperations.push('systemRestore');
    if (config.audit?.confirmClearData) sensitiveOperations.push('clearData');
    
    Object.assign(auditForm, {
      ...config.audit,
      auditEvents,
      sensitiveOperations,
    });
  } catch (error) {
    message.error('加载安全设置失败');
  } finally {
    loading.value = false;
  }
};

const handleSavePassword = async (values: any) => {
  saveLoading.value = true;
  try {
    await updateSecurityConfigApi({
      type: 'password',
      config: values,
    });
    message.success('密码策略保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saveLoading.value = false;
  }
};

const handleSaveLogin = async (values: any) => {
  saveLoading.value = true;
  try {
    await updateSecurityConfigApi({
      type: 'login',
      config: values,
    });
    message.success('登录安全保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saveLoading.value = false;
  }
};

const handleSaveIp = async (values: any) => {
  saveLoading.value = true;
  try {
    // 处理IP列表
    const config = {
      ...values,
      ipWhitelist: values.ipWhitelist ? values.ipWhitelist.split('\n').filter((ip: string) => ip.trim()) : [],
      ipBlacklist: values.ipBlacklist ? values.ipBlacklist.split('\n').filter((ip: string) => ip.trim()) : [],
      adminIpWhitelist: values.adminIpWhitelist ? values.adminIpWhitelist.split('\n').filter((ip: string) => ip.trim()) : [],
    };
    
    await updateSecurityConfigApi({
      type: 'ip',
      config,
    });
    message.success('IP访问控制保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saveLoading.value = false;
  }
};

const handleSaveAudit = async (values: any) => {
  saveLoading.value = true;
  try {
    // 处理审计事件类型
    const config = {
      ...values,
      auditLoginLogout: values.auditEvents?.includes('loginLogout') || false,
      auditUserManagement: values.auditEvents?.includes('userManagement') || false,
      auditRoleManagement: values.auditEvents?.includes('roleManagement') || false,
      auditPermissionManagement: values.auditEvents?.includes('permissionManagement') || false,
      auditSystemConfig: values.auditEvents?.includes('systemConfig') || false,
      auditDataExport: values.auditEvents?.includes('dataExport') || false,
      auditFileUpload: values.auditEvents?.includes('fileUpload') || false,
      auditSensitiveOperations: values.auditEvents?.includes('sensitiveOperations') || false,
      confirmDeleteUser: values.sensitiveOperations?.includes('deleteUser') || false,
      confirmResetPassword: values.sensitiveOperations?.includes('resetPassword') || false,
      confirmModifyRole: values.sensitiveOperations?.includes('modifyRole') || false,
      confirmSystemBackup: values.sensitiveOperations?.includes('systemBackup') || false,
      confirmSystemRestore: values.sensitiveOperations?.includes('systemRestore') || false,
      confirmClearData: values.sensitiveOperations?.includes('clearData') || false,
    };
    
    await updateSecurityConfigApi({
      type: 'audit',
      config,
    });
    message.success('操作审计保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saveLoading.value = false;
  }
};

const handleResetPassword = async () => {
  try {
    await resetSecurityConfigApi('password');
    await loadSettings();
    message.success('密码策略已重置');
  } catch (error) {
    message.error('重置失败');
  }
};

const handleResetLogin = async () => {
  try {
    await resetSecurityConfigApi('login');
    await loadSettings();
    message.success('登录安全已重置');
  } catch (error) {
    message.error('重置失败');
  }
};

const handleResetIp = async () => {
  try {
    await resetSecurityConfigApi('ip');
    await loadSettings();
    message.success('IP访问控制已重置');
  } catch (error) {
    message.error('重置失败');
  }
};

const handleResetAudit = async () => {
  try {
    await resetSecurityConfigApi('audit');
    await loadSettings();
    message.success('操作审计已重置');
  } catch (error) {
    message.error('重置失败');
  }
};

const handleTestIp = async () => {
  testIpLoading.value = true;
  try {
    const result = await testIpAccessApi();
    if (result.allowed) {
      message.success(`当前IP ${result.ip} 允许访问`);
    } else {
      message.warning(`当前IP ${result.ip} 被拒绝访问`);
    }
  } catch (error) {
    message.error('测试IP失败');
  } finally {
    testIpLoading.value = false;
  }
};

const handleViewAuditLog = () => {
  // 跳转到审计日志页面
  console.log('查看审计日志');
};

// 生命周期
onMounted(() => {
  loadSettings();
});
</script>

<style scoped>
.security-settings-page {
  padding: 20px;
}

.settings-container {
  max-width: 1200px;
  margin: 0 auto;
}
</style>