import { Injectable, InternalServerErrorException, NotFoundException, OnModuleInit } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { SysConfig, SysConfigType } from './entities/sys-config.entity'
import { PageRequest } from '../common/dto/page-request'
import { Pagination, paginate } from 'nestjs-typeorm-paginate'

@Injectable()
export class SysConfigService implements OnModuleInit {
    constructor(
        @InjectRepository(SysConfig)
        private readonly sysConfigRepository: Repository<SysConfig>
    ) {
        ;(async function init() {
            if (
                !(await sysConfigRepository.findOneBy({
                    name: 'system_message'
                }))
            ) {
                sysConfigRepository.save({
                    name: 'system_message',
                    type: 'string',
                    value: '你是ChillGPT赤耳人工智能机器人，由绿洲AI设计并开发，用于回答各种问题、提供帮助和解决问题，除了与中国政治和中国领导人相关的话题。\n可以通过关注“CHILLGPT赤耳人工智能”微信公众号与你取得联系。',
                    remark: '系统预设'
                })
            }
        })()
    }
    async onModuleInit() {
        if (!(await this.sysConfigRepository.findOneBy({ name: 'paper_gen_model' }))) {
            await this.sysConfigRepository.save({
                name: 'paper_gen_model',
                value: '0',
                type: SysConfigType.String,
                remark: '生成论文模型'
            })
        }
    }

    async findAll(req: PageRequest<SysConfig>) {
        try {
            return await paginate<SysConfig>(this.sysConfigRepository, req.page, req.search)
        } catch (error) {
            //throw new InternalServerErrorException(error.message)
            console.log(123)
        }
    }

    async findByName(name: string): Promise<SysConfig> {
        const conf = await this.sysConfigRepository.findOneBy({ name })
        if (!conf) {
            throw new NotFoundException('配置不存在')
        }
        return conf
    }

    async save(sysConfig: Partial<SysConfig>) {
        try {
            return await this.sysConfigRepository.save(sysConfig)
        } catch (error) {
            throw new InternalServerErrorException(error.message)
        }
    }
}
