package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dji.sample.common.util.DateUtil;
import com.dji.sample.manage.dao.ILoginLogMapper;
import com.dji.sample.manage.model.dto.LoginLogDTO;
import com.dji.sample.manage.model.entity.LoginLogEntity;
import com.dji.sample.manage.model.entity.UserEntity;
import com.dji.sample.manage.model.param.searchParam.LoginLogSearchParam;
import com.dji.sample.manage.service.ILoginLogService;
import com.dji.sdk.common.PaginationData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenshixian
 **/
@Service
public class LoginLogService implements ILoginLogService {

    @Autowired
    private ILoginLogMapper loginLogMapper;

    /**
     * 保存登录信息
     * @param userEntity
     * @param success
     * @param message
     */
    @Override
    public void addLoginLog(UserEntity userEntity, boolean success, String message) {
        addLoginLog(userEntity, success, message, null, null);
    }

    /**
     * 保存登录信息（包含IP和User Agent）
     *
     * @param userEntity
     * @param success
     * @param message
     * @param ipAddress
     * @param userAgent
     */
    @Override
    public void addLoginLog(UserEntity userEntity, boolean success, String message, String ipAddress, String userAgent) {
        LoginLogEntity loginLogEntity = new LoginLogEntity();
        loginLogEntity.setUserId(userEntity.getUserId());
        loginLogEntity.setUsername(userEntity.getUsername());
        loginLogEntity.setSuccess(success);
        loginLogEntity.setMessage(message);
        loginLogEntity.setIpAddress(ipAddress);
        loginLogEntity.setUserAgent(userAgent);
        loginLogEntity.setCreateTime(System.currentTimeMillis());
        loginLogMapper.insert(loginLogEntity);
    }

    /**
     * 保存登录信息（仅用户名，用于登录失败场景）
     *
     * @param username
     * @param success
     * @param message
     * @param ipAddress
     * @param userAgent
     */
    @Override
    public void addLoginLog(String username, boolean success, String message, String ipAddress, String userAgent) {
        LoginLogEntity loginLogEntity = new LoginLogEntity();
        loginLogEntity.setUserId("");
        loginLogEntity.setUsername(username);
        loginLogEntity.setSuccess(success);
        loginLogEntity.setMessage(message);
        loginLogEntity.setIpAddress(ipAddress);
        loginLogEntity.setUserAgent(userAgent);
        loginLogEntity.setCreateTime(System.currentTimeMillis());
        loginLogMapper.insert(loginLogEntity);
    }


    private LoginLogDTO entity2DTO(LoginLogEntity entity) {
        LoginLogDTO.LoginLogDTOBuilder builder = LoginLogDTO.builder();
        if (entity != null) {
            builder.userId(entity.getUserId())
                    .id(entity.getId())
                    .userId(entity.getUserId())
                    .username(entity.getUsername())
                    .success(entity.isSuccess())
                    .message(entity.getMessage())
                    .ipAddress(entity.getIpAddress())
                    .userAgent(entity.getUserAgent())
                    .createTime(entity.getCreateTime());

        }

        return builder.build();
    }


    @Override
    public PaginationData<LoginLogDTO> getLoginLogList(LoginLogSearchParam param, int page, int pageSize) {

        LambdaQueryWrapper<LoginLogEntity> queryWrapper = new LambdaQueryWrapper<>();

        if (param != null) {

            if (StringUtils.isNotBlank(param.getUserId())) {
                queryWrapper.eq(LoginLogEntity::getUserId, param.getUserId());
            }

            if (StringUtils.isNotBlank(param.getStartDate())) {
                String startDate = param.getStartDate();
                startDate += " 00:00:00";
                queryWrapper.ge(LoginLogEntity::getCreateTime, DateUtil.getTimeStampFromDateStr(startDate));
            }

            if (StringUtils.isNotBlank(param.getEndDate())) {
                String startDate = param.getStartDate();
                startDate += " 23:59:59";
                queryWrapper.lt(LoginLogEntity::getCreateTime, DateUtil.getTimeStampFromDateStrNext(startDate));
            }
        }

        queryWrapper.orderByDesc(LoginLogEntity::getCreateTime);

        Page<LoginLogEntity> userEntityPage = loginLogMapper.selectPage(new Page<>(page, pageSize), queryWrapper);
        List<LoginLogDTO> usersList = userEntityPage.getRecords()
                .stream()
                .map(this::entity2DTO)
                .collect(Collectors.toList());

        return PaginationData.of(usersList, userEntityPage.getTotal(), page, pageSize);

    }
}
