package org.dromara.elevator.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.elevator.domain.vo.EFaultStatisticsChartVo;
import org.dromara.elevator.domain.vo.ProjectFaultVo;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.domain.vo.SysDeptVo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.service.ISysDeptService;
import org.springframework.stereotype.Service;
import org.dromara.elevator.domain.bo.EFaultStatisticsBo;
import org.dromara.elevator.domain.vo.EFaultStatisticsVo;
import org.dromara.elevator.domain.EFaultStatistics;
import org.dromara.elevator.mapper.EFaultStatisticsMapper;
import org.dromara.elevator.service.IEFaultStatisticsService;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 故障统计Service业务层处理
 *
 * @author ym
 * @date 2024-09-03
 */
@RequiredArgsConstructor
@Service
public class EFaultStatisticsServiceImpl implements IEFaultStatisticsService {

    private final EFaultStatisticsMapper baseMapper;

    private final DictService dictService;

    private final ISysDeptService deptService;

    private final SysDeptMapper deptMapper;

    /**
     * 查询故障统计
     *
     * @param id 主键
     * @return 故障统计
     */
    @Override
    public EFaultStatisticsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询故障统计列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 故障统计分页列表
     */
    @Override
    public TableDataInfo<EFaultStatisticsVo> queryPageList(EFaultStatisticsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EFaultStatistics> lqw = buildQueryWrapper(bo);
        Page<EFaultStatisticsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的故障统计列表
     *
     * @param bo 查询条件
     * @return 故障统计列表
     */
    @Override
    public List<EFaultStatisticsVo> queryList(EFaultStatisticsBo bo) {
        LambdaQueryWrapper<EFaultStatistics> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EFaultStatistics> buildQueryWrapper(EFaultStatisticsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EFaultStatistics> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getRegisterCode()), EFaultStatistics::getRegisterCode, bo.getRegisterCode());
        lqw.eq(StringUtils.isNotBlank(bo.getElevatorNum()), EFaultStatistics::getElevatorNum, bo.getElevatorNum());
        lqw.like(StringUtils.isNotBlank(bo.getElevatorName()), EFaultStatistics::getElevatorName, bo.getElevatorName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceCode()), EFaultStatistics::getDeviceCode, bo.getDeviceCode());
        lqw.eq(StringUtils.isNotBlank(bo.getTenementId()), EFaultStatistics::getTenementId, bo.getTenementId());
        lqw.like(StringUtils.isNotBlank(bo.getTenementName()), EFaultStatistics::getTenementName, bo.getTenementName());
        lqw.eq(StringUtils.isNotBlank(bo.getMaintenanceId()), EFaultStatistics::getMaintenanceId, bo.getMaintenanceId());
        lqw.like(StringUtils.isNotBlank(bo.getMaintenanceName()), EFaultStatistics::getMaintenanceName, bo.getMaintenanceName());
        lqw.eq(StringUtils.isNotBlank(bo.getFaultCode()), EFaultStatistics::getFaultCode, bo.getFaultCode());
        lqw.like(StringUtils.isNotBlank(bo.getFaultName()), EFaultStatistics::getFaultName, bo.getFaultName());
        lqw.eq(bo.getFaultNum() != null, EFaultStatistics::getFaultNum, bo.getFaultNum());
        lqw.eq(bo.getFaultTime() != null, EFaultStatistics::getFaultTime, bo.getFaultTime());
        lqw.eq(bo.getDeptId() != null, EFaultStatistics::getDeptId, bo.getDeptId());

        lqw.ge(Objects.nonNull(bo.getStartDate()), EFaultStatistics::getCreateTime, bo.getStartDate());
        lqw.le(Objects.nonNull(bo.getEndDate()), EFaultStatistics::getCreateTime, bo.getEndDate());

        lqw.ge(Objects.nonNull(bo.getHappendTimeStart()), EFaultStatistics::getFaultTime, bo.getHappendTimeStart());
        lqw.le(Objects.nonNull(bo.getHappendTimeEnd()), EFaultStatistics::getFaultTime, bo.getHappendTimeEnd());
        lqw.eq(Objects.nonNull(bo.getBrand()), EFaultStatistics::getBrand, bo.getBrand());
        lqw.eq(Objects.nonNull(bo.getUseScenario()), EFaultStatistics::getUseScenario, bo.getUseScenario());

