<template>
  <div class="settings-page">
    <a-card title="系统设置" :bordered="false">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="basic" tab="基本设置">
          <a-form
            :model="basicSettings"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="系统名称">
              <a-input v-model:value="basicSettings.systemName" />
            </a-form-item>
            <a-form-item label="系统LOGO">
              <a-upload
                list-type="picture-card"
                :max-count="1"
                :file-list="fileList"
                @change="handleLogoChange"
              >
                <div v-if="fileList.length === 0">
                  <PlusOutlined />
                  <div style="margin-top: 8px">上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="系统简介">
              <a-textarea v-model:value="basicSettings.systemDesc" :rows="4" />
            </a-form-item>
            <a-form-item label="联系电话">
              <a-input v-model:value="basicSettings.contactPhone" />
            </a-form-item>
            <a-form-item label="联系邮箱">
              <a-input v-model:value="basicSettings.contactEmail" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" :loading="saving" @click="saveBasicSettings">
                保存设置
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="security" tab="安全设置">
          <a-form
            :model="securitySettings"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="密码强度">
              <a-radio-group v-model:value="securitySettings.passwordStrength">
                <a-radio value="low">低（6位以上）</a-radio>
                <a-radio value="medium">中（8位以上，包含数字和字母）</a-radio>
                <a-radio value="high">高（10位以上，包含特殊字符）</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="登录失败限制">
              <a-input-number
                v-model:value="securitySettings.maxLoginAttempts"
                :min="3"
                :max="10"
              />
              <span style="margin-left: 8px">次失败后锁定账号</span>
            </a-form-item>
            <a-form-item label="Token有效期">
              <a-select v-model:value="securitySettings.tokenExpire" style="width: 200px">
                <a-select-option value="1d">1天</a-select-option>
                <a-select-option value="7d">7天</a-select-option>
                <a-select-option value="30d">30天</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="强制HTTPS">
              <a-switch v-model:checked="securitySettings.forceHttps" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" :loading="saving" @click="saveSecuritySettings">
                保存设置
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="notification" tab="通知设置">
          <a-form
            :model="notificationSettings"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="邮件通知">
              <a-switch v-model:checked="notificationSettings.emailEnabled" />
            </a-form-item>
            <a-form-item label="邮件服务器">
              <a-input v-model:value="notificationSettings.smtpHost" placeholder="smtp.example.com" />
            </a-form-item>
            <a-form-item label="邮件端口">
              <a-input-number v-model:value="notificationSettings.smtpPort" :min="1" :max="65535" />
            </a-form-item>
            <a-form-item label="发件人邮箱">
              <a-input v-model:value="notificationSettings.fromEmail" />
            </a-form-item>
            <a-form-item label="短信通知">
              <a-switch v-model:checked="notificationSettings.smsEnabled" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" :loading="saving" @click="saveNotificationSettings">
                保存设置
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="storage" tab="存储设置">
          <a-form
            :model="storageSettings"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-form-item label="存储类型">
              <a-radio-group v-model:value="storageSettings.storageType">
                <a-radio value="local">本地存储</a-radio>
                <a-radio value="oss">阿里云OSS</a-radio>
                <a-radio value="cos">腾讯云COS</a-radio>
                <a-radio value="s3">AWS S3</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="上传限制">
              <a-input-number
                v-model:value="storageSettings.maxFileSize"
                :min="1"
                :max="500"
              />
              <span style="margin-left: 8px">MB</span>
            </a-form-item>
            <a-form-item label="允许的文件类型">
              <a-input v-model:value="storageSettings.allowedTypes" placeholder=".jpg,.png,.pdf,.doc,.docx" />
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
              <a-button type="primary" :loading="saving" @click="saveStorageSettings">
                保存设置
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import type { UploadFile } from 'ant-design-vue';
import { getAdminSettings, updateAdminSettings } from '@/api/admin';

const activeTab = ref('basic');
const saving = ref(false);
const loading = ref(false);
const fileList = ref<UploadFile[]>([]);

const basicSettings = ref({
  systemName: '',
  systemDesc: '',
  contactPhone: '',
  contactEmail: '',
  systemLogo: '',
});

const securitySettings = ref({
  passwordStrength: 'medium',
  maxLoginAttempts: 5,
  tokenExpire: '7d',
  forceHttps: false,
});

const notificationSettings = ref({
  emailEnabled: true,
  smtpHost: '',
  smtpPort: 465,
  fromEmail: '',
  smsEnabled: false,
});

const storageSettings = ref({
  storageType: 'local',
  maxFileSize: 100,
  allowedTypes: '.jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.ppt,.pptx',
});

// Load settings on mount
const loadSettings = async () => {
  loading.value = true;
  try {
    const settings = await getAdminSettings();

    // Basic settings
    basicSettings.value = {
      systemName: settings.systemName || '',
      systemDesc: settings.systemDesc || '',
      contactPhone: settings.contactPhone || '',
      contactEmail: settings.contactEmail || '',
      systemLogo: settings.systemLogo || '',
    };

    // Security settings
    securitySettings.value = {
      passwordStrength: settings.passwordStrength || 'medium',
      maxLoginAttempts: settings.maxLoginAttempts || 5,
      tokenExpire: settings.tokenExpire || '7d',
      forceHttps: settings.forceHttps || false,
    };

    // Notification settings
    notificationSettings.value = {
      emailEnabled: settings.emailEnabled ?? true,
      smtpHost: settings.smtpHost || '',
      smtpPort: settings.smtpPort || 465,
      fromEmail: settings.fromEmail || '',
      smsEnabled: settings.smsEnabled || false,
    };

    // Storage settings
    storageSettings.value = {
      storageType: settings.storageType || 'local',
      maxFileSize: settings.maxFileSize || 100,
      allowedTypes: settings.allowedTypes || '.jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.ppt,.pptx',
    };
  } catch (error) {
    console.error('Failed to load settings:', error);
    message.error('加载设置失败');
  } finally {
    loading.value = false;
  }
};

const handleLogoChange = (info: { fileList: UploadFile[] }) => {
  fileList.value = info.fileList;
};

const saveBasicSettings = async () => {
  saving.value = true;
  try {
    await updateAdminSettings(basicSettings.value);
    message.success('基本设置已保存');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

const saveSecuritySettings = async () => {
  saving.value = true;
  try {
    await updateAdminSettings(securitySettings.value);
    message.success('安全设置已保存');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

const saveNotificationSettings = async () => {
  saving.value = true;
  try {
    await updateAdminSettings(notificationSettings.value);
    message.success('通知设置已保存');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

const saveStorageSettings = async () => {
  saving.value = true;
  try {
    await updateAdminSettings(storageSettings.value);
    message.success('存储设置已保存');
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  loadSettings();
});
</script>

<style scoped lang="scss">
.settings-page {
  :deep(.ant-card-head) {
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.ant-form-item) {
    margin-bottom: 24px;
  }
}
</style>
