package cn.skcks.docking.gb28181.wvp.service.report;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.util.IdUtil;
import cn.skcks.docking.gb28181.wvp.config.ReportConfig;
import cn.skcks.docking.gb28181.wvp.dto.report.ReportReq;
import cn.skcks.docking.gb28181.wvp.orm.mybatis.dynamic.model.WvpProxyDevice;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;

import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class ReportService {
    private final ReportApi reportApi;
    private final ReportConfig reportConfig;

    public void report(HttpServletRequest request, WvpProxyDevice device, Date startTime, Date endTime, long fileSize) {
        if(!reportConfig.getEnabled()){
            return;
        }

        ReportReq reportReq = new ReportReq(IdUtil.fastUUID(),
                device.getDeviceCode(),
                device.getGbDeviceChannelId(),
                DateUtil.formatBetween(startTime, endTime, BetweenFormatter.Level.SECOND),
                new ReportReq.TimeRange(startTime, endTime),
                DateUtil.date(),
                DataSizeUtil.format(fileSize));
        LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        reportConfig.getCustomHeaders().forEach(headers::add);
        request.getHeaderNames().asIterator().forEachRemaining(headerKey -> {
            String header = request.getHeader(headerKey);
            headers.add(headerKey, header);
        });
        log.info("上报调用信息 {}", reportReq);

        try{
            reportApi.report(headers, reportReq);
        } catch (Exception e){
            log.error("上报调用信息失败", e);
        }
    }
}
