package cn.com.ty.lift.system.homepage.service;

import cn.com.ty.lift.common.constants.ApiConstants;
import cn.com.ty.lift.common.constants.CommonEnum;
import cn.com.ty.lift.common.utils.ProjectUtils;
import cn.com.ty.lift.system.constants.CommonConstants;
import cn.com.ty.lift.system.homepage.dao.dto.request.LiftDataRequest;
import cn.com.ty.lift.system.homepage.dao.dto.response.PlatformLiftData;
import cn.com.ty.lift.system.homepage.dao.mapper.CommonDataMapper;
import cn.com.ty.lift.system.homepage.dao.mapper.HomeLiftDataMapper;
import cn.com.ty.lift.system.homepage.dao.model.EmergencyRecordDataModel;
import cn.com.ty.lift.system.homepage.dao.model.LiftMapDataModel;
import cn.com.ty.lift.system.homepage.dao.model.MtPlanDataModel;
import cn.com.ty.lift.system.homepage.dao.model.MtRecordDataModel;
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.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huangyuan
 * @date 2020/2/14
 * @description
 */
@Service
public class LiftDataService {

    @Resource
    private HomeLiftDataMapper homeLiftDataMapper;

    @Resource
    private CommonDataMapper commonDataMapper;

    /**
     * @param
     * @return
     * @description 获取电梯数量
     * @date 2020/2/14 1:02 下午
     */
    public RestResponse liftNum(LiftDataRequest liftDataRequest) {
        //获取初始化数据
        Map<Integer, Long> liftStatusToNum = CommonConstants.LIFT_DATA_STATUS_TO_NUM;
        //获取电梯数据
        List<LiftMapDataModel> liftMapDataModelList = getLiftMapDataModel(liftDataRequest);
        if (liftMapDataModelList != null && liftMapDataModelList.size() > 0) {
            //设置总电梯数
            liftStatusToNum.put(CommonConstants.LiftDataConstants.STATUS_ALL_LIFT, (long) liftMapDataModelList.size());
            //设置未定位电梯数
            long noLocateCount = liftMapDataModelList.stream()
                    .filter(liftMapDataModel -> liftMapDataModel.getLiftLocateStatus() == -1).count();
            liftStatusToNum.put(CommonConstants.LiftDataConstants.STATUS_NO_LOCATE, noLocateCount);
            //循环设置电梯维保数量
            for (int liftStatus : CommonConstants.LiftDataConstants.LIFT_DATA_STATUS_ARRAY) {
                //去除所有和未定位的电梯状态
                if (liftStatus != CommonConstants.LiftDataConstants.STATUS_ALL_LIFT
                        && liftStatus != CommonConstants.LiftDataConstants.STATUS_NO_LOCATE) {
                    setMapStatusNum(liftStatusToNum, liftMapDataModelList, liftStatus);
                }
            }
        }
        return RestResponse.success(ProjectUtils.transReturnMapToStatisticsKVModel(liftStatusToNum),
                ApiConstants.RESULT_SUCCESS, "获取电梯统计数据成功");
    }

    /**
     * @param
     * @return
     * @description 设置电梯状态对应的电梯数量
     * @date 2020/2/18 2:48 下午
     */
    private void setMapStatusNum(Map<Integer, Long> liftStatusToNum, List<LiftMapDataModel> liftMapDataModelList, int liftMapStatus) {
        long liftStatusCount = liftMapDataModelList.stream()
                .filter(liftMapDataModel -> liftMapDataModel.getLiftMapStatus() == liftMapStatus).count();
        liftStatusToNum.put(liftMapStatus, liftStatusCount);
    }

