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

import com.zanxiang.game.module.mybatis.entity.User;
import com.zanxiang.game.module.sdk.pojo.dto.GameAppletDTO;
import com.zanxiang.game.module.sdk.pojo.param.MsgSceneCheckParam;
import com.zanxiang.game.module.sdk.pojo.param.UserData;
import com.zanxiang.game.module.sdk.service.IGameAppletService;
import com.zanxiang.game.module.sdk.service.IMsgSceneCheckService;
import com.zanxiang.game.module.sdk.service.IUserService;
import com.zanxiang.game.module.sdk.service.api.WxApiService;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : lingfeng
 * @time : 2023-11-13
 * @description : 小程序安全检测
 */
@Slf4j
@Service
public class MsgSceneCheckServiceImpl implements IMsgSceneCheckService {

    @Autowired
    private WxApiService wxApiService;

    @Autowired
    private IGameAppletService gameAppletService;

    @Autowired
    private IUserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String msgCheck(MsgSceneCheckParam param, UserData userData) {
        User user = userService.getById(userData.getUserId());
        GameAppletDTO gameAppletDTO = gameAppletService.getByGameId(userData.getGameId());
        String accessToken = wxApiService.getAccessToken(gameAppletDTO.getAppId(), gameAppletDTO.getAppSecret());
        Map<String, Object> paramMap = new HashMap<>(4);
        paramMap.put("content", param.getContent());
        paramMap.put("version", 2);
        paramMap.put("scene", param.getScene());
        paramMap.put("openid", user.getOpenId());
        URI uri = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/wxa/msg_sec_check")
                .queryParam("access_token", accessToken)
                .build().toUri();
        String result = null;
        try {
            result = restTemplate.postForObject(uri, paramMap, String.class);
        } catch (Exception e) {
            log.error("消息检测腾讯接口异常, param : {}, userData : {}", JsonUtil.toString(param), JsonUtil.toString(userData));
        }
        return result;
    }
}
