package com.zanxiang.game.back.serve.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.back.serve.dao.mapper.GameTencentAppUserMapper;
import com.zanxiang.game.back.serve.oceanengine.MiniGameCallback;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentAppUserDTO;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppBackLog;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentAppUser;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentUserVO;
import com.zanxiang.game.back.serve.service.IGameTencentAppBackLogService;
import com.zanxiang.game.back.serve.service.IGameTencentAppUserService;
import com.zanxiang.game.module.base.ServerInfo;
import com.zanxiang.game.module.base.pojo.vo.AgentRpcVO;
import com.zanxiang.game.module.base.rpc.IAgentRpc;
import com.zanxiang.module.util.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GameTencentAppUserServiceImpl extends ServiceImpl<GameTencentAppUserMapper, GameTencentAppUser>
        implements IGameTencentAppUserService {

    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IAgentRpc agentRpc;

    @Autowired
    private IGameTencentAppBackLogService gameTencentAppBackLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean userBack(GameTencentAppUser userLog, boolean mustBack) {
        BackStatusEnum backStatus = doCallback(userLog, mustBack);
        return update(new LambdaUpdateWrapper<GameTencentAppUser>()
                .set(GameTencentAppUser::getBackStatus, backStatus.getBackStatus())
                .eq(GameTencentAppUser::getId, userLog.getId())
        );
    }

    @Override
    public IPage<GameTencentUserVO> tencentUserLogList(GameTencentAppUserDTO dto) {
        IPage<GameTencentAppUser> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentAppUser>()
                .eq(StringUtils.isNotBlank(dto.getUserId()), GameTencentAppUser::getUserId, dto.getUserId())
                .eq(StringUtils.isNotBlank(dto.getMac()), GameTencentAppUser::getMac, dto.getMac())
                .eq(StringUtils.isNotBlank(dto.getImei()), GameTencentAppUser::getImei, dto.getImei())
                .eq(StringUtils.isNotBlank(dto.getOaid()), GameTencentAppUser::getOaid, dto.getOaid())
                .eq(StringUtils.isNotBlank(dto.getAndroidId()), GameTencentAppUser::getAndroidId, dto.getAndroidId())
                .eq(StringUtils.isNotBlank(dto.getIdfa()), GameTencentAppUser::getIdfa, dto.getIdfa())
                .eq(StringUtils.isNotBlank(dto.getCaid()), GameTencentAppUser::getCaid, dto.getCaid())
                .eq(StringUtils.isNotBlank(dto.getAgentKey()), GameTencentAppUser::getAgentKey, dto.getAgentKey())
                .ge(dto.getActiveTimeBegin() != null, GameTencentAppUser::getActiveTime, dto.getActiveTimeBegin() == null ? null : LocalDateTime.of(dto.getActiveTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getActiveTimeEnd() != null, GameTencentAppUser::getActiveTime, dto.getActiveTimeEnd() == null ? null : LocalDateTime.of(dto.getActiveTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameTencentAppUser::getGameId, dto.getGameId())
                .eq(null != dto.getAccountId(), GameTencentAppUser::getAccountId, dto.getAccountId())
                .eq(null != dto.getBackStatus(), GameTencentAppUser::getBackStatus, dto.getBackStatus())
                .orderByDesc(GameTencentAppUser::getCreateTime)
        );
        IPage<GameTencentUserVO> result = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return result;
        }
        result.setRecords(this.toVOBatch(page.getRecords()));
        return result;
    }

    private List<GameTencentUserVO> toVOBatch(List<GameTencentAppUser> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        Set<String> agentKeys = logList.stream().map(GameTencentAppUser::getAgentKey)
                .filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Map<String, AgentRpcVO> agentMap = CollectionUtils.isEmpty(agentKeys) ? Collections.emptyMap() : agentRpc.getByAgentKeys(new ArrayList<>(agentKeys))
                        .getData().stream().collect(Collectors.toMap(AgentRpcVO::getAgentKey, Function.identity()));
        return logList.stream().map(log -> {
            GameTencentUserVO vo = BeanUtil.copy(log, GameTencentUserVO.class);
            if (StringUtils.isNotBlank(log.getAgentKey())) {
                AgentRpcVO agent = agentMap.get(log.getAgentKey());
                if (agent != null) {
                    vo.setAgentName(agent.getAgentName());
                }
            }
            return vo;
        }).collect(Collectors.toList());
    }

    private BackStatusEnum doCallback(GameTencentAppUser userLog, boolean mustBack) {
        // 是否已经回传过
        if (!mustBack && gameTencentAppBackLogService.count(new LambdaQueryWrapper<GameTencentAppBackLog>()
                .eq(GameTencentAppBackLog::getGameId, userLog.getGameId())
                .eq(GameTencentAppBackLog::getUserId, userLog.getUserId())
                .eq(GameTencentAppBackLog::getAccountId, userLog.getAccountId())
                .eq(GameTencentAppBackLog::getEventType, MiniGameCallback.EventType.ACTIVE.getEventType())
                .eq(GameTencentAppBackLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
        ) > 0) {
            return BackStatusEnum.NO;
        }
        BackStatusEnum backStatus = BackStatusEnum.SUCCESS;
        gameTencentAppBackLogService.save(GameTencentAppBackLog.builder()
                .userId(userLog.getUserId())
                .mac(userLog.getMac())
                .imei(userLog.getImei())
                .oaid(userLog.getOaid())
                .androidId(userLog.getAndroidId())
                .idfa(userLog.getIdfa())
                .caid(userLog.getCaid())
                .gameId(userLog.getGameId())
                .accountId(userLog.getAccountId())
                .eventType(String.valueOf(MiniGameCallback.EventType.ACTIVE.getEventType()))
                .eventLogId(userLog.getId())
                .createTime(LocalDateTime.now())
                .backStatus(backStatus.getBackStatus())
                .errMsg(null)
                .build());
        return backStatus;
    }
}