    /**
     * @param
     * @return
     * @description 获取电梯数据信息
     * @date 2020/2/14 1:07 下午
     */
    public RestResponse getLiftDataList(LiftDataRequest liftDataRequest) {
        List<LiftMapDataModel> returnLiftMapDataModelList = new ArrayList<>();
        //获取电梯数据
        List<LiftMapDataModel> liftMapDataModelList = getLiftMapDataModel(liftDataRequest);
        if (liftMapDataModelList != null && liftMapDataModelList.size() > 0) {
            //通过电梯状态进行分组，默认通过状态来获取
            Map<Integer, List<LiftMapDataModel>> statusToLiftData = liftMapDataModelList.stream()
                    .collect(Collectors.groupingBy(LiftMapDataModel::getLiftLocateStatus));
            if (statusToLiftData != null) {
                returnLiftMapDataModelList = statusToLiftData.get(liftDataRequest.getLiftDataStatus());
            }
            switch (liftDataRequest.getLiftDataStatus()) {
                case CommonConstants.LiftDataConstants.STATUS_ALL_LIFT:
                    returnLiftMapDataModelList = liftMapDataModelList;
                    break;
                case CommonConstants.LiftDataConstants.STATUS_NO_LOCATE:
                    //未定位的数据
                    returnLiftMapDataModelList = liftMapDataModelList.stream()
                            .filter(liftMapDataModel -> liftMapDataModel.getLiftLocateStatus() == -1)
                            .collect(Collectors.toList());
                    break;
            }
        }
        return RestResponse.success(returnLiftMapDataModelList, ApiConstants.RESULT_SUCCESS, "获取电梯数据成功");
    }

    /**
     * @param
     * @return
     * @description 获取企业电梯数据
     * @date 2020/2/18 2:16 下午
     */
    public List<LiftMapDataModel> getLiftMapDataModel(LiftDataRequest liftDataRequest) {
        //获取电梯数据
        List<LiftMapDataModel> liftMapDataModelList = homeLiftDataMapper.getLiftMapData(liftDataRequest);
        if (liftMapDataModelList != null && liftMapDataModelList.size() > 0) {
            //过滤停保电梯
            liftMapDataModelList = liftMapDataModelList.stream()
                    .filter(liftMapDataModel -> {
                        if (StringUtils.isNotBlank(liftMapDataModel.getLiftCompanyStatus())) {
                            return !CommonEnum.LiftStatus.STOP_INSURANCE.getCode().equals(
                                    liftMapDataModel.getLiftCompanyStatus());
                        }
                        return false;
                    }).collect(Collectors.toList());
            //设置起始时间
            setStartEndDate(liftDataRequest);
            //获取维保计划
            List<MtPlanDataModel> mtPlanDataModelList = commonDataMapper.getMtPlanData(liftDataRequest);
            //将维保计划数据转化为 liftId(电梯id) -> status(维保计划状态)
            final Map<Long, Integer> liftIdToMaintenancePlanStatus = getLiftIdToMaintenancePlanStatus(mtPlanDataModelList);
            //获取急修记录
            List<EmergencyRecordDataModel> emergencyRecordDataModelList =
                    commonDataMapper.getEmergencyRecordData(liftDataRequest);
            //将急修记录数据转化为 liftId(电梯id) -> status(急修状态)
            final Map<Long, Integer> liftIdToEmergencyStatus = getLiftIdToEmergencyStatus(emergencyRecordDataModelList);
            //设置电梯状态
            setLiftMapStatus(liftMapDataModelList, liftIdToMaintenancePlanStatus, liftIdToEmergencyStatus);
        }
        return liftMapDataModelList;
    }

    /**
     * @param
     * @return
     * @description 设置电梯状态
     * @date 2020/2/18 2:17 下午
     */
    private void setLiftMapStatus(List<LiftMapDataModel> liftMapDataModelList,
                                  Map<Long, Integer> liftIdToMaintenancePlanStatus,
                                  Map<Long, Integer> liftIdToEmergencyStatus) {
        //循环设置电梯状态
        liftMapDataModelList.forEach(liftMapDataModel -> {
            //设置电梯定位状态
            //-1表示电梯未定位
            liftMapDataModel.setLiftLocateStatus(-1);
            if (StringUtils.isNotBlank(liftMapDataModel.getCoordinate())) {
                //经纬度不为空说明电梯已经定位 1表示电梯已经定位
                liftMapDataModel.setLiftLocateStatus(1);
            }
            //设置电梯保养状态
            if (liftIdToMaintenancePlanStatus.size() > 0) {
                Integer maintenanceStatus = liftIdToMaintenancePlanStatus.get(liftMapDataModel.getLiftId());
                if (maintenanceStatus != null) {
                    if(maintenanceStatus == 0) {
                        //维保状态 - 待维保
                        liftMapDataModel.setLiftMapStatus(CommonConstants.LiftDataConstants.STATUS_WAIT_MAINTENANCE);
                    }
                    if(maintenanceStatus == 2) {
                        //维保状态 - 维保中
                        liftMapDataModel.setLiftMapStatus(CommonConstants.LiftDataConstants.STATUS_GO_MAINTENANCE);
                    }
                    if (maintenanceStatus == 1) {
                        //维保完成
                        liftMapDataModel.setLiftMapStatus(CommonConstants.LiftDataConstants.STATUS_HAVE_MAINTENANCE);
                    }
                }
            }
            //设置电梯急修状态
            if (liftIdToEmergencyStatus.size() > 0) {
                Integer emergencyStatus = liftIdToEmergencyStatus.get(liftMapDataModel.getLiftId());
                if (emergencyStatus != null) {
                    //有急修记录设置状态为待急修
                    liftMapDataModel.setLiftMapStatus(CommonConstants.LiftDataConstants.STATUS_WAIT_EMERGENCY);
                    if (emergencyStatus == 2 || emergencyStatus == 3) {
                        //状态2,3属于急修中
                        liftMapDataModel.setLiftMapStatus(CommonConstants.LiftDataConstants.STATUS_HAVE_EMERGENCY);
                    }
                }
            }
        });
    }

