import { Injectable } from '@nestjs/common';
import { CreateOperationLogDto } from './dto/create-operation-log.dto';
import { UpdateOperationLogDto } from './dto/update-operation-log.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { OperationLog } from './entities/operation-log.entity';
import { Like, MoreThan, Repository } from 'typeorm';
import { QueryOperationLogDto } from './dto/query.dto';
import { Between } from 'typeorm';
import { dayjs } from '../../common/utils';
import { format } from 'date-fns';
import { Dayjs } from 'dayjs';

@Injectable()
export class OperationLogService {
  constructor(
    @InjectRepository(OperationLog)
    private operationLogRepo: Repository<OperationLog>,
  ) {}

  create(createOperationLogDto: CreateOperationLogDto) {
    return this.operationLogRepo.save(createOperationLogDto);
  }

  findAll() {
    return `This action returns all operationLog`;
  }

  findOne(id: number) {
    return `This action returns a #${id} operationLog`;
  }

  update(id: number, updateOperationLogDto: UpdateOperationLogDto) {
    return `This action updates a #${id} operationLog`;
  }

  remove(id: number) {
    return `This action removes a #${id} operationLog`;
  }

  async findPagination(query: QueryOperationLogDto) {
    const pageSize = query.pageSize || 10;
    const pageNo = query.pageNo || 1;
    let from, to;
    if (query.times) {
      from = dayjs
        .unix(Number(query.times[0]) / 1000)
        // .utc()
        // .tz('Asia/Shanghai')
        .format('YYYY-MM-DD HH:mm:ss');
      to = dayjs
        .unix(Number(query.times[1]) / 1000)
        // .utc()
        // .tz('Asia/Shanghai')
        .format('YYYY-MM-DD HH:mm:ss');
    }

    const [data, total] = await this.operationLogRepo.findAndCount({
      relations: { user: true },
      where: {
        //  User: Like(`%${query.title || ''}%`),
        user: {
          username: Like(`%${query.useName || ''}%`),
        },
        userId: MoreThan(0),
        createTime: query.times ? Between(from, to) : undefined,
      },
      select: {
        user: {
          id: true,
          username: true,
        },
      },
      order: {
        // title: 'ASC',
        createTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNo - 1) * pageSize,
    });
    // console.log('data', data)
    const pageData = data.map((item) => {
      return { ...item };
    });
    return { pageData, total };
  }
}
