package cn.com.poc.data_report.rest.impl;

import cn.com.poc.common.utils.BlContext;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.common.utils.IPAddressUtil;
import cn.com.poc.data_report.dto.WebBrowseHarvestDto;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.poc.thirdparty.resource.demand.clickhouse.entity.WebBrowseHarvestEntity;
import cn.com.poc.data_report.rest.DataReportRest;
import cn.com.poc.thirdparty.resource.demand.clickhouse.service.DataReportService;
import cn.com.yict.framemax.core.config.Config;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.Header;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class DataReportRestImpl implements DataReportRest {

    @Resource
    private DataReportService dataReportService;

    @Override
    public void webBrowseHarvest(WebBrowseHarvestDto webBrowseHarvestDto, HttpServletRequest httpServletRequest) {
        WebBrowseHarvestEntity webBrowseHarvestEntity = new WebBrowseHarvestEntity();
        BeanUtil.copyProperties(webBrowseHarvestDto, webBrowseHarvestEntity);
        Date date = new Date();

        String projectName = Config.get("sys.applicationName");
        String ipAddress = IPAddressUtil.getIpAddress(httpServletRequest);
        String ipArea = IPAddressUtil.getIpArea(ipAddress);
        UserAgent userAgent = UserAgentUtil.parse(httpServletRequest.getHeader(Header.USER_AGENT.toString()));

        webBrowseHarvestEntity.setProject_name(projectName);
        webBrowseHarvestEntity.setRemote_addr(ipAddress);
        webBrowseHarvestEntity.setArea(ipArea);
        webBrowseHarvestEntity.setBrowser(userAgent.getPlatform().getName());
        webBrowseHarvestEntity.setDate(DateUtils.formatDate(date, DateUtils.yyyy_MM_dd));
        webBrowseHarvestEntity.setTime(DateUtils.formatDate(date, DateUtils.yyyy_MM_dd_HH_mm_ss));

        UserBaseEntity userBaseEntity = BlContext.getCurrentUserNotException();
        if (userBaseEntity != null && userBaseEntity.getUserId() != null) {
            webBrowseHarvestEntity.setUser_id(userBaseEntity.getUserId().toString());
        }

        dataReportService.webBrowseHarvest(webBrowseHarvestEntity);

    }
}
