package com.sckw.slope.detection.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.model.enums.MessageLogEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.web.response.HttpResult;
import com.sckw.slope.detection.dao.mysql.KwsDeviceMapper;
import com.sckw.slope.detection.dao.mysql.KwsLogMapper;
import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
import com.sckw.slope.detection.dao.tdengine.OriginalMapper;
import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
import com.sckw.slope.detection.model.dos.mysql.KwsCompany;
import com.sckw.slope.detection.model.dos.mysql.KwsDevice;
import com.sckw.slope.detection.model.dos.mysql.KwsLog;
import com.sckw.slope.detection.model.dto.HeaderData;
import com.sckw.slope.detection.model.param.OriginalDeviceQuery;
import com.sckw.slope.detection.model.param.ProjectLogQuery;
import com.sckw.slope.detection.model.vo.LogSelectVO;
import com.sckw.slope.detection.model.vo.OriginalDeviceVO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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-11-09 14:11:21
 */
@Slf4j
@Service
public class LogService {

    @Autowired
    KwsLogMapper logMapper;

    @Autowired
    KwsDeviceMapper deviceMapper;

    @Autowired
    SlopeDataMapper slopeDataMapper;

    @Autowired
    CommonService commonService;

    public PageRes select(ProjectLogQuery query, HttpServletRequest request) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
        HeaderData headerData = commonService.getHeaderData(request);
        List<KwsLog> kwsLogs = logMapper.selectList(new LambdaQueryWrapper<KwsLog>()
                .eq(StringUtils.isNotBlank(query.getType()), KwsLog::getType, query.getType())
                .eq(StringUtils.isNotBlank(headerData.getCompanyId()), KwsLog::getCompanyId, headerData.getCompanyId())
                .like(StringUtils.isNotBlank(query.getContent()), KwsLog::getContent, query.getContent())
                .orderByDesc(KwsLog::getCreateTime)
        );
        PageInfo<KwsLog> info = new PageInfo<>(kwsLogs);
        if (CollectionUtils.isEmpty(kwsLogs)) {
            return PageRes.build(info, kwsLogs);
        }
        List<LogSelectVO> list = new ArrayList<>();
        kwsLogs.forEach(projectLog -> {
            LogSelectVO vo = new LogSelectVO();
            BeanUtils.copyProperties(projectLog, vo);
            vo.setTypeName(MessageLogEnum.getEnumTitleByCode(projectLog.getType()));
            vo.setCreateByName(projectLog.getCreateBy() == null ? null : projectLog.getCreateBy().toString());
            list.add(vo);
        });
        return PageRes.build(info, list);
    }

    public HttpResult selectType(HttpServletRequest request) {
        List<KwsLog> kwsLogs = logMapper.selectList(null);
        List<String> typeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(kwsLogs)) {
            typeList = kwsLogs.stream().map(KwsLog::getType).distinct().collect(Collectors.toList());
        }
        List<Map<String, String>> returnList = new ArrayList<>();
        for (String s : typeList) {
            Map<String, String> map = new HashMap<>();
            map.put("name", MessageLogEnum.getEnumTitleByCode(s));
            map.put("value", s);
            returnList.add(map);
        }
        return HttpResult.ok(returnList);
    }

    @Autowired
    DevicesMapper devicesMapper;

    @Autowired
    OriginalMapper originalMapper;

//    public PageResult selectMetadata(Integer page, Integer pageSize, HttpServletRequest request) {
//        Integer newPage = (page - 1) * pageSize;
//        List<SlopeDataVo> list = slopeDataMapper.selectListByMaster(newPage, pageSize);
//        List<SlopeDataVo> listByMasterCount = slopeDataMapper.selectListByMasterCount(newPage, pageSize);
//        Long count = 0L;
//        if (!CollectionUtils.isEmpty(listByMasterCount)) {
//            count = listByMasterCount.stream().count();
//        }
//        if (!CollectionUtils.isEmpty(list)) {
//            for (SlopeDataVo slopeDataVo : listByMasterCount) {
//                Date rawId = slopeDataVo.getRawId();
//                Original original = originalMapper.selectByData(rawId);
//            }
//        }
//        PageResult build = PageResult.build(page, pageSize, count, list);
//        return build;
//    }

    public PageRes selectMetadata(OriginalDeviceQuery query, HttpServletRequest request) {
        List<OriginalDeviceVO> original = new ArrayList<>();
        PageInfo<OriginalDeviceVO> info = new PageInfo<>(original);
        Integer newPage = (query.getPage() - 1) * query.getPageSize();
        String deviceId = query.getDeviceId();
        KwsDevice kwsDevice = deviceMapper.selectByPrimaryKey(Long.parseLong(deviceId));
        String deviceSn = kwsDevice == null ? null : kwsDevice.getSnCode();
        if (StringUtils.isBlank(deviceSn)) {
            return PageRes.build(info, original);
        }
        int count = 0;
        try {
            original = originalMapper.selectListLimit(newPage, query.getPageSize(), deviceSn);
            count = originalMapper.selectDataCount(deviceSn);
        } catch (Exception e) {
            log.error("select original error :{}", e.getMessage(), e);
        }
        if (CollectionUtils.isEmpty(original)) {
            return PageRes.build(info, original);
        }
        original.forEach(originalDeviceVO -> {
            originalDeviceVO.setDeviceId(kwsDevice.getId().toString());
            originalDeviceVO.setDeviceName(kwsDevice.getName());
        });
        info.setPageNum(query.getPage());
        info.setPageSize(query.getPageSize());
        info.setTotal(count);
        int totalPages = (int) Math.ceil((double) count / query.getPageSize());
        info.setPages(totalPages);
        return PageRes.build(info, original);
    }
}
