package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FireBrigadeResourceDto;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyCarServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.CarStatusInfoDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerCarCountDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerCompanyCountDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferCompanyDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferCompanyResourcesDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferResourceDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferSimpleDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ResourceStatisticsDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.*;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertFeedbackStatusEnum;
import com.yeejoin.amos.boot.module.jcs.api.enums.DutyInfoEnum;
import com.yeejoin.amos.boot.module.jcs.api.enums.FireBrigadeTypeEnum;
import com.yeejoin.amos.boot.module.jcs.api.enums.FireCarStatusEnum;
import com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.IPowerTransferService;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

/**
 * 力量调派 服务实现类
 *
 * @author tb
 * @date 2021-06-17
 */
@Service
public class PowerTransferServiceImpl extends BaseService<PowerTransferDto, PowerTransfer, PowerTransferMapper> implements IPowerTransferService {

    @Autowired
    AlertCalledServiceImpl alertCalledService;

    @Autowired
    PowerTransferCompanyServiceImpl powerTransferCompanyService;

    @Autowired
    PowerTransferCompanyResourcesServiceImpl powerTransferCompanyResourcesService;

    @Autowired
    TemplateServiceImpl templateService;

    @Autowired
    AlertFormValueServiceImpl alertFormValueService;

    @Autowired
    EquipFeignClient equipFeignService;

    @Autowired
    FireTeamServiceImpl fireTeamService;

    @Autowired
    PowerTransferMapper powerTransferMapper;

    @Autowired
    EquipFeignClient equipFeignClient;

    @Autowired
    private EmqKeeper emqKeeper;

    @Value("${mqtt.topic.command.power.deployment}")
    private String topic;

    @Autowired
    private DutyCarServiceImpl dutyCarService;

