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

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.advertising.tencent.base.AdvertisingTencentServer;
import com.zanxiang.advertising.tencent.base.rpc.IUserActionSetRpc;
import com.zanxiang.game.back.serve.dao.mapper.GameTencentMiniGameUserMapper;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentMiniGameUserDTO;
import com.zanxiang.game.back.serve.pojo.entity.GameOceanengineOrderLog;
import com.zanxiang.game.back.serve.pojo.entity.GameOceanengineUserLog;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameBackLog;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameUser;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.pojo.vo.GameOceanengineOrderLogVO;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentMiniGameUserVO;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameBackLogService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameUserService;
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.collections4.CollectionUtils;
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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GameTencentMiniGameUserServiceImpl extends ServiceImpl<GameTencentMiniGameUserMapper, GameTencentMiniGameUser>
        implements IGameTencentMiniGameUserService {

    @DubboReference(providedBy = AdvertisingTencentServer.SERVER_DUBBO_NAME)
    private IUserActionSetRpc userActionSetRpc;
    @Autowired
    private IGameTencentMiniGameBackLogService gameTencentMiniGameBackLogService;
    @DubboReference(providedBy = ServerInfo.SERVER_DUBBO_NAME)
    private IAgentRpc agentRpc;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean userBack(GameTencentMiniGameUser userLog, boolean mustBack) {
        if (StringUtils.isBlank(userLog.getClickId())) {
            // 没有点击 id（之后做监测链接，从监测链接里面找）
            return false;
        }
        BackStatusEnum backStatus = doCallback(userLog, mustBack);
        return update(new LambdaUpdateWrapper<GameTencentMiniGameUser>()
                .set(GameTencentMiniGameUser::getBackStatus, backStatus.getBackStatus())
                .eq(GameTencentMiniGameUser::getId, userLog.getId())
        );
    }


    @Override
    public IPage<GameTencentMiniGameUserVO> listOfPage(GameTencentMiniGameUserDTO dto) {
        IPage<GameTencentMiniGameUser> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentMiniGameUser>()
                .eq(StringUtils.isNotBlank(dto.getAgentKey()), GameTencentMiniGameUser::getAgentKey, dto.getAgentKey())
                .ge(dto.getActiveTimeBegin() != null, GameTencentMiniGameUser::getRegisterTime, dto.getActiveTimeBegin() == null ? null : LocalDateTime.of(dto.getActiveTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getActiveTimeEnd() != null, GameTencentMiniGameUser::getRegisterTime, dto.getActiveTimeEnd() == null ? null : LocalDateTime.of(dto.getActiveTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameTencentMiniGameUser::getGameId, dto.getGameId())
                .eq(null != dto.getAdAccountId(), GameTencentMiniGameUser::getAdAccountId, dto.getAdAccountId())
                .eq(StringUtils.isNotBlank(dto.getWechatAppId()), GameTencentMiniGameUser::getWechatAppId, dto.getWechatAppId())
                .eq(StringUtils.isNotBlank(dto.getWechatOpenid()), GameTencentMiniGameUser::getWechatOpenid, dto.getWechatOpenid())
                .eq(null != dto.getBackStatus(), GameTencentMiniGameUser::getBackStatus, dto.getBackStatus())
                .orderByDesc(GameTencentMiniGameUser::getCreateTime)
        );
        IPage<GameTencentMiniGameUserVO> result = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return result;
        }
        result.setRecords(toVOBatch(page.getRecords()));
        return result;
    }

    @Override
    public boolean doReport(List<Long> userLogIds) {
        listByIds(userLogIds).forEach(userLog -> {
            BackStatusEnum backStatus = doCallback(userLog, true);
            update(new LambdaUpdateWrapper<GameTencentMiniGameUser>()
                    .set(GameTencentMiniGameUser::getBackStatus, backStatus.getBackStatus())
                    .eq(GameTencentMiniGameUser::getId, userLog.getId())
            );
        });
        return true;
    }

    private List<GameTencentMiniGameUserVO> toVOBatch(List<GameTencentMiniGameUser> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        Set<String> agentKeys = logList.stream().map(GameTencentMiniGameUser::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 -> {
            GameTencentMiniGameUserVO vo = toVOSimple(log);
            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(GameTencentMiniGameUser userLog, boolean mustBack) {
        boolean isBack = mustBack ? false : gameTencentMiniGameBackLogService.count(new LambdaQueryWrapper<GameTencentMiniGameBackLog>()
                .eq(GameTencentMiniGameBackLog::getGameId, userLog.getGameId())
                .eq(GameTencentMiniGameBackLog::getWechatAppId, userLog.getWechatAppId())
                .eq(GameTencentMiniGameBackLog::getWechatOpenid, userLog.getWechatOpenid())
                .eq(GameTencentMiniGameBackLog::getAdAccountId, userLog.getAdAccountId())
                .eq(GameTencentMiniGameBackLog::getBackStatus, BackStatusEnum.SUCCESS.getBackStatus())
        ) > 0;
        if (isBack) {
            return BackStatusEnum.NO;
        }
        return gameTencentMiniGameBackLogService.userBack(userLog);
    }

    private GameTencentMiniGameUserVO toVOSimple(GameTencentMiniGameUser userLog) {
        if (userLog == null) {
            return null;
        }
        return BeanUtil.copy(userLog, GameTencentMiniGameUserVO.class);
    }
}
