import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Resource } from 'src/resource/entities/resource.entity';
import { DataSource } from 'typeorm';
import { LoginUserDto } from '../dto/login-user.dto';
import { Role } from '../entities/role.entity';
import { User } from '../entities/user.entity';

@Injectable()
export class SystemService {
  constructor(
    private dataSource: DataSource,

    private jwtService: JwtService,
  ) {}

  async login(loginUserDto: LoginUserDto) {
    const user = await this.dataSource
      .getRepository(User)
      .findOneBy({ ...loginUserDto, delFlag: 0 });
    if (!user) throw '用户名或密码错误';

    const role = await this.dataSource
      .getRepository(Role)
      .findOneBy({ id: user.roleId });

    const resource =
      user.photo &&
      (await this.dataSource
        .getRepository(Resource)
        .findOneBy({ id: user.photo }));

    return {
      user: {
        ...user,
        roleName: role.name,
        baseRole: role.base,
        photo: resource?.diskname,
      },
      token: this.jwtService.sign({
        sub: user.id,
        auth: user.roleId,
        base: role.base,
        org: user.orgId,
      }),
    };
  }

  async checkAdminPassword(password) {
    console.log({ password });
    if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,12}$/.test(password))
      throw '密码输入不合法，若是初始密码请修改后再试';

    if (
      !(await this.dataSource
        .getRepository(User)
        .findOneBy({ username: 'admin', password }))
    )
      throw '管理员密码错误';
    return true;
  }
}