    @Override
    public PowerTransferSimpleDto getPowerTransferList(Long alertCalledId) {
        List<PowerTransferCompanyResourcesDto> powerTransferList =
                this.baseMapper.getPowerTransferList(alertCalledId);
        PowerTransferSimpleDto powerTransferSimpleDto = new PowerTransferSimpleDto();
        int resourcesCount = powerTransferList.size();
        powerTransferSimpleDto.setResourcesCount(resourcesCount);
        powerTransferSimpleDto.setResourcesList(powerTransferList);
        return powerTransferSimpleDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createPowerTransfer(PowerTransferDto powerTransferDto) {
        try {
            // 获取调派ID
            Long alertCalledId = powerTransferDto.getAlertCalledId();
            int count = count(new QueryWrapper<PowerTransfer>().eq("alert_called_id", alertCalledId));
            String dispatch_num = alertCalledId.toString() + (count + 1);

            // 获取警情详情
            AlertCalled alertCalled = alertCalledService.getById(alertCalledId);

            // 创建力量调派
            PowerTransfer powerTransfer = new PowerTransfer();
            BeanUtils.copyProperties(powerTransferDto, powerTransfer);
            BeanUtils.copyProperties(alertCalled, powerTransfer);
            powerTransfer.setDispatchNum(dispatch_num);
            powerTransfer.setSequenceNbr(null);

            save(powerTransfer);
            Long powerTransferSequenceNbr = powerTransfer.getSequenceNbr();

            // 获取任务派发模板
            Template template = templateService.getOne(new QueryWrapper<Template>().eq("type",
                    alertCalled.getAlertType()).eq("format", false));
            String content = template.getContent();
            Map<String, String> definitions = new HashMap<>();
            initDefinitions(definitions, alertCalled, powerTransferDto);

            // 创建力量调派单位
            createPowerTransferCompany(powerTransferDto, powerTransferSequenceNbr, definitions, content);

            //发送调派通知
            //通知实战指挥页面发送mqtt 默认发送 String 类型 0, 新警情 1 警情状态变化
            emqKeeper.getMqttClient().publish(topic, "0".getBytes(), RuleConfig.DEFAULT_QOS, true);
        } catch (MqttException e) {
            throw new RuntimeException();
        }

        return true;
    }

    @Override
    public List<FireBrigadeResourceDto> getPowerTree(String type) {
        List<FireBrigadeResourceDto> fireBrigadeResourceList = Lists.newArrayList();

        if(type!=null&&!"".equals(type)){
            // 3.消防队伍-监控大队
            List<FireBrigadeResourceDto> monitorFireBrigadeList1 = fireTeamService.listMonitorFireBrigade(FireBrigadeTypeEnum.医疗救援队.getCode());
            FireBrigadeResourceDto monitorResourceDto1 = new FireBrigadeResourceDto();
            monitorResourceDto1.setId("-1");
            monitorResourceDto1.setName(FireBrigadeTypeEnum.医疗救援队.getName());
            monitorResourceDto1.setType(FireBrigadeTypeEnum.医疗救援队.getKey());
            monitorResourceDto1.setChildren(monitorFireBrigadeList1);
            if (!CollectionUtils.isEmpty(monitorFireBrigadeList1)) {
                fireBrigadeResourceList.add(monitorResourceDto1);
            }
        }

        // 1.调用装备服务接口查询车辆列表
        List<FireBrigadeResourceDto> fireCarDtoList = Lists.newArrayList();
        ResponseModel<Object> result = equipFeignService.getFireCarListAll();
//        if (!ObjectUtils.isEmpty(result)) {
//            List<Map<String, Object>> fireCarListMapList = (List<Map<String, Object>>) result.getResult();
//            if (!ValidationUtil.isEmpty(fireCarListMapList)) {
//                fireCarListMapList.stream().filter(car -> ObjectUtils.isNotEmpty(car.get("teamId"))).filter(car ->
//                        FireCarStatusEnum.执勤.getCode().equals(car.get("carState")) //TODO 后续如果需要多个状态需要删掉这个过滤条件
//                                || FireCarStatusEnum.出动.getCode().equals(car.get("carState"))).forEach(car -> {
//
//                    FireBrigadeResourceDto fireCarDto = (FireBrigadeResourceDto) Bean.mapToBean(car, FireBrigadeResourceDto.class);
//                    // TODO 后期根据车物联状态来返回，现在为"(装备)在位=执勤","(装备)执勤=出动"
//                    if (FireCarStatusEnum.执勤.getCode().equals(fireCarDto.getCarState())) {
//                        fireCarDto.setCarStateDesc(FireCarStatusEnum.执勤.getName());
//                    } else {
//                        fireCarDto.setCarState(FireCarStatusEnum.出动.getCode());
//                        fireCarDto.setCarStateDesc(FireCarStatusEnum.出动.getName());
//                    }
//                    fireCarDtoList.add(fireCarDto);
//                });
//            }
//        }


        //查询车辆当前任务状态
        QueryWrapper<PowerTransferCompanyResources> queryWrapper = new QueryWrapper<>();
       // queryWrapper.notIn("car_status", FireCarStatusEnum.返队.getCode(),FireCarStatusEnum.加油.getCode(),FireCarStatusEnum.演练.getCode(),FireCarStatusEnum.训练.getCode(),FireCarStatusEnum.试车.getCode());
        queryWrapper.eq("status",FireCarStatusEnum.执行中.getCode() );
        List<PowerTransferCompanyResources> alertFormValue = powerTransferCompanyResourcesService.list(queryWrapper);

        Map<String, String> appleMap = alertFormValue!=null&&alertFormValue.size()>0?alertFormValue.stream().collect(Collectors.toMap(PowerTransferCompanyResources::getResourcesId, PowerTransferCompanyResources::getCarStatus)):null;
        if (!ObjectUtils.isEmpty(result)) {
            List<Map<String, Object>> fireCarListMapList = (List<Map<String, Object>>) result.getResult();
            if (!ValidationUtil.isEmpty(fireCarListMapList)) {
                fireCarListMapList.stream().filter(car -> ObjectUtils.isNotEmpty(car.get("teamId"))).forEach(car -> {

                    FireBrigadeResourceDto fireCarDto = (FireBrigadeResourceDto) Bean.mapToBean(car, FireBrigadeResourceDto.class);
                    // TODO 后期根据车物联状态来返回，现在为"(装备)在位=执勤","(装备)执勤=出动"
                    if (FireCarStatusEnum.执勤.getCode().equals(fireCarDto.getCarState())) {
                        fireCarDto.setCarStateDesc(FireCarStatusEnum.执勤.getName());
                    } else {
                       if(appleMap!=null){
                          String state= appleMap.containsKey(car.get("id"))?appleMap.get(car.get("id")):null;
                           fireCarDto.setCarState(state);
                           fireCarDto.setCarStateDesc(state!=null?FireCarStatusEnum.getEnum(state).getName():null);
                       }else{
                           fireCarDto.setCarState(null);
                           fireCarDto.setCarStateDesc(null);
                       }
                 }
                    fireCarDtoList.add(fireCarDto);
                });
            }
        }


        // 2.查询消防队伍列表
        List<FireTeam> fullTimeFireBrigadeList = fireTeamService.list(new QueryWrapper<FireTeam>().eq("type_code", FireBrigadeTypeEnum.专职消防队.getCode()).eq("is_delete", 0));
        if (!CollectionUtils.isEmpty(fullTimeFireBrigadeList)) {
            Map<String, List<FireBrigadeResourceDto>> resultMap = fireCarDtoList.stream().collect(Collectors.groupingBy(FireBrigadeResourceDto::getTeamId));
            if (!ValidationUtil.isEmpty(fullTimeFireBrigadeList)) {
                fullTimeFireBrigadeList.forEach(brigade -> {
                    if (!CollectionUtils.isEmpty(resultMap.get(brigade.getSequenceNbr().toString()))) {
                        FireBrigadeResourceDto fireCarResourceDto = new FireBrigadeResourceDto();
                        List<FireBrigadeResourceDto> fireBrigadeResourceDtoList =
                                resultMap.get(brigade.getSequenceNbr().toString());
                        long onDutyCarCount =
                                fireBrigadeResourceDtoList.stream().filter(car -> FireCarStatusEnum.执勤.getCode().equals(car.getCarState())).count();
                        long outCarCount = fireBrigadeResourceDtoList.size() - onDutyCarCount;
                        fireCarResourceDto.setId(brigade.getSequenceNbr().toString());
                        fireCarResourceDto.setType(FireBrigadeTypeEnum.专职消防队.getKey());
                        fireCarResourceDto.setName(brigade.getName());
                        fireCarResourceDto.getChildren().addAll(fireBrigadeResourceDtoList);
                        fireCarResourceDto.setOutCount((int) outCarCount);
                        fireCarResourceDto.setOnDutyCount((int) onDutyCarCount);
                        fireBrigadeResourceList.add(fireCarResourceDto);
                    }
                });
            }
        }

        // 3.消防队伍-监控大队
        List<FireBrigadeResourceDto> monitorFireBrigadeList = fireTeamService.listMonitorFireBrigade(FireBrigadeTypeEnum.监控大队.getCode());
       // List<FireBrigadeResourceDto> monitorFireBrigadeList = fireTeamService.listMonitorFireBrigade();
        /*bug 2403 队伍未显示图片 2021-09-23 陈召开始 */
//        for (FireBrigadeResourceDto fireBrigadeResourceDto : monitorFireBrigadeList) {
//            if (fireBrigadeResourceDto.getPic() != null) {
//                String[] split = fireBrigadeResourceDto.getPic().split(",");
//                if (split.length > 1) {
//                    fireBrigadeResourceDto.setImage(Arrays.asList(split));
//                } else {
//                    List<String> objects = new ArrayList<>();
//                    objects.add(fireBrigadeResourceDto.getPic());
//                    fireBrigadeResourceDto.setImage(objects);
//                }
//            }
//        }
        /*bug 2403 队伍未显示图片 2021-09-23 陈召结束 */
        FireBrigadeResourceDto monitorResourceDto = new FireBrigadeResourceDto();
        monitorResourceDto.setId("0");
        monitorResourceDto.setName(FireBrigadeTypeEnum.监控大队.getName());
        monitorResourceDto.setType(FireBrigadeTypeEnum.监控大队.getKey());
        monitorResourceDto.setChildren(monitorFireBrigadeList);

        if (!CollectionUtils.isEmpty(monitorFireBrigadeList)) {
            fireBrigadeResourceList.add(monitorResourceDto);
        }




        return fireBrigadeResourceList;
    }


    private List<PowerTransferCompanyResources> DtoEntityBatchConvert(List<PowerTransferCompanyResourcesDto> powerTransferCompanyResourcesDtoList, Long powerTransferCompanySequenceNbr) {
        ArrayList<PowerTransferCompanyResources> powerTransferCompanyResourcesList = new ArrayList<>();
        PowerTransferCompanyResources powerTransferCompanyResources;
        for (PowerTransferCompanyResourcesDto powerTransferCompanyResourcesDto : powerTransferCompanyResourcesDtoList) {
            powerTransferCompanyResources = new PowerTransferCompanyResources();
            BeanUtils.copyProperties(powerTransferCompanyResourcesDto, powerTransferCompanyResources);
            powerTransferCompanyResources.setPowerTransferCompanyId(powerTransferCompanySequenceNbr);
            //资源状态
            powerTransferCompanyResources.setStatus(FireCarStatusEnum.执行中.getCode());
            //资源状态
            powerTransferCompanyResources.setCarStatus(FireCarStatusEnum.出动.getCode());
            powerTransferCompanyResourcesList.add(powerTransferCompanyResources);
        }
        return powerTransferCompanyResourcesList;
    }

    private void initDefinitions(Map<String, String> definitions,
                                 AlertCalled alertCalled, PowerTransferDto powerTransferDto) {
        List<AlertFormValue> alertFormValue = alertFormValueService.list(new QueryWrapper<AlertFormValue>().eq(
                "alert_called_id", alertCalled.getSequenceNbr()));
        definitions.put("rescueGrid", alertCalled.getRescueGrid());
        definitions.put("alertType", alertCalled.getAlertType());
        definitions.put("address", alertCalled.getAddress());
        definitions.put("trappedNum", alertCalled.getTrappedNum().toString());
        definitions.put("casualtiesNum", alertCalled.getCasualtiesNum().toString());
        definitions.put("companyName", powerTransferDto.getCompanyName());

        for (AlertFormValue formValue : alertFormValue) {
            definitions.put(formValue.getFieldCode(), formValue.getFieldValue());
        }
    }

    private String getTaskInformation(String content, Map<String, String> definitions) {
        int size = definitions.size();
        String[] keys = definitions.keySet().toArray(new String[size]);
        String[] values = definitions.values().toArray(new String[size]);
        return StringUtils.replaceEach(content, keys, values);
    }

    private void createPowerTransferCompany(PowerTransferDto powerTransferDto, Long powerTransferSequenceNbr,
                                            Map<String, String> definitions, String content) {
        List<PowerTransferCompanyDto> powerTransferCompanyDotList = powerTransferDto.getPowerTransferCompanyDotList();
        PowerTransferCompany powerTransferCompany;

        List<Object> carStatusInfoDtoList = Lists.newArrayList();

        for (PowerTransferCompanyDto powerTransferCompanyDto : powerTransferCompanyDotList) {
            powerTransferCompany = new PowerTransferCompany();
            BeanUtils.copyProperties(powerTransferCompanyDto, powerTransferCompany);
            powerTransferCompany.setPowerTransferId(powerTransferSequenceNbr);
            List<PowerTransferCompanyResourcesDto> powerTransferCompanyResourcesDtoList =
                    powerTransferCompanyDto.getPowerTransferCompanyResourcesDtoList();
            if (powerTransferCompanyResourcesDtoList.size() == 0) {
                powerTransferCompany.setIsDistributionAgencies(true);
                definitions.put("type", "");
                definitions.put("resourcesNum", "");
                powerTransferCompany.setTaskInformation(getTaskInformation(content, definitions));
                powerTransferCompanyService.save(powerTransferCompany);
            } else {
                powerTransferCompany.setIsDistributionAgencies(false);
                StringBuilder taskInformation = new StringBuilder();
                for (PowerTransferCompanyResourcesDto powerTransferCompanyResourcesDto :
                        powerTransferCompanyResourcesDtoList) {
                    definitions.put("type", powerTransferCompanyResourcesDto.getType());
                    definitions.put("resourcesNum", powerTransferCompanyResourcesDto.getResourcesNum());
                    String information = getTaskInformation(content, definitions);
                    taskInformation.append(information).append(";");

                    CarStatusInfoDto carStatusInfoDto = new CarStatusInfoDto();
                    carStatusInfoDto.setSequenceNbr(powerTransferCompanyResourcesDto.getResourcesId());
                    carStatusInfoDto.setStatus(FireCarStatusEnum.出动.getCode());
                    carStatusInfoDtoList.add(carStatusInfoDto);
                }
                powerTransferCompany.setTaskInformation(taskInformation.toString());
                powerTransferCompanyService.save(powerTransferCompany);
                Long powerTransferCompanySequenceNbr = powerTransferCompany.getSequenceNbr();
                List<PowerTransferCompanyResources> powerTransferCompanyResourcesList =
                        DtoEntityBatchConvert(powerTransferCompanyResourcesDtoList, powerTransferCompanySequenceNbr);
                powerTransferCompanyResourcesService.saveBatch(powerTransferCompanyResourcesList);

                // 更新车辆状态
                equipFeignService.updateCarStatus(carStatusInfoDtoList);
            }
        }
    }

    @Override
    public List<PowerTransferCompanyDto> getLastPowerTransferCompany(Long alertCalledId) {
        return this.baseMapper.getLastPowerTransferCompany(alertCalledId);
    }

    public List<String> queryTransferCarIdsByAlertCalledId(Long alertCalledId) {
        return this.baseMapper.queryTransferCarIdsByAlertCalledId(alertCalledId);
    }

    public Map<String, Object> getPowerTransferList(String beginDate, String endDate) {
        // 获取力量调派信息
        List<PowerTransferDto> powerTransferInfo = this.baseMapper.getPowerTransferInfo(beginDate, endDate);
        List<PowerTransferCompanyDto> powerTransferCompanyInfo =
                this.baseMapper.getPowerTransferCompanyInfo(beginDate, endDate);
        List<PowerTransferCompanyResourcesDto> powerTransferCompanyResourcesInfo =
                this.baseMapper.getPowerTransferCompanyResourcesInfo(beginDate, endDate);
        Map<String, Object> transferInfo = this.baseMapper.getPowerTransferInfoCount(beginDate, endDate);

        // 获取力量出动模板
        Template template = templateService.getOne(new QueryWrapper<Template>().eq("type_code",
                DutyInfoEnum.力量出动.getKey()).eq("format", false));
        String templateContent = template.getContent();
        List<String> transferContent = new ArrayList<>();
        powerTransferInfo.forEach(pt -> {
            StringBuilder transferDetail = new StringBuilder();
            Long powerTransferId = pt.getSequenceNbr();
            String rescueGrid = pt.getRescueGrid();
            powerTransferCompanyInfo.forEach(ptc -> {
                if (powerTransferId.equals(ptc.getPowerTransferId())) {
                    transferDetail.append(ptc.getCompanyName());
                    if (!ptc.getIsDistributionAgencies()) {
                        Long powerTransferCompanyId = ptc.getSequenceNbr();
                        transferDetail.append("车辆车牌号");
                        powerTransferCompanyResourcesInfo.forEach(ptcr -> {
                            if (powerTransferCompanyId.equals(ptcr.getPowerTransferCompanyId())) {
                                transferDetail.append(ptcr.getResourcesNum()).append("、");
                            }
                        });
                        transferDetail.deleteCharAt(transferDetail.length() - 1);
                    }
                    transferDetail.append("；");
                }
            });
            transferDetail.deleteCharAt(transferDetail.length() - 1);
            String transferDetails = templateContent.replace("departmentName-type-resourcesNum",
                    transferDetail.toString()).replace("rescueGrid", rescueGrid == null ? "" : rescueGrid).replace(
                    "taskStatus", "");

            transferContent.add(transferDetails);
        });
        transferInfo.put("transferContent", transferContent);

        return transferInfo;
    }

    @Override
    public List<PowerCompanyCountDto> getPowerCompanyCountDtocount(Long id) {
        List<PowerCompanyCountDto> list = powerTransferMapper.getPowerCompanyCountDtocount(id);
        if (list != null && list.size() > 0) {
            list.stream().forEach(powerCompanyCountDto -> {
                List<PowerCarCountDto> li = powerTransferMapper.getPowerCarCountDtocount(id, powerCompanyCountDto.getCompanyId());
                powerCompanyCountDto.setPowerCarCountDto(li);
            });
        }
        return list;
    }

    @Override
    public IPage<PowerTransferResourceDto> getPowerTransferPageByParam(Long alertCalledId, String type, Page<PowerTransferResourceDto> page) {
        if (ValidationUtil.isEmpty(alertCalledId)) {
            throw new BaseException("警情id为空", "", "警情id为空");
        }
        IPage<PowerTransferResourceDto> resultPage = null;
        switch (type) {
            case "team":
                resultPage = getPowerTransferTeamResource(page, alertCalledId);
                break;
            case "car":
                resultPage = getPowerTransferCarResource(page, alertCalledId);
                break;
            case "person":
                // TODO 暂时没有调度人员
                resultPage = new Page<>();
                break;
            default:
                break;
        }
        return resultPage;
    }

    @Override
    public List<ResourceStatisticsDto> getPowerTransferStatistics(Long alertCalledId, String type) {
        List<ResourceStatisticsDto> result;
        result = powerTransferMapper.getPowerTransferTeamResourceCount(alertCalledId, type);
        if (ValidationUtil.isEmpty(result)) {
            ResourceStatisticsDto team = new ResourceStatisticsDto("team", 0, 0, 0);
            ResourceStatisticsDto car = new ResourceStatisticsDto("car", 0, 0, 0);
            ResourceStatisticsDto person = new ResourceStatisticsDto("person", 0, 0, 0);
            result.add(team);
            result.add(car);
            result.add(person);
        }
        return result;
    }

    public IPage<PowerTransferResourceDto> getPowerTransferTeamResource(Page<PowerTransferResourceDto> page,
                                                                        Long alertCalledId) {
        return powerTransferMapper.getPowerTransferTeamResource(page, alertCalledId);
    }

    private IPage<PowerTransferResourceDto> getPowerTransferCarResource(Page<PowerTransferResourceDto> page,
                                                                        Long alertCalledId) {
        Map<String, List<Map<String, Object>>> carInfoMap = getCarListMap();

        IPage<PowerTransferResourceDto> carResourcePage = powerTransferMapper.getPowerTransferCarResource(page, alertCalledId);
        Map<String, List<Map<String, Object>>> finalCarInfoMap = carInfoMap;
        carResourcePage.getRecords().forEach(car -> {
            String seq = car.getSequenceNbr().toString();
            car.setName((String) finalCarInfoMap.get(seq).get(0).get("name"));
            String carStateCode = (String) finalCarInfoMap.get(seq).get(0).get("carState");
            car.setCarState(!ValidationUtil.isEmpty(FireCarStatusEnum.getEnum(carStateCode)) ?
                    FireCarStatusEnum.getEnum(carStateCode).getName() : "");
            List<String> images = (List<String>) finalCarInfoMap.get(seq).get(0).get("image");
            car.setImg(!ValidationUtil.isEmpty(images) ? images.get(0) : "");
        });
        return carResourcePage;
    }

    private Map<String, List<Map<String, Object>>> getCarListMap() {
        ResponseModel<Object> result = equipFeignClient.getFireCarListAll();
        Map<String, List<Map<String, Object>>> carInfoMap = Maps.newConcurrentMap();
        if (!ValidationUtil.isEmpty(result)) {
            List<Map<String, Object>> fireCarListMapList = (List<Map<String, Object>>) result.getResult();
            if (!ValidationUtil.isEmpty(fireCarListMapList)) {
                carInfoMap =
                        fireCarListMapList.stream().collect(Collectors.groupingBy(car -> car.get("id").toString()));
            }
        }
        return carInfoMap;
    }

    private List<Map<String, Object>> getCarList() {
        ResponseModel<Object> result = equipFeignClient.getFireCarListAll();
        List<Map<String, Object>> fireCarListMapList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(result)) {
            fireCarListMapList = (List<Map<String, Object>>) result.getResult();
        }
        return fireCarListMapList;
    }

