package cn.com.ty.lift.batch.applet.service;

import cn.com.ty.lift.batch.applet.dao.mapper.MaintenanceDataMapper;
import cn.com.ty.lift.batch.applet.dao.model.MaintenanceDataModel;
import cn.com.ty.lift.batch.applet.dao.model.request.CommonRequest;
import cn.com.ty.lift.batch.applet.dao.model.response.MaintenanceOverViewResponse;
import cn.com.ty.lift.batch.applet.util.DataStatisticsUtil;
import cn.com.ty.lift.common.constants.ApiConstants;
import cn.com.ty.lift.common.utils.ProjectUtils;
import cn.com.xwy.boot.web.dto.RestResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author huangyuan
 * @date 2020/2/3
 * @description
 */
@Service
public class MaintenanceDataService {

    @Resource
    private MaintenanceDataMapper maintenanceDataMapper;

    /**
     * @param
     * @return
     * @description 将维保数据从redis中取出来
     * @date 2020/2/4 2:04 下午
     */
    public List<MaintenanceDataModel> getMaintenanceDataListFromRedis(CommonRequest CommonRequest) {
        //从redis中获取当前公司维保数据
        return maintenanceDataMapper.getMaintenanceDataList(CommonRequest);
    }

    /**
     * @param
     * @return
     * @description 获取维保统计总览情况
     * @date 2020/2/5 4:50 下午
     */
    public RestResponse maintenanceOverView(CommonRequest commonRequest) {
        //如果时间为空就赋予默认值：年初时间-当前时间
        if (StringUtils.isBlank(commonRequest.getStartTimeDateStr()) &&
                StringUtils.isBlank(commonRequest.getEndTimeDateStr())) {
            DataStatisticsUtil.initCommonRequest(commonRequest);
        }
        MaintenanceOverViewResponse maintenanceOverViewResponse = new MaintenanceOverViewResponse();
        //从redis中获取数据
        List<MaintenanceDataModel> maintenanceDataModelList = getMaintenanceDataListFromRedis(commonRequest);
        if (maintenanceDataModelList != null && maintenanceDataModelList.size() > 0) {
            //设置计划保养数
            maintenanceOverViewResponse.setPlanNum((long) maintenanceDataModelList.size());
            //保养状态 0:待保养 2:保养中 1:已完成 -1:超期
            //设置完成保养数
            long finishNum = maintenanceDataModelList.stream()
                    .filter(maintenanceDataModel -> {
                        if (maintenanceDataModel.getStatus() != null) {
                            return maintenanceDataModel.getStatus() == 1;
                        }
                        return false;
                    }).count();
            maintenanceOverViewResponse.setFinishNum(finishNum);
            setBeyondNum(maintenanceOverViewResponse, maintenanceDataModelList);
        }
        return RestResponse.success(maintenanceOverViewResponse, ApiConstants.RESULT_SUCCESS, "获取统计数据成功");
    }

    /**
     * @param
     * @return
     * @description 超期统计
     * @date 2020/2/5 4:53 下午
     */
    public RestResponse beyondStatistics(CommonRequest commonRequest) {
        Map<String, Long> projectNameToBeyondNum = new HashMap<>();
        //从redis中获取维保数据
        List<MaintenanceDataModel> maintenanceDataModelList = getMaintenanceDataListFromRedis(commonRequest);
        if (maintenanceDataModelList != null && maintenanceDataModelList.size() > 0) {
            //获取超期数
            maintenanceDataModelList = maintenanceDataModelList.stream().filter(maintenanceDataModel -> {
                if (maintenanceDataModel.getStatus() != null) {
                    return maintenanceDataModel.getStatus() == -1;
                }
                return false;
            }).collect(Collectors.toList());
            Map<String, Long> allProjectNameToBeyondNum = maintenanceDataModelList.stream()
                    .collect(Collectors.groupingBy(MaintenanceDataModel::getProjectName, Collectors.counting()));
            //通过超期台量倒序排列
            allProjectNameToBeyondNum = DataStatisticsUtil.sortByValue(allProjectNameToBeyondNum, true);
            if ("five".equals(commonRequest.getNumFlag())) {
                //获取前5的数据
                AtomicInteger i = new AtomicInteger(1);
                allProjectNameToBeyondNum.forEach((key, value) -> {
                    if (i.getAndIncrement() <= 5) {
                        projectNameToBeyondNum.put(key, value);
                    }
                });
            } else {
                allProjectNameToBeyondNum.forEach(projectNameToBeyondNum::put);
            }
        }
        return RestResponse.success(ProjectUtils.transReturnMapToStatisticsKVModel(projectNameToBeyondNum),
                ApiConstants.RESULT_SUCCESS, "获取统计数据成功");
    }

