package cn.qinys.platform.gateway.msgsender;


import cn.qinys.platform.gateway.constants.GatewayConstants;
import cn.qinys.platform.gateway.dto.LoginDTO;
import cn.qinys.platform.gateway.entity.GatewayLog;
import cn.qinys.platform.gateway.mapper.GatewayLogMapper;
import cn.qinys.platform.gateway.utils.RedisUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Date 2022-03-17 9:06
 * Description
 *
 * @author Tanlie
 */

@Service
@Slf4j
@AllArgsConstructor
public class RabbitmqServiceImpl implements IMessageService {
    private final GatewayLogMapper logMapper;
    private final RedisUtils redisUtils;

    @Async
    @Override
    public void send(GatewayLog gatewayLog) {
        try {
            if (gatewayLog.getRequestPath().contains(".jpg")
                    || gatewayLog.getRequestPath().contains(".png")
                    || gatewayLog.getRequestPath().contains(".jpeg")) {
                return;
            }
            gatewayLog.setMonth(LocalDate.now().getMonthValue());
            gatewayLog.setUserMobile(this.getMobileByToken(gatewayLog.getToken(), gatewayLog.getMonth()));
            logMapper.insert(gatewayLog);
        } catch (Exception e) {
            log.error("收集网关日志出错 == {}", e.getMessage());
        }
    }

    /**
     * 获取用户
     *
     * @param token
     * @return
     */
    private String getMobileByToken(String token, Integer month) {
        if (!StringUtils.hasText(token)) {
            return "";
        }
        token = token.replaceFirst("Bearer ", "");
        if (!StringUtils.hasLength(token)) {
            return "";
        }
        String key = GatewayConstants.RedisKeyEnum.MOBILE_BY_TOKEN.getCode() + token;
        if (redisUtils.exists(key)) {
            return (String) redisUtils.get(key);
        }
        String mobile = "";
        try {
            List<String> loginPath = new ArrayList<>();
            loginPath.add("/dgapi/mobile/map/user/login");
            loginPath.add("/dgapi/v3/mobile/map/user/login");
            loginPath.add("/dgapi/upms/login/admin-token");
            QueryWrapper<GatewayLog> wrapper = new QueryWrapper<>();
            wrapper.select("id", "response_data");
            wrapper.eq("month", month);
            wrapper.in("request_path", loginPath);
            wrapper.eq("DATE_FORMAT(request_time,'%Y-%m-%d')", DateUtils.format(new Date(), "yyyy-MM-dd"));
            wrapper.orderByDesc("id");
            List<GatewayLog> logList = logMapper.selectList(wrapper);
            for (GatewayLog gatewayLog : logList) {
                JSONObject json = JSON.parseObject(gatewayLog.getResponseData());
                if (json.getIntValue("code", 0) == 200) {
                    LoginDTO dto = JSON.parseObject(json.getString("data"), LoginDTO.class);
                    if (token.equalsIgnoreCase(dto.getToken())) {
                        if (dto.getMobile() != null) {
                            mobile = dto.getMobile();
                        } else {
                            mobile = dto.getUserInfo().getMobile();
                        }
                        break;
                    }
                }
            }
        } catch (Exception ignored) {
        }
        redisUtils.set(key, mobile, GatewayConstants.RedisKeyEnum.MOBILE_BY_TOKEN.getExpireTime());
        return mobile;
    }
}