    /**
     * @param
     * @return
     * @description 设置起始时间
     * @date 2020/2/18 2:13 下午
     */
    private void setStartEndDate(LiftDataRequest liftDataRequest) {
        //获取昨天的时间
        String yesterdayStr = LocalDate.now().plusDays(-1).format(
                DateTimeFormatter.ofPattern(CommonConstants.PLAN_DATE_FORMAT));
        //获取明天的时间
        String tomorrowStr = LocalDate.now().format(
                DateTimeFormatter.ofPattern(CommonConstants.PLAN_DATE_FORMAT));
        //设置时间段
        liftDataRequest.setStartDateStr(yesterdayStr);
        liftDataRequest.setEndDateStr(tomorrowStr);
    }

    /**
     * @param
     * @return
     * @description 获取电梯id->电梯维保计划状态
     * @date 2020/2/18 1:32 下午
     */
    private Map<Long, Integer> getLiftIdToMaintenancePlanStatus(List<MtPlanDataModel> mtPlanDataModelList) {
        Map<Long, Integer> liftIdToMaintenancePlanStatus = new HashMap<>();
        if (mtPlanDataModelList != null && mtPlanDataModelList.size() > 0) {
            mtPlanDataModelList.forEach(mtPlanDataModel -> {
                liftIdToMaintenancePlanStatus.put(mtPlanDataModel.getLiftId(), mtPlanDataModel.getStatus());
            });
        }
        return liftIdToMaintenancePlanStatus;
    }

    /**
     * @param
     * @return
     * @description 获取电梯id->电梯维保状态
     * @date 2020/2/18 1:32 下午
     */
    private Map<Long, Integer> getLiftIdToEmergencyStatus(List<EmergencyRecordDataModel> emergencyRecordDataModelList) {
        if (emergencyRecordDataModelList != null && emergencyRecordDataModelList.size() > 0) {
            Map<Long, Integer> liftIdToEmergencyStatus = new HashMap<>();
            emergencyRecordDataModelList.forEach(emergencyRecordDataModel -> {
                liftIdToEmergencyStatus.put(emergencyRecordDataModel.getLiftId(), emergencyRecordDataModel.getStatus());
            });
            return liftIdToEmergencyStatus;
        }
        return new HashMap<>();
    }

    /**
     * @param liftDataRequest 平台电梯数量
     * @description 获取平台电梯数量
     * @date 2020/4/23 2:07 下午
     */
    public RestResponse liftPlatformNum(LiftDataRequest liftDataRequest) {
        Long totalLiftNum = homeLiftDataMapper.getTotalLiftNum(liftDataRequest);
        Map<String, Long> liftNum = new HashMap<>();
        liftNum.put("totalLiftNum", totalLiftNum != null ? totalLiftNum : 0L);
        return RestResponse.success(liftNum, ApiConstants.RESULT_SUCCESS, "获取总电梯数量成功");
    }

    /**
     * @param liftDataRequest 请求数据
     * @return 平台电梯数据
     * @description 获取平台电梯数据
     * @date 2020/4/23 2:57 下午
     */
    public RestResponse getPlatformLiftList(LiftDataRequest liftDataRequest) {
        List<PlatformLiftData> platformLiftData = homeLiftDataMapper.getPlatformLiftList(liftDataRequest);
        return RestResponse.success(platformLiftData, ApiConstants.RESULT_SUCCESS, "获取平台电梯数据成功");
    }
}