    /**
     * @param
     * @return
     * @description 设置超期数
     * @date 2020/2/9 9:57 下午
     */
    private void setBeyondNum(MaintenanceOverViewResponse maintenanceOverViewResponse,
                              List<MaintenanceDataModel> maintenanceDataModelList) {
        //设置总超期数
        long totalBeyondNum = maintenanceDataModelList.stream().filter(maintenanceDataModel -> {
            if (maintenanceDataModel.getStatus() != null) {
                return maintenanceDataModel.getStatus() == -1;
            }
            return false;
        }).count();
        maintenanceOverViewResponse.setTotalBeyondNum(totalBeyondNum);
        //获取超期的维保记录
        List<MaintenanceDataModel> beyondMaintenanceDataModelList = maintenanceDataModelList.stream()
                .filter(maintenanceDataModel -> {
                    if (maintenanceDataModel.getStatus() != null) {
                        return maintenanceDataModel.getStatus() == -1;
                    }
                    return false;
                }).collect(Collectors.toList());
        if (beyondMaintenanceDataModelList.size() > 0) {
            //设置超期类型
            setBeyondType(beyondMaintenanceDataModelList);
            //设置计划超期数
            long planBeyondNum = beyondMaintenanceDataModelList.stream()
                    .filter(maintenanceDataModel -> {
                        if (maintenanceDataModel.getBeyondType() != null) {
                            return maintenanceDataModel.getBeyondType() == 1;
                        }
                        return false;
                    }).count();
            //设置法规超期数
            long lawBeyondNum = beyondMaintenanceDataModelList.stream().filter(maintenanceDataModel -> {
                if (maintenanceDataModel.getBeyondType() != null) {
                    return maintenanceDataModel.getBeyondType() == 2;
                }
                return false;
            }).count();
            maintenanceOverViewResponse.setPlanBeyondNum(planBeyondNum);
            maintenanceOverViewResponse.setLawBeyondNum(lawBeyondNum);
        }
    }

    /**
     * @param
     * @return
     * @description 设置超期类型
     * @date 2020/2/9 10:01 下午
     */
    private void setBeyondType(List<MaintenanceDataModel> maintenanceDataModelList) {
        maintenanceDataModelList.forEach(maintenanceDataModel -> {
            maintenanceDataModel.setBeyondType(1);
        });
    }

    /**
     * @param commonRequest 无
     * @return 维保月份数据
     * @description 获取每月维保数据
     * @date 2020/5/22 10:41 上午
     */
    public RestResponse monthMaintenanceOverView(CommonRequest commonRequest) {
        Map<Integer, Map<Integer, Long>> monthToMaintenance = DataStatisticsUtil.initNum();
        DataStatisticsUtil.initCommonRequest(commonRequest);
        List<MaintenanceDataModel> maintenanceDataModelList = maintenanceDataMapper.getMonthMaintenanceData(commonRequest);
        if (maintenanceDataModelList != null && maintenanceDataModelList.size() > 0) {
            //月份 -> 维保记录数据
            Map<Integer, List<MaintenanceDataModel>> monthToMaintenanceData = maintenanceDataModelList.stream()
                    .collect(Collectors.groupingBy(maintenanceDataModel ->
                            DataStatisticsUtil.getMonth(maintenanceDataModel.getPlanDate())));
            //封装数据
            if (monthToMaintenanceData != null && monthToMaintenanceData.size() > 0) {
                monthToMaintenance.keySet().forEach(month -> {
                    Map<Integer, Long> statusToNum = monthToMaintenance.get(month);
                    List<MaintenanceDataModel> maintenanceDataModels = monthToMaintenanceData.get(month);
                    if (maintenanceDataModels != null && maintenanceDataModels.size() > 0) {
                        //计划维保的数量
                        statusToNum.put(0, (long) maintenanceDataModels.size());
                        //维保完成的数据
                        long maintenanceNum = maintenanceDataModels.stream().filter(maintenanceDataModel -> {
                            if (maintenanceDataModel.getStatus() != null) {
                                return maintenanceDataModel.getStatus() == 1;
                            }
                            return false;
                        }).count();
                        statusToNum.put(1, maintenanceNum);
                    }
                    monthToMaintenance.put(month, statusToNum);
                });
            }
        }
        return RestResponse.success(ProjectUtils.transReturnMapToStatisticsKVModel(monthToMaintenance));
    }
}
