import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateOrgDto } from '../dto/create-org.dto';
import { UpdateOrgDto } from '../dto/update-org.dto';
import { Org } from '../entities/org.entity';
import { User } from '../entities/user.entity';

@Injectable()
export class OrgService {
  constructor(
    @InjectRepository(Org)
    private orgRepository: Repository<Org>,
  ) {}

  async create(createOrgDto: CreateOrgDto) {
    await this.orgRepository.insert(createOrgDto);
    return true;
  }

  async findAll() {
    return this.orgRepository.find({
      select: ['id', 'name', 'desc', 'pid'],
      where: { delFlag: 0 },
    });
  }

  async findOrgByUserId(userId) {
    return this.orgRepository
      .createQueryBuilder('org')
      .innerJoin(
        User,
        'user',
        ['org.del_flag=0', 'user.del_flag=0', 'user.orgId=org.id'].join(
          ' and ',
        ),
      )
      .select(['org.id', 'org.name', 'org.pid'])
      .where('user.id = :userId', { userId })
      .getMany();
  }

  async update(id: number, updateOrgDto: UpdateOrgDto) {
    return this.orgRepository.update(id, updateOrgDto);
  }

  async remove(id: number) {
    return this.orgRepository.update(id, { delFlag: 1 });
  }
}
