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.GameTencentMiniGameRoleRegisterMapper;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentMiniGameRoleRegisterDTO;
import com.zanxiang.game.back.serve.pojo.dto.GameTencentMiniGameUserDTO;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameBackLog;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameRoleRegister;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentMiniGameUser;
import com.zanxiang.game.back.serve.pojo.entity.GameTencentUser;
import com.zanxiang.game.back.serve.pojo.enums.BackStatusEnum;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentMiniGameRoleRegisterVO;
import com.zanxiang.game.back.serve.pojo.vo.GameTencentMiniGameUserVO;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameBackLogService;
import com.zanxiang.game.back.serve.service.IGameTencentMiniGameRoleRegisterService;
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 GameTencentMiniGameRoleRegisterServiceImpl extends ServiceImpl<GameTencentMiniGameRoleRegisterMapper, GameTencentMiniGameRoleRegister>
        implements IGameTencentMiniGameRoleRegisterService {

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean roleRegisterBack(GameTencentMiniGameRoleRegister roleRegisterLog) {
        if (StringUtils.isBlank(roleRegisterLog.getClickId())) {
            return false;
        }
        BackStatusEnum backStatus = doCallback(roleRegisterLog);
        return update(new LambdaUpdateWrapper<GameTencentMiniGameRoleRegister>()
                .set(GameTencentMiniGameRoleRegister::getBackStatus, backStatus.getBackStatus())
                .eq(GameTencentMiniGameRoleRegister::getId, roleRegisterLog.getId())
        );
    }


    @Override
    public IPage<GameTencentMiniGameRoleRegisterVO> listOfPage(GameTencentMiniGameRoleRegisterDTO dto) {
        IPage<GameTencentMiniGameRoleRegister> page = page(dto.toPage(), new LambdaQueryWrapper<GameTencentMiniGameRoleRegister>()
                .eq(StringUtils.isNotBlank(dto.getAgentKey()), GameTencentMiniGameRoleRegister::getAgentKey, dto.getAgentKey())
                .ge(dto.getRegisterTimeBegin() != null, GameTencentMiniGameRoleRegister::getRegisterTime, dto.getRegisterTimeBegin() == null ? null : LocalDateTime.of(dto.getRegisterTimeBegin(), LocalTime.MIDNIGHT))
                .le(dto.getRegisterTimeEnd() != null, GameTencentMiniGameRoleRegister::getRegisterTime, dto.getRegisterTimeEnd() == null ? null : LocalDateTime.of(dto.getRegisterTimeEnd(), LocalTime.MAX))
                .eq(null != dto.getGameId(), GameTencentMiniGameRoleRegister::getGameId, dto.getGameId())
                .eq(null != dto.getAdAccountId(), GameTencentMiniGameRoleRegister::getAdAccountId, dto.getAdAccountId())
                .eq(StringUtils.isNotBlank(dto.getWechatAppId()), GameTencentMiniGameRoleRegister::getWechatAppId, dto.getWechatAppId())
                .eq(StringUtils.isNotBlank(dto.getWechatOpenid()), GameTencentMiniGameRoleRegister::getWechatOpenid, dto.getWechatOpenid())
                .eq(null != dto.getBackStatus(), GameTencentMiniGameRoleRegister::getBackStatus, dto.getBackStatus())
                .orderByDesc(GameTencentMiniGameRoleRegister::getCreateTime)
        );
        IPage<GameTencentMiniGameRoleRegisterVO> 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);
            update(new LambdaUpdateWrapper<GameTencentMiniGameRoleRegister>()
                    .set(GameTencentMiniGameRoleRegister::getBackStatus, backStatus.getBackStatus())
                    .eq(GameTencentMiniGameRoleRegister::getId, userLog.getId())
            );
        });
        return true;
    }

    private List<GameTencentMiniGameRoleRegisterVO> toVOBatch(List<GameTencentMiniGameRoleRegister> logList) {
        if (CollectionUtils.isEmpty(logList)) {
            return Collections.emptyList();
        }
        Set<String> agentKeys = logList.stream().map(GameTencentMiniGameRoleRegister::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 -> {
            GameTencentMiniGameRoleRegisterVO 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(GameTencentMiniGameRoleRegister roleRegisterLog) {
        GameTencentMiniGameUser user = gameTencentMiniGameUserService.getOne(new LambdaQueryWrapper<GameTencentMiniGameUser>()
                .eq(GameTencentMiniGameUser::getGameId, roleRegisterLog.getGameId())
                .eq(GameTencentMiniGameUser::getWechatAppId, roleRegisterLog.getWechatAppId())
                .eq(GameTencentMiniGameUser::getWechatOpenid, roleRegisterLog.getWechatOpenid())
                .eq(GameTencentMiniGameUser::getAdAccountId, roleRegisterLog.getAdAccountId())
                .orderByDesc(GameTencentMiniGameUser::getCreateTime)
                .last("limit 1")
        );
        if (user != null) {
            if (BackStatusEnum.NO.getBackStatus().equals(user.getBackStatus())) {
                gameTencentMiniGameUserService.userBack(user, true);
            } else {
                // 注册已回传，则默认认为创角也回传了
                return BackStatusEnum.NO;
            }
        }
        return gameTencentMiniGameBackLogService.roleRegisterBack(roleRegisterLog);
    }

    private GameTencentMiniGameRoleRegisterVO toVOSimple(GameTencentMiniGameRoleRegister roleRegisterLog) {
        if (roleRegisterLog == null) {
            return null;
        }
        return BeanUtil.copy(roleRegisterLog, GameTencentMiniGameRoleRegisterVO.class);
    }
}
