import {
    Injectable,
    NotFoundException,
    HttpException,
    HttpStatus,
    BadRequestException,
    InternalServerErrorException,
    UnauthorizedException
} from '@nestjs/common'
import { In, Repository, UpdateResult, MoreThanOrEqual, LessThanOrEqual, And } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { Users } from './entities/users.entity'
import { IUsers } from './interfaces/users.interface'
import { UserCreateDto } from './dto/user-create.dto'
import { UserProfileDto } from './dto/user-profile.dto'
import { UserUpdateDto } from './dto/user-update.dto'
import { HashingService } from '../shared/hashing/hashing.service'
import { SmsService } from '../sms/sms.service'
import * as randomstring from 'randomstring'
import { MembershipService } from '../membership/membership.service'
import { ApiUserService } from '../api-users/api-user.service'
import { paginate, Pagination } from 'nestjs-typeorm-paginate'
import { Role } from '../model/role.enum'
import { PageRequest } from '../common/dto/page-request'
import { th } from 'date-fns/locale'
import { startOfDay, endOfDay, addDays, format } from 'date-fns'
import { where } from 'sequelize'

@Injectable()
export class UsersService {
    constructor(
        @InjectRepository(Users)
        private readonly userRepository: Repository<Users>,
        private readonly hashingService: HashingService,
        private readonly smsService: SmsService,
        private readonly membershipService: MembershipService,
        private readonly apiUserService: ApiUserService
    ) {}

    async findAll(req: PageRequest<Users>): Promise<Pagination<Users>> {
        return await paginate<Users>(this.userRepository, req.page, req.search)
    }

    public async findByEmail(email: string): Promise<Users> {
        const user = await this.userRepository.findOneBy({
            email: email
        })

        if (!user) {
            throw new NotFoundException(`User not found`)
        }

        return user
    }

    public async findById(userId: number): Promise<Users> {
        const user = await this.userRepository.findOneBy({
            id: +userId
        })

        if (!user) {
            throw new NotFoundException(`User #${userId} not found`)
        }

        return user
    }

    async findInfoByIds(userIds: number[]): Promise<Users[]> {
        const userList = await this.userRepository
            .createQueryBuilder('users')
            .select(['users.id', 'users.name'])
            .where({
                id: In(userIds)
            })
            .getMany()

        return userList
    }

    public async loginByPhone(phone: string, code: string, invitor: number | null): Promise<Users> {
        const verified = await this.smsService.verify(phone, code)
        if (!verified) {
            throw new InternalServerErrorException('手机号或验证码错误')
        }
        let newRegister = false
        let user = await this.userRepository.findOneBy({ phone: phone })
        if (!user) {
            newRegister = true
            user = new Users()
            user.phone = phone
            user.name = '0x' + randomstring.generate({ length: 8, charset: 'alphanumeric' })
            user.username = phone
            user.invitor = invitor || 48
            try {
                const invitorUser = await this.findById(invitor)
                if (!!invitorUser.apiUserId) {
                    user.apiUserId = invitorUser.apiUserId
                }
            } catch (error) {}
        }
        user = await this.userRepository.save(user)
        if (newRegister) {
            await this.membershipService.trial(user.id)
        }
        return user
    }

    public async loginAdmin(username: string, password: string): Promise<Users> {
        let user = await this.userRepository
            .createQueryBuilder('users')
            .where({ username })
            .addSelect('users.password')
            .getOne()
        if (!user) {
            throw new UnauthorizedException('用户名或密码错误')
        }
        const isMatch = await this.hashingService.compare(password, user.password)
        if (!isMatch) {
            throw new UnauthorizedException('用户名或密码错误')
        }
        if (!user.roles.includes(Role.Admin) && !user.roles.includes(Role.Api) && !user.roles.includes(Role.Org)) {
            throw new UnauthorizedException('用户名或密码错误')
        }
        return user
    }

    public async create(userDto: UserCreateDto) {
        try {
            if (userDto.password) {
                userDto.password = await this.hashingService.hash(userDto.password)
            }
            let user = await this.userRepository.save(userDto)
            if (userDto.roles.includes(Role.Api)) {
                let apiUser = await this.apiUserService.create(user.id)
                user.apiUserId = apiUser.id
                user = await this.userRepository.save(user)
            }

            return user
        } catch (err) {
            throw new InternalServerErrorException(err.message)
        }
    }

