import { DataSource, Repository } from 'typeorm';
import { SystemSetting } from './system-setting.entity';
import { CreateSystemSettingDto, UpdateSystemSettingDto } from './system-setting.schema';

export class SystemSettingService {
  private repository: Repository<SystemSetting>;
  
  constructor(dataSource: DataSource) {
    this.repository = dataSource.getRepository(SystemSetting);
  }

  /**
   * 获取所有系统设置
   */
  async findAll(): Promise<SystemSetting[]> {
    return this.repository.find({ order: { settingKey: 'ASC' } });
  }

  /**
   * 根据键名获取系统设置
   */
  async findByKey(settingKey: string): Promise<SystemSetting | null> {
    return this.repository.findOne({ where: { settingKey } });
  }

  /**
   * 获取设置值
   */
  async getValue(settingKey: string): Promise<string | null> {
    const setting = await this.findByKey(settingKey);
    return setting?.settingValue || null;
  }

  /**
   * 获取布尔值设置
   */
  async getBooleanValue(settingKey: string): Promise<boolean> {
    const value = await this.getValue(settingKey);
    return value === 'true';
  }

  /**
   * 获取数字值设置
   */
  async getNumberValue(settingKey: string): Promise<number> {
    const value = await this.getValue(settingKey);
    return value ? Number(value) : 0;
  }

  /**
   * 创建系统设置
   */
  async create(data: CreateSystemSettingDto): Promise<SystemSetting> {
    const existing = await this.findByKey(data.settingKey);
    if (existing) {
      throw new Error(`设置键名 ${data.settingKey} 已存在`);
    }

    const setting = this.repository.create(data);
    return this.repository.save(setting);
  }

  /**
   * 更新系统设置
   */
  async update(settingKey: string, data: UpdateSystemSettingDto): Promise<SystemSetting> {
    const setting = await this.findByKey(settingKey);
    if (!setting) {
      throw new Error(`设置 ${settingKey} 不存在`);
    }

    Object.assign(setting, data);
    return this.repository.save(setting);
  }

  /**
   * 更新设置值
   */
  async updateValue(settingKey: string, settingValue: string | null): Promise<SystemSetting> {
    const setting = await this.findByKey(settingKey);
    if (!setting) {
      throw new Error(`设置 ${settingKey} 不存在`);
    }

    setting.settingValue = settingValue;
    return this.repository.save(setting);
  }

  /**
   * 批量更新设置
   */
  async batchUpdate(settings: Array<{ settingKey: string; settingValue: string | null }>): Promise<SystemSetting[]> {
    const results: SystemSetting[] = [];
    
    for (const item of settings) {
      try {
        const setting = await this.findByKey(item.settingKey);
        if (setting) {
          setting.settingValue = item.settingValue;
          const updated = await this.repository.save(setting);
          results.push(updated);
        } else {
          // 如果设置不存在，创建新的
          const newSetting = this.repository.create({
            settingKey: item.settingKey,
            settingValue: item.settingValue,
            settingType: 'string',
            description: `系统设置: ${item.settingKey}`
          });
          const created = await this.repository.save(newSetting);
          results.push(created);
        }
      } catch (error) {
        console.error(`更新设置 ${item.settingKey} 失败:`, error);
      }
    }
    
    return results;
  }

  /**
   * 删除系统设置
   */
  async delete(settingKey: string): Promise<boolean> {
    const result = await this.repository.delete({ settingKey });
    return result.affected !== null && result.affected > 0;
  }

  /**
   * 初始化默认设置
   */
  async initDefaultSettings(): Promise<void> {
    const defaultSettings = [
      {
        settingKey: 'home_register_enabled',
        settingValue: 'true',
        description: '首页注册功能开关',
        settingType: 'boolean'
      }
    ];

    for (const setting of defaultSettings) {
      const existing = await this.findByKey(setting.settingKey);
      if (!existing) {
        await this.create(setting);
      }
    }
  }
}