    @Override
    public JSONObject getPowerTransferCarResourceStatistics(Long alertCalledId) {
        // 所有车辆
        List<Map<String, Object>> carList = getCarList();

        IPage<PowerTransferResourceDto> carResourcePage =
                powerTransferMapper.getPowerTransferCarResource(new Page<>(1L, Long.MAX_VALUE),
                        alertCalledId);
        // 调派的车辆id列表
        List<Long> carIdList = Lists.transform(carResourcePage.getRecords(), PowerTransferResourceDto::getSequenceNbr);
        // 调派的车辆信息列表
        List<Map<String, Object>> totalCarList =
                carList.stream().filter(c -> carIdList.contains(Long.valueOf((String) c.get("id")))).collect(Collectors.toList());
        // TODO 车辆枚举后期修改为已到达状态车辆
        List<Map<String, Object>> arrivedCarList =
                carList.stream().filter(c -> carIdList.contains(Long.valueOf((String) c.get("id"))) && FireCarStatusEnum.出动.getCode().equals(c.get(
                        "carState"))).collect(Collectors.toList());
        // 调派-已到达车辆id列表
        List<Long> arrivedCarIdList = Lists.newArrayList();
        arrivedCarList.forEach(c -> {
            if (FireCarStatusEnum.出动.getCode().equals(c.get("carState"))) {
                arrivedCarIdList.add(Long.valueOf((String) c.get("id")));
            }
        });

        JSONObject resourceStatistics = new JSONObject();
        Long carTotal = carResourcePage.getTotal();

        // 车辆统计
        carCount(arrivedCarList, resourceStatistics, carTotal, "car");

        // 车辆人员统计
        dutyPersonCount(carIdList, arrivedCarIdList, resourceStatistics);

        // 车载器材统计
        fireAgentOnCarCount(totalCarList, arrivedCarList, resourceStatistics, "equipment", "equip");

        // TODO 车载水量统计
        carCount(arrivedCarList, resourceStatistics, carTotal, "water");

        // 车载药剂统计
        fireAgentOnCarCount(totalCarList, arrivedCarList, resourceStatistics, "fireAgent", "medicament");
        return resourceStatistics;
    }