    public async createSubUser(userDto: UserCreateDto, apiUserId: number): Promise<IUsers> {
        try {
            const apiUser = await this.findById(apiUserId)
            if (userDto.password) {
                userDto.password = await this.hashingService.hash(userDto.password)
            }
            userDto.apiUserId = apiUser.apiUserId
            let user = await this.userRepository.save(userDto)

            return user
        } catch (err) {
            throw new InternalServerErrorException(err.message)
        }
    }

    public async updateByEmail(email: string): Promise<Users> {
        try {
            const user = await this.userRepository.findOneBy({ email: email })
            user.password = await this.hashingService.hash(Math.random().toString(36).slice(-8))

            return await this.userRepository.save(user)
        } catch (err) {
            throw new HttpException(err, HttpStatus.BAD_REQUEST)
        }
    }

    public async updateByPassword(email: string, password: string): Promise<Users> {
        try {
            const user = await this.userRepository.findOneBy({ email: email })
            user.password = await this.hashingService.hash(password)

            return await this.userRepository.save(user)
        } catch (err) {
            throw new HttpException(err, HttpStatus.BAD_REQUEST)
        }
    }

    public async updatePassword(id: number, password: string): Promise<Users> {
        try {
            const user = await this.userRepository.findOneBy({ id })
            user.password = await this.hashingService.hash(password)

            return await this.userRepository.save(user)
        } catch (err) {
            throw new HttpException(err, HttpStatus.BAD_REQUEST)
        }
    }

    public async updateProfileUser(id: number, userProfileDto: UserProfileDto): Promise<Users> {
        try {
            const user = await this.userRepository.findOneBy({ id: +id })
            if (userProfileDto.name) user.name = userProfileDto.name
            if (userProfileDto.avatar) user.avatar = userProfileDto.avatar

            return await this.userRepository.save(user)
        } catch (err) {
            throw new HttpException(err, HttpStatus.BAD_REQUEST)
        }
    }

    public async updateUser(id: number, userUpdateDto: UserUpdateDto): Promise<UpdateResult> {
        try {
            const user = await this.userRepository.update(
                {
                    id: +id
                },
                { ...userUpdateDto }
            )

            return user
        } catch (err) {
            throw new BadRequestException('User not updated')
        }
    }

    public async deleteUser(id: number): Promise<void> {
        const user = await this.findById(id)
        await this.userRepository.remove(user)
    }

    public async getInvites(userId: number) {
        return await this.userRepository.find({
            where: {
                invitor: userId
            }
        })
    }

    public async updateIat(user: Users, iat?: number) {
        user.iat = iat || Math.floor(new Date().getTime() / 1000) - 1
        return await this.userRepository.save(user)
    }

    public async getCount(apiUserId: number, roles?: Role, date?: string) {
        return await this.userRepository.count({
            where: {
                orgId: apiUserId,
                roles: roles,
                createdAt: date
                    ? And(MoreThanOrEqual(startOfDay(new Date(date))), LessThanOrEqual(endOfDay(new Date(date))))
                    : undefined
            }
        })
    }

    public async getWeekCount(apiUserId: number) {
        const date1 = new Date()
        let dayInfo = {}
        for (let i = 0; i < 7; i++) {
            let date2 = format(addDays(date1, 0 - i), 'yyyy-MM-dd')
            let api = await this.getCount(apiUserId, Role.Api, date2)
            let user = await this.getCount(apiUserId, Role.User, date2)
            dayInfo[format(addDays(date1, 0 - i), 'MM-dd')] = {
                api: api,
                user: user
            }
        }

        return dayInfo
    }

    public async getUsers(apiUserId: number, roles?: Role) {
        let users = await this.userRepository.findBy({
            orgId: apiUserId,
            roles: roles
        })

        return users.map((item) => {
            return item.id
        })
    }

    public async findByPhone(phone: string[]) {
        return await this.userRepository.findBy({
            phone: In(phone)
        })
    }
}
