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

import cn.com.ty.lift.batch.applet.dao.mapper.EmergencyRepairDataMapper;
import cn.com.ty.lift.batch.applet.dao.model.EmergencyRepairDataModel;
import cn.com.ty.lift.batch.applet.dao.model.request.EmergencyRepairDataRequest;
import cn.com.ty.lift.batch.applet.dao.model.response.EmergencyTimeStatisticsResponse;
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 cn.hutool.core.date.DatePattern;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    @Resource
    private EmergencyRepairDataMapper emergencyRepairDataMapper;

    /**
     * @param emergencyRepairDataRequest 起始时间，结束时间
     * @return
     * @description 获取年度急修数据
     * @date 2020/2/3 4:28 下午
     */
    public List<EmergencyRepairDataModel> getEmergencyRepairDataListFromRedis(EmergencyRepairDataRequest
                                                                                      emergencyRepairDataRequest) {
        setEmergencyRepairTime(emergencyRepairDataRequest);
        //从redis获取当前公司的急修信息
        List<EmergencyRepairDataModel> emergencyRepairDataModelList =
                emergencyRepairDataMapper.getEmergencyRepairDataList(emergencyRepairDataRequest);
        if (emergencyRepairDataModelList != null && emergencyRepairDataModelList.size() > 0) {
            emergencyRepairDataModelList.forEach(emergencyRepairDataModel -> {
                //计算接单时长
                if (emergencyRepairDataModel.getAssignTime() != null && emergencyRepairDataModel.getTakingTime() != null) {
                    emergencyRepairDataModel.setTakingTimeLength(DataStatisticsUtil.getDiffMinute(
                            emergencyRepairDataModel.getAssignTime(), emergencyRepairDataModel.getTakingTime()));
                }
                //计算到达时长
                if (emergencyRepairDataModel.getTakingTime() != null && emergencyRepairDataModel.getArriveTime() != null) {
                    emergencyRepairDataModel.setArriveTimeLength(DataStatisticsUtil.getDiffMinute(
                            emergencyRepairDataModel.getTakingTime(), emergencyRepairDataModel.getArriveTime()));
                }
                //计算修理时长
                if (emergencyRepairDataModel.getArriveTime() != null && emergencyRepairDataModel.getRecoveryDate() != null) {
                    emergencyRepairDataModel.setFixTimeLength(DataStatisticsUtil.getDiffMinute(
                            emergencyRepairDataModel.getTakingTime(), emergencyRepairDataModel.getRecoveryDate()));
                }
            });
        }
        if (emergencyRepairDataModelList != null && emergencyRepairDataModelList.size() > 0) {
            //通过区域id过滤数据
            if (emergencyRepairDataRequest.getRegionId() != null) {
                emergencyRepairDataModelList = emergencyRepairDataModelList.stream()
                        .filter(emergencyRepairDataModel -> emergencyRepairDataModel.getRegionId().equals(
                                emergencyRepairDataRequest.getRegionId())).collect(Collectors.toList());
            }
            //通过状态过滤数据
            if (emergencyRepairDataRequest.getStatus() != null) {
                emergencyRepairDataModelList = emergencyRepairDataModelList.stream().filter(emergencyRepairDataModel -> {
                    if (emergencyRepairDataModel.getStatus() != null) {
                        return emergencyRepairDataModel.getStatus().equals(emergencyRepairDataRequest.getStatus());
                    }
                    return false;
                }).collect(Collectors.toList());
            }
        }
        return emergencyRepairDataModelList;
    }

    /**
     * @param
     * @return
     * @description 以月为维度统计每个月急修的电梯台量
     * @date 2020/2/4 3:04 下午
     */
    public RestResponse getEachMonthUnits(EmergencyRepairDataRequest emergencyRepairDataRequest) {
        Map<String, Long> monthToUnits = DataStatisticsUtil.initDateMap();
        //设置时间段
        DataStatisticsUtil.setBeginYearToNow(emergencyRepairDataRequest);
        //从redis中获取时间段内的急修数据
        List<EmergencyRepairDataModel> emergencyRepairDataModelList =
                getEmergencyRepairDataListFromRedis(emergencyRepairDataRequest);
        if (emergencyRepairDataModelList != null && emergencyRepairDataModelList.size() > 0) {
            //将数据组合成月->台量的map
            Map<String, Long> monthToUnitsRow = emergencyRepairDataModelList.stream()
                    .collect(Collectors.groupingBy(emergencyRepairDataModel ->
                            DataStatisticsUtil.getMonthStr(emergencyRepairDataModel.getCallerDate()), Collectors.counting()));
            //将monthToUnitsRow月份对应台量的值放入monthToUnits中
            monthToUnitsRow.forEach(monthToUnits::put);
        }
        return RestResponse.success(ProjectUtils.transReturnMapToStatisticsKVModel(monthToUnits),
                ApiConstants.RESULT_SUCCESS, "获取统计数据成功");
    }

    /**
     * @param
     * @return
     * @description 急修时间统计
     * @date 2020/2/5 9:20 上午
     */
    public RestResponse emergencyTimeStatistics(EmergencyRepairDataRequest emergencyRepairDataRequest) {
        //获取急修完成的急修信息
        //emergencyRepairDataRequest.setStatus(Validate.Repair.STATUS_FINISH);
        List<EmergencyRepairDataModel> emergencyRepairDataModelList =
                getEmergencyRepairDataListFromRedis(emergencyRepairDataRequest);
        EmergencyTimeStatisticsResponse emergencyTimeStatisticsResponse = new EmergencyTimeStatisticsResponse();
        if (emergencyRepairDataModelList != null && emergencyRepairDataModelList.size() > 0) {
            //1.设置接单时间
            //平均接单时间
            emergencyTimeStatisticsResponse.setAverageTakingTime(
                    emergencyRepairDataModelList.stream().mapToLong(
                            EmergencyRepairDataModel::getTakingTimeLength).average().getAsDouble());
            //最大接单时间
            emergencyTimeStatisticsResponse.setMaxTakingTime(
                    emergencyRepairDataModelList.stream().mapToLong(
                            EmergencyRepairDataModel::getTakingTimeLength).max().getAsLong());
            //2.设置到场时间
            //平均到场时间
            emergencyTimeStatisticsResponse.setAverageArriveTime(
                    emergencyRepairDataModelList.stream().mapToLong(
                            EmergencyRepairDataModel::getArriveTimeLength).average().getAsDouble());
            //设置最大到场时间
            emergencyTimeStatisticsResponse.setMaxArriveTime(
                    emergencyRepairDataModelList.stream().mapToLong(
                            EmergencyRepairDataModel::getArriveTimeLength).max().getAsLong());
            //3.设置修梯时间
            //平均修梯时间
            emergencyTimeStatisticsResponse.setAverageFixTime(
                    emergencyRepairDataModelList.stream().mapToLong(
                            EmergencyRepairDataModel::getFixTimeLength).average().getAsDouble());
            //设置最大修梯时间
            emergencyTimeStatisticsResponse.setMaxFixTime(
                    emergencyRepairDataModelList.stream().mapToLong(
                            EmergencyRepairDataModel::getFixTimeLength).max().getAsLong());
        }
        return RestResponse.success(emergencyTimeStatisticsResponse, ApiConstants.RESULT_SUCCESS, "获取统计数据成功");
    }

    /**
     * @param
     * @return
     * @description 获取急修状态
     * @date 2020/2/5 11:49 上午
     */
    public RestResponse emergencyStatus(EmergencyRepairDataRequest emergencyRepairDataRequest) {
        List<EmergencyRepairDataModel> emergencyRepairDataModelList =
                getEmergencyRepairDataListFromRedis(emergencyRepairDataRequest);
        if (emergencyRepairDataModelList != null && emergencyRepairDataModelList.size() > 0) {
            //通过发起时间降序排列
            emergencyRepairDataModelList = emergencyRepairDataModelList.stream()
                    .sorted(Comparator.comparing(EmergencyRepairDataModel::getCallerDate).reversed()).collect(Collectors.toList());
            if ("five".equals(emergencyRepairDataRequest.getNumFlag())) {
                //通过发起急修时间降序排列,并获取前5条数据
                emergencyRepairDataModelList = emergencyRepairDataModelList.stream().limit(5)
                        .collect(Collectors.toList());
            }
        }
        return RestResponse.success(emergencyRepairDataModelList, ApiConstants.RESULT_SUCCESS, "获取统计数据成功");
    }

    /**
     * @param
     * @return
     * @description
     * @date 2020/5/15 11:06 上午
     */
    private void setEmergencyRepairTime(EmergencyRepairDataRequest emergencyRepairDataRequest) {
        if (StringUtils.isBlank(emergencyRepairDataRequest.getEndTimeDateStr()) ||
                StringUtils.isBlank(emergencyRepairDataRequest.getEndTimeDateStr())) {
            //设置时间
            emergencyRepairDataRequest.setStartTimeDateStr(DataStatisticsUtil.getYearFirstTime()
                    .format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
            emergencyRepairDataRequest.setEndTimeDateStr(LocalDateTime.now()
                    .format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        }
    }
}
