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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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 com.zanxiang.game.module.sdk.service.IUserAgentLogService;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import reactor.util.function.Tuple3;

import java.time.LocalDateTime;

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

    @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;
    }

    @Override
    public boolean agentUpdateLog(Tuple3<Long, Long, String> oldAgentChannel, Long newAgentId, String newChannel) {
        if (newAgentId == null || Strings.isBlank(newChannel)) {
            return Boolean.FALSE;
        }
        try {
            return super.save(this.transform(oldAgentChannel, newAgentId, newChannel));
        } catch (Exception e) {
            log.error("用户渠道更新记录保存异常, oldAgentChannel : {}, newAgentId : {}, newChannel : {}, e : {}",
                    JsonUtil.toString(oldAgentChannel), newAgentId, newChannel, 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();
    }

    private UserAgentLog transform(Tuple3<Long, Long, String> oldAgentChannel, Long newAgentId, String newChannel) {
        return UserAgentLog.builder()
                .userId(oldAgentChannel.getT1())
                .oldAgentId(Agent.DEFAULT_AGENT.equals(oldAgentChannel.getT2()) ? null : oldAgentChannel.getT2())
                .oldChannel(Agent.DEFAULT_AGENT.equals(oldAgentChannel.getT2()) ? null : oldAgentChannel.getT3())
                .newAgentId(newAgentId)
                .newChannel(newChannel)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
    }
}