        lqw.and(ObjectUtil.isNotNull(bo.getDeptId()), w -> {
            List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptId)
                .apply(DataBaseHelper.findInSet(bo.getDeptId(), "ancestors")));
            List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
            ids.add(bo.getDeptId());
            w.in(EFaultStatistics::getDeptId, ids);
        });

        return lqw;
    }

    /**
     * 新增故障统计
     *
     * @param bo 故障统计
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EFaultStatisticsBo bo) {
        EFaultStatistics add = MapstructUtils.convert(bo, EFaultStatistics.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改故障统计
     *
     * @param bo 故障统计
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EFaultStatisticsBo bo) {
        EFaultStatistics update = MapstructUtils.convert(bo, EFaultStatistics.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EFaultStatistics entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除故障统计信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean insertOrUpdateBatch(Collection<EFaultStatistics> statisticsList) {
        return baseMapper.insertOrUpdateBatch(statisticsList);
    }

    @Override
    public List<EFaultStatistics> selectFaultStatisticsList(Collection<String> eleNumList, LocalDate faultTime) {
        return baseMapper.selectList(Wrappers.<EFaultStatistics>lambdaQuery()
            .in(EFaultStatistics::getElevatorNum, eleNumList).eq(EFaultStatistics::getFaultTime, faultTime));
    }

    @Override
    public EFaultStatisticsChartVo queryChartList(EFaultStatisticsBo bo) {
        EFaultStatisticsChartVo statisticsChartVo = new EFaultStatisticsChartVo();
        LambdaQueryWrapper<EFaultStatistics> queryWrapper = buildQueryWrapper(bo);
        // 故障统计记录查询
        List<EFaultStatistics> faultStatistics = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(faultStatistics)) {
            return statisticsChartVo;
        }
        // 故障编号分组
        Map<String, List<EFaultStatistics>> faultCodeStatMap = faultStatistics.stream()
            .collect(Collectors.groupingBy(EFaultStatistics::getFaultCode));
        // 故障字典信息
        Map<String, String> faultTypeMap = dictService.getAllDictByDictType(bo.getFaultTypeKey());
        // 构建图表信息 故障次数、电梯数量倒序
        List<EFaultStatisticsChartVo.FaultStatisticsInfo> statisticsInfos = faultTypeMap.entrySet().stream()
            .map(item -> buildStatisticsInfo(item, faultCodeStatMap.get(item.getKey())))
            .sorted(Comparator.comparing(EFaultStatisticsChartVo.FaultStatisticsInfo::getFaultTotal, Comparator.reverseOrder())
                .thenComparing(EFaultStatisticsChartVo.FaultStatisticsInfo::getElevatorTotal, Comparator.reverseOrder()))
            .peek(item -> {
                statisticsChartVo.getFaultNameList().add(item.getFaultName());
                statisticsChartVo.getFaultTotalList().add(item.getFaultTotal());
            }).toList();
        statisticsChartVo.setStatisticsList(statisticsInfos);
        return statisticsChartVo;
    }

    @Override
    public List<EFaultStatistics> queryFaultStatisticsList(EFaultStatisticsBo bo) {
        LocalDate start = DateUtils.toLocalDate(bo.getStartTime());
        LocalDate end = DateUtils.toLocalDate(bo.getEndTime());
        return baseMapper.selectList(Wrappers.<EFaultStatistics>lambdaQuery()
            .in(CollectionUtils.isNotEmpty(bo.getElevatorNumList()), EFaultStatistics::getElevatorNum, bo.getElevatorNumList())
            .in(CollectionUtils.isNotEmpty(bo.getFaultCodeList()), EFaultStatistics::getFaultCode, bo.getFaultCodeList())
            .in(CollectionUtils.isNotEmpty(bo.getTenementIds()), EFaultStatistics::getTenementId, bo.getTenementIds())
            .in(CollectionUtils.isNotEmpty(bo.getMaintenanceIds()), EFaultStatistics::getMaintenanceId, bo.getMaintenanceIds())
            .between(EFaultStatistics::getFaultTime, start, end));
    }

    @Override
    public TableDataInfo<ProjectFaultVo> queryFaultPageList(EFaultStatisticsBo bo, PageQuery pageQuery) {
        Page<ProjectFaultVo> result = baseMapper.queryFaultPageList(pageQuery.build(), bo);
        if (CollectionUtils.isNotEmpty(result.getRecords())) {
            Map<Long, String> deptMap = deptService.selectDeptList(new SysDeptBo()).stream()
                .collect(Collectors.toMap(SysDeptVo::getDeptId, SysDeptVo::getDeptName, (o1, o2) -> o1));
            for (ProjectFaultVo record : result.getRecords()) {
                record.setDeptName(deptMap.get(record.getDeptId()));
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 构建故障图表信息
     *
     * @param faultDict           故障字典
     * @param faultStatisticsList 故障统计消息
     * @return 故障图表信息
     */
    private EFaultStatisticsChartVo.FaultStatisticsInfo buildStatisticsInfo(Map.Entry<String, String> faultDict,
                                                                            List<EFaultStatistics> faultStatisticsList) {
        EFaultStatisticsChartVo.FaultStatisticsInfo statisticsInfo = new EFaultStatisticsChartVo.FaultStatisticsInfo();
        statisticsInfo.setFaultCode(faultDict.getKey());
        statisticsInfo.setFaultName(faultDict.getValue());
        if (CollectionUtils.isNotEmpty(faultStatisticsList)) {
            statisticsInfo.setElevatorTotal(StreamUtils.toSet(faultStatisticsList, EFaultStatistics::getElevatorNum).size());
            statisticsInfo.setFaultTotal(faultStatisticsList.stream().mapToInt(EFaultStatistics::getFaultNum).sum());
        }
        return statisticsInfo;
    }
}
