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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.mybatis.entity.Agent;
import com.zanxiang.game.module.mybatis.entity.UserVisitLog;
import com.zanxiang.game.module.mybatis.mapper.UserVisitLogMapper;
import com.zanxiang.game.module.sdk.service.IAgentService;
import com.zanxiang.game.module.sdk.service.IUserVisitLogService;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.web.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : lingfeng
 * @time : 2023-07-24
 * @description : 用户下载地址访问记录
 */
@Slf4j
@Service
public class UserVisitLogServiceImpl extends ServiceImpl<UserVisitLogMapper, UserVisitLog> implements IUserVisitLogService {

    @Autowired
    private IAgentService agentService;

    @Override
    public boolean visitLogCreate(String url, String userAgent, HttpServletRequest httpServletRequest) {
        //解析url
        Map<String, String> urlParamMap = this.getUrlParameter(url);
        log.error("下载地址访问上报参数 urlParamMap : {}", JsonUtil.toString(urlParamMap));
        //获取渠道标识
        Agent agent = null;
        String agentId = urlParamMap.get("agentId");
        String agentKey = urlParamMap.get("agentKey");
        if (Strings.isNotBlank(agentId)) {
            agent = agentService.getById(agentId);
        }
        if (agent == null && Strings.isNotBlank(agentKey)) {
            agent = agentService.getOne(new LambdaQueryWrapper<Agent>().eq(Agent::getAgentKey, agentKey));
        }
        //判断是否存在渠道
        if (agent == null) {
            return Boolean.FALSE;
        }
        //保存访问记录
        return super.save(UserVisitLog.builder()
                .gameId(agent.getGameId())
                .agentId(agent.getId())
                .ip(IpUtil.getRealIp(httpServletRequest))
                .ua(userAgent)
                .url(urlParamMap.get("url"))
                .channel(urlParamMap.get("channel"))
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build());
    }

    /**
     * 解析头条的url的host和参数
     *
     * @param url : 请求的url
     * @return : 返回url中携带的参数的和host地址
     */
    private Map<String, String> getUrlParameter(String url) {
        //参数判断
        if (Strings.isBlank(url)) {
            return Collections.emptyMap();
        }
        //没有拼接参数
        if (url.indexOf('?') == -1) {
            return Collections.singletonMap("url", url);
        }
        //参数map
        Map<String, String> map = new HashMap<>(5);
        try {
            final String charset = "utf-8";
            url = URLDecoder.decode(url, charset);
            //添加url的host
            map.put("url", url.substring(0, url.indexOf('?')));
            map.put("channel", url.substring(url.indexOf('?') + 1));
            //解析参数
            final String contents = url.substring(url.indexOf('?') + 1);
            String[] keyValues = contents.split("&");
            for (String keyValue : keyValues) {
                String key = keyValue.substring(0, keyValue.indexOf("="));
                String value = keyValue.substring(keyValue.indexOf("=") + 1);
                map.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
