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

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.mybatis.entity.CpPushErrorLog;
import com.zanxiang.game.module.mybatis.mapper.CpPushErrorLogMapper;
import com.zanxiang.game.module.sdk.enums.CpPushDataEnum;
import com.zanxiang.game.module.sdk.service.ICpPushErrorLogService;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author : lingfeng
 * @time : 2024-06-27
 * @description : CP推送数据错误日志
 */
@Slf4j
@Service
public class CpPushErrorLogServiceImpl extends ServiceImpl<CpPushErrorLogMapper, CpPushErrorLog> implements ICpPushErrorLogService {

    @Override
    public void createLog(Long gameId, CpPushDataEnum cpPushDataEnum, Object param, String errorMsg) {
        String paramJsonStr = JsonUtil.toString(param);
        Map<String, String> paramMap = JsonUtil.toMap(paramJsonStr, Map.class, String.class);
        super.save(CpPushErrorLog.builder()
                .dataType(cpPushDataEnum.getValue())
                .gameId(gameId)
                .openId(paramMap.get("openId"))
                .orderId(paramMap.get("orderId"))
                .serverId(paramMap.get("serverId"))
                .roleId(paramMap.get("roleId"))
                .param(paramJsonStr)
                .errorMsg(errorMsg)
                .status(CpPushErrorLog.STATUS_VALID)
                .createTime(LocalDateTime.now())
                .build());
    }

    @Override
    public void errorLogUpdate(Long gameId, CpPushDataEnum cpPushDataEnum, Object param) {
        Map<String, String> paramMap = JsonUtil.toMap(JsonUtil.toString(param), Map.class, String.class);
        super.update(new LambdaUpdateWrapper<CpPushErrorLog>()
                .set(CpPushErrorLog::getStatus, CpPushErrorLog.STATUS_INVALID)
                .eq(CpPushErrorLog::getGameId, gameId)
                .eq(CpPushErrorLog::getDataType, cpPushDataEnum.getValue())
                .eq(Strings.isNotBlank(paramMap.get("openId")), CpPushErrorLog::getOpenId, paramMap.get("openId"))
                .eq(Strings.isNotBlank(paramMap.get("orderId")), CpPushErrorLog::getOrderId, paramMap.get("orderId"))
                .eq(Strings.isNotBlank(paramMap.get("serverId")), CpPushErrorLog::getServerId, paramMap.get("serverId"))
                .eq(Strings.isNotBlank(paramMap.get("roleId")), CpPushErrorLog::getRoleId, paramMap.get("roleId"))
        );
    }
}
