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.pojo.dto.DataReportOfAppIdRpcDTO;
import com.zanxiang.advertising.tencent.base.pojo.dto.UserActionRpcDTO;
import com.zanxiang.advertising.tencent.base.rpc.IUserActionSetRpc;
import com.zanxiang.game.back.serve.dao.mapper.GameTencentUserMapper;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentUserDTO;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentBackLog;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentUser;
import com.zanxiang.game.back.serve.pojo.enums.ActionTypeEnum;
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.IGameTencentBackLogService;
import com.zanxiang.game.back.serve.service.IGameTencentUserService;
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 com.zanxiang.module.util.pojo.ResultVO;
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.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 游戏腾讯用户表 服务实现类
 * </p>
 *
 * @author auto
 * @since 2023-06-01
 */
@Slf4j
@Service
public class GameTencentUserServiceImpl extends ServiceImpl<GameTencentUserMapper, GameTencentUser> implements IGameTencentUserService {

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

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


    @Override
    public IPage<GameTencentUserVO> tencentUserLogList(GameTencentUserDTO dto) {
        IPage<GameTencentUser> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentUser>()
                .eq(StringUtils.isNotBlank(dto.getChannel()), GameTencentUser::getChannel, dto.getChannel())
                .ge(dto.getActiveTimeBegin() != null, GameTencentUser::getRegisterTime, dto.getActiveTimeBegin() == null ? null : LocalDateTime.of(dto.getActiveTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getActiveTimeEnd() != null, GameTencentUser::getRegisterTime, dto.getActiveTimeEnd() == null ? null : LocalDateTime.of(dto.getActiveTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameTencentUser::getGameId, dto.getGameId())
                .eq(null != dto.getAdAccountId(), GameTencentUser::getAdAccountId, dto.getAdAccountId())
                .eq(StringUtils.isNotBlank(dto.getWechatAppId()), GameTencentUser::getWechatAppId, dto.getWechatAppId())
                .eq(StringUtils.isNotBlank(dto.getWechatOpenid()), GameTencentUser::getWechatOpenid, dto.getWechatOpenid())
                .eq(null != dto.getIsBack(), GameTencentUser::getIsBack, dto.getIsBack())
                .orderByDesc(GameTencentUser::getCreateTime)
        );

        IPage<GameTencentUserVO> 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 tencentUserReport(List<Long> ids) {
        listByIds(ids).forEach(userLog -> {
            BackStatusEnum backStatus = doCallback(userLog, true);
            update(new LambdaUpdateWrapper<GameTencentUser>()
                    .set(GameTencentUser::getIsBack, backStatus.getBackStatus())
                    .eq(GameTencentUser::getId, userLog.getId())
            );
        });
        return true;
    }

    private List<GameTencentUserVO> toVOBatch(List<GameTencentUser> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        Set<String> agentKeys = logList.stream().map(GameTencentUser::getChannel).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.getChannel())) {
                AgentRpcVO agent = agentMap.get(log.getChannel());
                if (agent != null) {
                    vo.setAgentName(agent.getAgentName());
                }
            }
            return vo;
        }).collect(Collectors.toList());

    }


    private BackStatusEnum doCallback(GameTencentUser userLog, boolean mustBack) {
        boolean isBack = mustBack ? false : gameTencentBackLogService.count(new LambdaQueryWrapper<GameTencentBackLog>()
                .eq(GameTencentBackLog::getGameId, userLog.getGameId())
                .eq(GameTencentBackLog::getWechatAppId, userLog.getWechatAppId())
                .eq(GameTencentBackLog::getWechatOpenid, userLog.getWechatOpenid())
                .eq(GameTencentBackLog::getAdAccountId, userLog.getAdAccountId())
                .eq(GameTencentBackLog::getBackLog, "回传成功")
        ) > 0;
        if (isBack) {
            return BackStatusEnum.NO;
        }

        Map<String, Object> actionParam = new HashMap<>(2);
        actionParam.put("claim_type", 0);
        DataReportOfAppIdRpcDTO dataReportOfAppIdRpcDTO = DataReportOfAppIdRpcDTO.builder()
                .appId(userLog.getWechatAppId())
                .userActionSetId(userLog.getUserActionSetId())
                .action(UserActionRpcDTO.builder()
                        .actionTime(userLog.getRegisterTime())
                        .actionType(ActionTypeEnum.REGISTER.getActionType())
                        .userId(UserActionRpcDTO.UserIdRpcDTO.builder()
                                .wechatAppId(userLog.getWechatAppId())
                                .wechatOpenid(userLog.getWechatOpenid())
                                .build())
                        .actionParam(actionParam)
                        .build())
                .build();

        GameTencentBackLog gameTencentBackLog = GameTencentBackLog.builder()
                .gameId(userLog.getGameId())
                .adAccountId(userLog.getAdAccountId())
                .actionTime(userLog.getRegisterTime())
                .createTime(LocalDateTime.now())
                .actionType(ActionTypeEnum.REGISTER.getActionType())
                .wechatAppId(userLog.getWechatAppId())
                .wechatOpenid(userLog.getWechatOpenid())
                .userActionSetId(userLog.getUserActionSetId())
                .actionParam(actionParam.toString())
                .build();
        ResultVO<Boolean> result = userActionSetRpc.reportByAppId(dataReportOfAppIdRpcDTO);
        BackStatusEnum backStatus = BackStatusEnum.FAILED;
        if (result.isSuccess()) {
            backStatus = BackStatusEnum.SUCCESS;
            gameTencentBackLog.setBackLog("回传成功");
        } else {
            gameTencentBackLog.setBackLog(result.getMsg());
        }
        gameTencentBackLogService.save(gameTencentBackLog);
        return backStatus;
    }
}
