package com.sckw.slope.detection.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.MessageLogEnum;
import com.sckw.core.model.enums.ReportTypeEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.FileUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.response.HttpResult;
import com.sckw.slope.detection.dao.mysql.KwsProjectMapper;
import com.sckw.slope.detection.dao.mysql.KwsReportDataMapper;
import com.sckw.slope.detection.dao.mysql.KwsReportTemplateMapper;
import com.sckw.slope.detection.model.dos.mysql.KwsProject;
import com.sckw.slope.detection.model.dos.mysql.KwsReportData;
import com.sckw.slope.detection.model.dto.HeaderData;
import com.sckw.slope.detection.model.param.StatementQuery;
import com.sckw.slope.detection.model.vo.ReportDetailVO;
import com.sckw.slope.detection.model.vo.ReportStatementVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description 报表service
 * @date 2023-10-31 10:10:39
 */
@Slf4j
@Service
public class ReportService {

    @Autowired
    CommonService commonService;

    @Autowired
    KwsReportDataMapper reportDataMapper;

    @Autowired
    KwsProjectMapper projectMapper;

    @Autowired
    KwsReportTemplateMapper reportTemplateMapper;

    public PageRes select(StatementQuery query, HttpServletRequest request) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
        String mountainId = commonService.getHeaderData(request).getMountainId();
        List<ReportStatementVO> list = reportDataMapper.selectListByReportNameAndProjectId(query, mountainId);
        PageInfo<ReportStatementVO> info = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(info, list);
        }
        List<String> collect = list.stream().map(ReportStatementVO::getProjectId).distinct().collect(Collectors.toList());
        List<KwsProject> kwsProjects = projectMapper.selectListData(collect, null);
        Map<Long, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(kwsProjects)) {
            map = kwsProjects.stream().collect(Collectors.toMap(KwsProject::getId, KwsProject::getName));
        }
        for (ReportStatementVO reportStatementVO : list) {
            reportStatementVO.setReportType(ReportTypeEnum.getDescription(reportStatementVO.getReportType()));
            reportStatementVO.setProjectName(map.get(Long.parseLong(reportStatementVO.getProjectId())));
            BigDecimal fileSizeNumber = FileUtils.getFileSize(new BigDecimal(reportStatementVO.getFileSize()).intValue(), "KB");
//            reportStatementVO.setFileSize(reportStatementVO.getFileSize());
            reportStatementVO.setFileSize(fileSizeNumber.setScale(2, RoundingMode.HALF_UP)+"KB");
        }
        return PageRes.build(info, list);
    }

    public HttpResult detail(String id, HttpServletRequest request) {
        ReportDetailVO vo = reportTemplateMapper.selectDataAndTemplate(Long.parseLong(id));
        if (vo != null) {
            vo.setType(ReportTypeEnum.getDescription(vo.getType()));
        }
        return HttpResult.ok(vo);
    }

    public HttpResult dels(String ids, HttpServletRequest request) {
        List<Long> list = StringUtils.splitStrToList(ids, Long.class);
        HeaderData headerData = commonService.getHeaderData(request);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(id -> {
                reportDataMapper.update(null, new LambdaUpdateWrapper<KwsReportData>()
                        .eq(KwsReportData::getId, id)
                        .eq(KwsReportData::getDelFlag, 0)
                        .set(KwsReportData::getDelFlag, 1));
            });
        }
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("count", list.size());
        commonService.insertLog(MessageLogEnum.REPORT_BATCH_DELETE, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    /**
     * @param ids
     * @param request
     * @return
     */
    public HttpResult export(String ids, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        List<Long> list = StringUtils.splitStrToList(ids, Long.class);
        List<KwsReportData> kwsReportData = reportDataMapper.selectList(new LambdaQueryWrapper<KwsReportData>()
                .eq(KwsReportData::getDelFlag, 0)
                .in(KwsReportData::getId, list));
        List<String> fileUrls = new ArrayList<>();
        if (!CollectionUtils.isEmpty(kwsReportData)) {
            fileUrls = kwsReportData.stream().map(KwsReportData::getFileUrl).collect(Collectors.toList());
            Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
            logMap.put("count", fileUrls.size());
            commonService.insertLog(MessageLogEnum.REPORT_BATCH_EXPORT, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
        }
        return HttpResult.ok(fileUrls);
    }
}
