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.exception.BusinessException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.DictEnum;
import com.sckw.core.model.enums.MessageLogEnum;
import com.sckw.core.model.enums.ReportEnum;
import com.sckw.core.model.enums.ReportTypeEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.IdWorker;
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.dos.mysql.KwsReportTemplate;
import com.sckw.slope.detection.model.dto.*;
import com.sckw.slope.detection.model.param.StatementQuery;
import com.sckw.slope.detection.model.vo.KwsReportTemplateVO;
import com.sckw.slope.detection.model.vo.ReportStatementVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description
 * @date 2023-11-01 14:11:07
 */
@Slf4j
@Service
public class ReportTemplateService {

    @Autowired
    CommonService commonService;

    @Autowired
    KwsProjectMapper projectMapper;

    @Autowired
    KwsReportTemplateMapper reportTemplateMapper;

    @Autowired
    KwsReportDataMapper reportDataMapper;

    @Transactional
    public HttpResult add(ReportTemplateAddDTO reportTemplateDTO, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        String projectId = reportTemplateDTO.getProjectId();
        KwsReportTemplate template = new KwsReportTemplate();
        long id = new IdWorker(NumberConstant.ONE).nextId();
        template.setId(id);
        template.setProjectId(projectId);
        template.setMountainId(headerData.getMountainId());
        template.setName(reportTemplateDTO.getName());
        template.setCompanyId(headerData.getCompanyId());
        String type = reportTemplateDTO.getType();
        String status = reportTemplateDTO.getStatus();
//        if (Objects.isNull(status)) {
//            status = ReportEnum.FORBIDDEN.getStatus();
//        }
//        String tabulationTime = "";
//        if (ReportTypeEnum.DAY.getStatus().equals(type)) {
//            tabulationTime = ReportTypeEnum.DAY.getValue();
//        } else if (ReportTypeEnum.WEEK.getStatus().equals(type)) {
//            tabulationTime = ReportTypeEnum.WEEK.getValue();
//        } else if (ReportTypeEnum.MONTH.getStatus().equals(type)) {
//            tabulationTime = ReportTypeEnum.MONTH.getValue();
//        } else {
//            throw new BusinessException("报表类型错误");
//        }
        template.setTabulationTime(type);
        template.setType(Integer.valueOf(reportTemplateDTO.getType()));
        template.setPartNames(reportTemplateDTO.getPartNames());
        template.setIntergrationNames(reportTemplateDTO.getIntergrationNames());
        template.setStatus(Integer.valueOf(status));
        template.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        LocalDateTime now = LocalDateTime.now();
        template.setCreateTime(now);
        template.setUpdateTime(now);
        reportTemplateMapper.insert(template);
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getId, Long.parseLong(projectId)));
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("templateName", reportTemplateDTO.getName());
        commonService.insertLog(MessageLogEnum.ADD_REPORT_TEMPLATE, headerData, logMap, headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        return HttpResult.ok();
    }

    public HttpResult detail(String id, HttpServletRequest request) {
        KwsReportTemplate template = reportTemplateMapper.selectOne(new LambdaQueryWrapper<KwsReportTemplate>().eq(KwsReportTemplate::getId, id));
        if (template == null) {
            return HttpResult.ok(new KwsReportTemplate());
        }
        KwsReportTemplateVO vo = new KwsReportTemplateVO();
        BeanUtils.copyProperties(template, vo);

        return HttpResult.ok(vo);
    }

    @Transactional
    public HttpResult update(ReportTemplateUpdateDTO reportTemplateUpdateDTO, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        String id = reportTemplateUpdateDTO.getId();
        KwsReportTemplate template = reportTemplateMapper.selectOne(new LambdaQueryWrapper<KwsReportTemplate>().eq(KwsReportTemplate::getId, id));
        if (template == null) {
            return HttpResult.ok(new KwsReportTemplate());
        }
//        template.setProjectId();
        template.setName(reportTemplateUpdateDTO.getName());
//        template.setCompanyId();
        String type = reportTemplateUpdateDTO.getType();
        String tabulationTime = "";
        if (ReportTypeEnum.DAY.getStatus().equals(type)) {
            tabulationTime = ReportTypeEnum.DAY.getValue();
        } else if (ReportTypeEnum.WEEK.getStatus().equals(type)) {
            tabulationTime = ReportTypeEnum.WEEK.getValue();
        } else if (ReportTypeEnum.MONTH.getStatus().equals(type)) {
            tabulationTime = ReportTypeEnum.MONTH.getValue();
        } else {
            throw new BusinessException("报表类型错误");
        }
        template.setTabulationTime(tabulationTime);
        template.setType(Integer.valueOf(type));
        template.setPartNames(reportTemplateUpdateDTO.getPartNames());
        template.setIntergrationNames(reportTemplateUpdateDTO.getIntergrationNames());
        template.setStatus(Integer.parseInt(reportTemplateUpdateDTO.getStatus()));
        template.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
        template.setUpdateTime(LocalDateTime.now());
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getId, Long.parseLong(template.getProjectId())));
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("templateName", template.getName());
        commonService.insertLog(MessageLogEnum.UPDATE_REPORT_TEMPLATE, headerData, logMap, headerData.getUpdateBy() == null ?
                null : Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    @Transactional
    public HttpResult enable(IsEnableDTO isEnable, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        Integer status = 1;
        String flag = isEnable.getFlag();
        if ("1".equals(flag)){
            status=0;
        }
        Long templateId = Long.parseLong(isEnable.getId());
        KwsReportTemplate template = reportTemplateMapper.selectOne(new LambdaQueryWrapper<KwsReportTemplate>()
                .eq(KwsReportTemplate::getId, templateId)
                .eq(KwsReportTemplate::getMountainId, headerData.getMountainId()));
        if (template == null) {
            throw new BusinessException("模板数据异常!");
        }
        reportTemplateMapper.update(null, new LambdaUpdateWrapper<KwsReportTemplate>()
                .set(KwsReportTemplate::getStatus, status)
                .set(KwsReportTemplate::getUpdateTime, LocalDateTime.now())
                .set(KwsReportTemplate::getUpdateBy, (headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy())))
                .eq(KwsReportTemplate::getId, templateId)
        );
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getId, Long.parseLong(template.getProjectId())));
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("templateName", template.getName());
        MessageLogEnum messageLogEnum = MessageLogEnum.FORBIDDEN_REPORT_TEMPLATE;;
        if ("1".equals(flag)) {
            messageLogEnum = MessageLogEnum.ENABLE_REPORT_TEMPLATE;
        }
        commonService.insertLog(messageLogEnum, headerData, logMap, headerData.getUpdateBy() == null ?
                null : Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok("修改成功");
    }

    public PageRes select(StatementQuery query, HttpServletRequest request) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
        String mountainId = commonService.getHeaderData(request).getMountainId();
        List<ReportStatementVO> list = reportTemplateMapper.selectListByReportNameAndProjectIdAndCompany(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).collect(Collectors.toList());
        List<KwsProject> kwsProjects = projectMapper.selectList(new LambdaQueryWrapper<KwsProject>()
                .in(KwsProject::getId, collect)
                .eq(KwsProject::getDelFlag, 0));
        Map<Long, String> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(kwsProjects)) {
            map = kwsProjects.stream().collect(Collectors.toMap(KwsProject::getId, KwsProject::getName));
        }
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.THRESHOLD_TYPE);
        Map<String, SystemDict> alarmDetailType = commonService.getDictByDictCode(DictEnum.ALARM_DETAIL_TYPE);
        for (ReportStatementVO reportStatementVO : list) {
            reportStatementVO.setStatusLabel(ReportEnum.getDescription(reportStatementVO.getStatus()));
            reportStatementVO.setReportType(ReportTypeEnum.getDescription(reportStatementVO.getReportType()));
            reportStatementVO.setProjectName(map.get(Long.parseLong(reportStatementVO.getProjectId())));
            reportStatementVO.setTabulationTime(ReportTypeEnum.getValue(reportStatementVO.getTabulationTime()));
        }
        return PageRes.build(info, list);
    }

    @Transactional
    public HttpResult dels(String id, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        KwsReportTemplate template = reportTemplateMapper.selectOne(new LambdaQueryWrapper<KwsReportTemplate>().eq(KwsReportTemplate::getDelFlag, 0)
                .eq(KwsReportTemplate::getId, Long.parseLong(id)));
        if (template == null) {
            throw new BusinessException("模板删除失败,参数错误");
        }
        reportTemplateMapper.update(null, new LambdaUpdateWrapper<KwsReportTemplate>()
                .eq(KwsReportTemplate::getId, Long.parseLong(id))
                .set(KwsReportTemplate::getUpdateTime, LocalDateTime.now())
                .set(KwsReportTemplate::getDelFlag, NumberConstant.ONE)
                .set(KwsReportTemplate::getUpdateBy, (headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy())))
                .set(KwsReportTemplate::getStatus, NumberConstant.ONE)
        );
        reportDataMapper.update(null, new LambdaUpdateWrapper<KwsReportData>()
                .eq(KwsReportData::getTemplateId, Long.parseLong(id))
                .set(KwsReportData::getDelFlag, NumberConstant.ONE)
        );
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getId, Long.parseLong(template.getProjectId())));
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("templateName", template.getName());
        commonService.insertLog(MessageLogEnum.DELETE_REPORT_TEMPLATE, headerData, logMap, headerData.getUpdateBy() == null ?
                null : Long.parseLong(headerData.getUpdateBy()));

        return HttpResult.ok("删除成功");
    }
}
