package com.zanxiang.game.module.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.manage.service.IUserAgentLogService;
import com.zanxiang.game.module.mybatis.entity.Agent;
import com.zanxiang.game.module.mybatis.entity.User;
import com.zanxiang.game.module.mybatis.entity.UserAgentLog;
import com.zanxiang.game.module.mybatis.mapper.UserAgentLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author : lingfeng
 * @time : 2023-07-20
 * @description : 用户渠道记录
 */
@Slf4j
@Service
public class UserAgentLogServiceImpl extends ServiceImpl<UserAgentLogMapper, UserAgentLog> implements IUserAgentLogService {

    @Override
    public void userAgentLogUpdate(boolean isRunUpdate) {
        List<UserAgentLog> errorList = super.list(new LambdaQueryWrapper<UserAgentLog>()
                .isNotNull(UserAgentLog::getOldAgentId)
                .isNotNull(UserAgentLog::getNewAgentId)
                .apply("old_agent_id=new_agent_id"));
        if (CollectionUtils.isEmpty(errorList)) {
            log.error("查询到可修正的数据列表为空!!!");
            return;
        }
        log.error("查询到数据 count : {}", errorList.size());
        if (!isRunUpdate) {
            return;
        }
        int count = 0;
        for (UserAgentLog userAgentLog : errorList) {
            this.agentLogUpdate(userAgentLog);
            count++;
            log.error("第 count : {} 条数据, id : {} 修正", count, userAgentLog.getId());
        }
        log.error("=========== 全部修正完成 ===========");
    }

    private void agentLogUpdate(UserAgentLog userAgentLog) {
        //不是错误数据
        if (!Objects.equals(userAgentLog.getOldAgentId(), userAgentLog.getNewAgentId())) {
            return;
        }
        //根据 userId 和 createTime 查询上一条数据
        UserAgentLog beforeLog = super.getOne(new LambdaQueryWrapper<UserAgentLog>()
                .eq(UserAgentLog::getUserId, userAgentLog.getUserId())
                .lt(UserAgentLog::getCreateTime, userAgentLog.getCreateTime())
                .orderByDesc(UserAgentLog::getCreateTime)
                .last("limit 1"));
        //未查询到上一条记录, 不做修正
        if (beforeLog == null) {
            log.error("查询上一条记录结果为空-------!!!!!!, logId : {}", userAgentLog.getId());
            return;
        }
        //数据修正
        userAgentLog.setOldAgentId(beforeLog.getNewAgentId());
        userAgentLog.setOldChannel(beforeLog.getNewChannel());
        super.updateById(userAgentLog);
    }

    @Override
    public boolean regAgentLog(User user) {
        if (Agent.DEFAULT_AGENT.equals(user.getAgentId()) || Strings.isBlank(user.getChannel())) {
            return Boolean.FALSE;
        }
        try {
            return super.save(this.transform(user));
        } catch (Exception e) {
            log.error("用户注册渠道记录保存异常, userId : {}, e : {}", user.getId(), e.getMessage());
        }
        return Boolean.FALSE;
    }

    private UserAgentLog transform(User user) {
        return UserAgentLog.builder()
                .userId(user.getId())
                .newAgentId(user.getAgentId())
                .newChannel(user.getChannel())
                .createTime(user.getCreateTime())
                .updateTime(user.getCreateTime())
                .build();
    }
}