    public void carCount(List<Map<String, Object>> arrivedCarList, JSONObject resourceStatistics, Long carTotal, String jsoKey) {
        JSONObject car = new JSONObject();
        car.put("total", carTotal);
        car.put("count", arrivedCarList.size());
        resourceStatistics.put(jsoKey, car);
    }

    public void dutyPersonCount(List<Long> carIdList, List<Long> arrivedCarIdList, JSONObject resourceStatistics) {
        // 当前时间所在班次
        List<Long> shiftIdList = dutyCarService.getDutyShiftIdList();
        List<Map<String, Object>> allDutyPersonList = Lists.newArrayList();
        if (!ValidationUtil.isEmpty(shiftIdList)) {
            // 当前值班车辆-人
            allDutyPersonList = dutyCarService.dayDutyPersonList(DateUtils.getDateNowShortStr(),
                    shiftIdList.get(0), null);
        }
        // 当前车辆执勤人员
        List<Map<String, Object>> allTransferDutyPerson =
                allDutyPersonList.stream().filter(c -> carIdList.contains(Long.valueOf((String) c.get("carId")))).collect(Collectors.toList());
        // 当前已到达车辆执勤人员
        List<Map<String, Object>> allArrivedTransferDutyPerson =
                allDutyPersonList.stream().filter(c -> arrivedCarIdList.contains(Long.valueOf((String) c.get("carId")))).collect(Collectors.toList());
        JSONObject person = new JSONObject();
        person.put("total", allTransferDutyPerson.size());
        person.put("count", allArrivedTransferDutyPerson.size());
        resourceStatistics.put("person", person);
    }

    public void fireAgentOnCarCount(List<Map<String, Object>> totalCarList, List<Map<String, Object>> arrivedCarList,
                                    JSONObject resourceStatistics, String equipType, String jsonKey) {
        double agentCountAll = totalCarList.stream().mapToDouble(car -> ((List<Map<String, Object>>) car.get(
                "resourceList")).stream().filter(res -> equipType.equals(res.get(
                "equipType"))).mapToDouble(c -> (double) c.get("equipCount")).sum()).sum();
        double agentCountArrived = arrivedCarList.stream().mapToDouble(car -> ((List<Map<String, Object>>) car.get(
                "resourceList")).stream().filter(res -> equipType.equals(res.get(
                "equipType"))).mapToDouble(c -> (double) c.get("equipCount")).sum()).sum();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", agentCountAll);
        jsonObject.put("count", agentCountArrived);
        resourceStatistics.put(jsonKey, jsonObject);
    }

    @Override
    public List<Map<String, String>> getFireCarStatusList() {
        return FireCarStatusEnum.toList();
    }

    @Override
    public List<Map<String, String>> getDispatchTaskStatusList() {
        return AlertFeedbackStatusEnum.toList();
    }
}
