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

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

import com.yeejoin.amos.boot.biz.common.dto.BaseDto;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.common.api.dto.DutyPersonShiftDto;
import com.yeejoin.amos.boot.module.common.api.dto.DutyShiftDto;
import com.yeejoin.amos.boot.module.common.api.entity.DutyShift;
import com.yeejoin.amos.boot.module.common.api.mapper.DutyPersonShiftMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.DutyShiftMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.runtime.directive.Break;
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.springframework.validation.ValidationUtils;
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 com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.api.mapper.DynamicFormInstanceMapper;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DutyCarServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireTeamServiceImpl;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledRo;
import com.yeejoin.amos.boot.module.jcs.api.dto.CarStatusInfoDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.ControllerDto;
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.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.jcs.api.entity.Controller;
import com.yeejoin.amos.boot.module.jcs.api.entity.PowerTransfer;
import com.yeejoin.amos.boot.module.jcs.api.entity.PowerTransferCompany;
import com.yeejoin.amos.boot.module.jcs.api.entity.PowerTransferCompanyResources;
import com.yeejoin.amos.boot.module.jcs.api.entity.Template;
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;

/**
 * 力量调派 服务实现类
 *
 * @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
    DutyCarServiceImpl iDutyCarService;


    @Autowired
    AlertFormValueServiceImpl alertFormValueService;

    @Autowired
    EquipFeignClient equipFeignService;

    @Autowired
    FireTeamServiceImpl fireTeamService;

    @Autowired
    PowerTransferMapper powerTransferMapper;

    @Autowired
    EquipFeignClient equipFeignClient;

    @Autowired
    private EmqKeeper emqKeeper;

    @Autowired
    DutyPersonShiftMapper dutyPersonShiftMapper;

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

    @Autowired
    private DutyCarServiceImpl dutyCarService;

    @Autowired
    FireTeamServiceImpl iFireTeamService;

    @Autowired
    DynamicFormInstanceMapper dynamicFormInstanceMapper;

    @Autowired
    RuleAlertCalledService ruleAlertCalledService;

    @Autowired
    ControllerServiceImpl controllerServiceImpl;

    @Autowired
    private AircraftServiceImpl aircraftServiceImpl;
    @Autowired
    private DutyShiftMapper dutyShiftMapper;

    @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);

            // 获取警情详情
            AlertCalledObjsDto alertCalled = (AlertCalledObjsDto) alertCalledService
                    .selectAlertCalledByIdNoRedisNew(alertCalledId);

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

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

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

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

            // 封装调派任务的集合，以便于实现任务规则校验
            try {
                packagePowerTransferDetail(powerTransferDto);
            } catch (Exception e) {
                log.error("调用规则失败：PowerTransferServiceImpl。createPowerTransfer（）");
            }

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

        return true;
    }

    private void packagePowerTransferDetail(PowerTransferDto powerTransferDto) throws Exception {
        List<PowerTransferCompanyDto> powerTransferCompanyDtoList = powerTransferDto.getPowerTransferCompanyDotList();
        Set<PowerTransferCompanyDto> fullTimeList = new HashSet<PowerTransferCompanyDto>();
        Set<PowerTransferCompanyDto> medicalTeamList = new HashSet<PowerTransferCompanyDto>();
        Set<PowerTransferCompanyDto> monitorTeamList = new HashSet<PowerTransferCompanyDto>();

        for (PowerTransferCompanyDto powerTransferCompanyDto : powerTransferCompanyDtoList) {
            if (FireBrigadeTypeEnum.专职消防队.getKey().equals(powerTransferCompanyDto.getPowerTransType())) {
                fullTimeList.add(powerTransferCompanyDto);
            } else if (FireBrigadeTypeEnum.医疗救援队.getKey().equals(powerTransferCompanyDto.getPowerTransType())) {
                medicalTeamList.add(powerTransferCompanyDto);
            } else if (FireBrigadeTypeEnum.监控大队.getKey().equals(powerTransferCompanyDto.getPowerTransType())) {
                monitorTeamList.add(powerTransferCompanyDto);
            }
        }
        if (fullTimeList.size() > 0) {
            ruleAlertCalledService.powerTransferCalledRule(fullTimeList, powerTransferDto.getAlertCalledId(),
                    FireBrigadeTypeEnum.专职消防队.getKey(), powerTransferDto.getCompanyName());
        }
        if (medicalTeamList.size() > 0) {
            ruleAlertCalledService.powerTransferCalledRule(medicalTeamList, powerTransferDto.getAlertCalledId(),
                    FireBrigadeTypeEnum.医疗救援队.getKey(), powerTransferDto.getCompanyName());

        }
        if (monitorTeamList.size() > 0) {
            ruleAlertCalledService.powerTransferCalledRule(monitorTeamList, powerTransferDto.getAlertCalledId(),
                    FireBrigadeTypeEnum.监控大队.getKey(), powerTransferDto.getCompanyName());

        }
    }

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

        if (type != null && !"".equals(type) && "1214".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);
                        }
                    }

                    if (fireCarDto.getId() != null) {
                        List<Map<String,String>> resultList = new ArrayList<>();

                        String dutyDay = DateUtils.getDateNowShortStr();
                        Map<String, Object> instanceMap = dutyPersonShiftMapper.getInstanceIdForSpecifyDateAndEquipment(dutyDay,
                                "dutyCar", fireCarDto.getId());

                   if (instanceMap != null){
                       String instanceId = instanceMap.get("instanceIds").toString();
                       if (StringUtils.isNotBlank(instanceId)) {
                           String[] instanceIds = instanceId.split(",");
                           List<Map<String, Object>>  dutyList = dutyPersonShiftMapper.getDutyForSpecifyDate(dutyDay);
                           if(dutyList!=null && dutyList.size()>0) {
                               for (Map<String, Object> dutyDetail : dutyList) {
                                   if(!dutyDetail.containsKey("name")) {
                                       continue;
                                   }
                                   // 获取当前装备ID下的排版数据
                                   List<Map<String, Object>> specifyDateList = dutyPersonShiftMapper.getPositionStaffDutyForSpecifyDate(dutyDay,
                                           "dutyCar", instanceIds,dutyDetail.get("name").toString());
                                   if(specifyDateList==null || specifyDateList.size() < 1 || specifyDateList.get(0)==null) {
                                       continue;
                                   }
                                   LinkedHashMap<String, String> infoMap_1 =new LinkedHashMap<String, String>();
                                   for (Map<String, Object> specify : specifyDateList) {
//
                                       if(specify.containsKey("userName")&& specify.get("userName")!=null ) {

                                           if (specify.get("userName").toString().contains(",")){
                                               String[] userNames = specify.get("userName").toString().split(",");
                                               infoMap_1.put(dutyDetail.get("name").toString(),userNames.length+"");
                                           }else {
                                               infoMap_1.put(dutyDetail.get("name").toString(),"1");
                                           }
                                           resultList.add(infoMap_1);
                                       }
                                   }
                               }
                           }
                       }
                   }



                        int num = 0;
                        String todayTime = DateUtils.getDateNowShortStr();
                        String beginDate = todayTime;
                        beginDate = beginDate + " 00:00:00";
                        String endDate = todayTime;
                        endDate = endDate + " 23:59:59";
                        LambdaQueryWrapper<DutyShift> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(BaseEntity::getIsDelete,false);
                        List<DutyShift> dutyShifts = dutyShiftMapper.selectList(wrapper);

                        String[] dutyShiftName = {" "};

                        dutyShifts.forEach(e->{
                            String startTime = e.getStartTime();
                            Date startDate = null;
                            Date dateEnd = null;
                            if (startTime.startsWith("当日:")){
                                String resultTime = startTime.replace("当日:", todayTime)+":00";
                                startDate = DateUtils.longStr2Date(resultTime);
                            }else if (startTime.startsWith("次日:")){
                                Date dateNow = DateUtils.getDateNow();
                                Date date = DateUtils.dateAddDays(dateNow, 1);
                                String s = DateUtils.convertDateToString(date, DateUtils.DATE_PATTERN);
                                String resultTime = startTime.replace("次日:", s)+":00";
                                startDate = DateUtils.longStr2Date(resultTime);
                            }
                            String endTime = e.getEndTime();
                            if (endTime.startsWith("当日:")){
                                String resultTime = endTime.replace("当日:", todayTime)+":00";
                                dateEnd = DateUtils.longStr2Date(resultTime);
                            }else if (endTime.startsWith("次日:")){
                                Date dateNow = DateUtils.getDateNow();
                                Date date = DateUtils.dateAddDays(dateNow, 1);
                                String s = DateUtils.convertDateToString(date, DateUtils.DATE_PATTERN);
                                String resultTime =endTime.replace("次日:",s)+":00";
                                dateEnd = DateUtils.longStr2Date(resultTime);
                            }

                            if (DateUtils.belongCalendar(DateUtils.getDateNow(),startDate,dateEnd)) {
                              dutyShiftName[0] = dutyShiftName[0].replace(" ", e.getName());
                            }
                        });

                        if (resultList != null  ){
                            resultList.forEach(e->{
                                if (e.containsKey( dutyShiftName[0])) {
                                    String personNum = e.get(dutyShiftName[0]);
                                    fireCarDto.setPersonCount(Integer.valueOf(personNum));
                                }
                            });
                        }else {
                            fireCarDto.setPersonCount(num);
                        }

                    }
                    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;
        List idList = powerTransferCompanyResourcesDtoList.stream()
                .map(PowerTransferCompanyResourcesDto::getResourcesId).collect(Collectors.toList());
        QueryWrapper<PowerTransferCompanyResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", FireCarStatusEnum.执行中.getCode());
        queryWrapper.in("resources_id", idList);
        List<PowerTransferCompanyResources> alertFormValue = powerTransferCompanyResourcesService.list(queryWrapper);
        if (alertFormValue != null && alertFormValue.size() > 0) {
            throw new RuntimeException("已选车辆有已调派车辆！");
        } else {
            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, AlertCalledObjsDto alertCalledObjsDto) {
        List<PowerTransferCompanyDto> powerTransferCompanyDotList = powerTransferDto.getPowerTransferCompanyDotList();
        PowerTransferCompany powerTransferCompany;
        List<Object> carStatusInfoDtoList = Lists.newArrayList();
        AlertCalled alertCalled = alertCalledObjsDto.getAlertCalled();
        // 初始化警情 信息
        /**
         * 构建警情报送规则对象
         */
        AlertCalledRo alertCalledRo = new AlertCalledRo();
        String replaceContent = "";
        if (null != alertCalled) {
            replaceContent = RuleAlertCalledService.init(alertCalledRo, alertCalledObjsDto);
        }
        List<AlertFormValue> alertFormValue = alertCalledObjsDto.getAlertFormValue();

        String responseLevel = "";
        List<AlertFormValue> list1 = alertFormValue.stream().filter(formValue -> formValue.getFieldCode().equals("responseLevel")).collect(Collectors.toList());
        ;
        if (list1.size() > 0) {
            responseLevel = list1.get(0).getFieldValue();
        }

        definitions.put("rescueGrid", ValidationUtil.isEmpty(alertCalled.getAddress() ) ? "" : alertCalled.getAddress());
        definitions.put("type", alertCalled.getAlertType());
        definitions.put("contactUser", ValidationUtil.isEmpty(alertCalled.getContactUser() ) ? "" : alertCalled.getContactUser());
        definitions.put("contactPhone", ValidationUtil.isEmpty(alertCalled.getContactPhone() ) ? "" : alertCalled.getContactPhone());
        definitions.put("replaceContent", replaceContent);
        definitions.put("responseLevel", responseLevel);
        definitions.put("callTime",
                DateUtils.convertDateToString(alertCalled.getCallTime(), DateUtils.DATE_TIME_PATTERN));
        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("departmentName", powerTransferCompanyDto.getCompanyName());

                definitions.put("content", "");
                powerTransferCompany.setTaskInformation(getTaskInformation(content, definitions));
                powerTransferCompanyService.save(powerTransferCompany);
                powerTransferCompanyDto.setSequenceNbr(powerTransferCompany.getSequenceNbr());
            } else {
                powerTransferCompany.setIsDistributionAgencies(false);
                StringBuilder taskInformation = new StringBuilder();
                for (PowerTransferCompanyResourcesDto powerTransferCompanyResourcesDto : powerTransferCompanyResourcesDtoList) {
//					definitions.put("type", powerTransferCompanyResourcesDto.getType());
//					definitions.put("resourcesNum", powerTransferCompanyResourcesDto.getResourcesNum());
                    String information = powerTransferCompanyResourcesDto.getType().concat("车牌号")
                            .concat(powerTransferCompanyResourcesDto.getResourcesNum());
                    taskInformation.append(information).append("丶");
                    CarStatusInfoDto carStatusInfoDto = new CarStatusInfoDto();
                    carStatusInfoDto.setSequenceNbr(powerTransferCompanyResourcesDto.getResourcesId());
                    carStatusInfoDto.setStatus(FireCarStatusEnum.出动.getCode());
                    carStatusInfoDtoList.add(carStatusInfoDto);
                }
                definitions.put("departmentName", powerTransferCompanyDto.getCompanyName());
                definitions.put("content", taskInformation.toString());
                powerTransferCompany.setTaskInformation(getTaskInformation(content, definitions));
                powerTransferCompanyService.save(powerTransferCompany);
                powerTransferCompanyDto.setSequenceNbr(powerTransferCompany.getSequenceNbr());
                Long powerTransferCompanySequenceNbr = powerTransferCompany.getSequenceNbr();
                List<PowerTransferCompanyResources> powerTransferCompanyResourcesList = DtoEntityBatchConvert(
                        powerTransferCompanyResourcesDtoList, powerTransferCompanySequenceNbr);
                powerTransferCompanyResourcesService.saveBatch(powerTransferCompanyResourcesList);
                List<PowerTransferCompanyResourcesDto> resourcesDtoList = new ArrayList<>();
                powerTransferCompanyResourcesList.stream().forEach(e -> {
                    PowerTransferCompanyResourcesDto dto = new PowerTransferCompanyResourcesDto();
                    Bean.toPo(e, dto);
                    resourcesDtoList.add(dto);
                });
                powerTransferCompanyDto.setPowerTransferCompanyResourcesDtoList(resourcesDtoList);
                // 更新车辆状态
                equipFeignService.updateCarStatus(carStatusInfoDtoList);
                // 警情力量调派时，点击【任务派发】后，如果被调派的 力量包含消防车，那么该消防车所在的 大队的警铃、广播自动 启动，消防车所在的车库门自动开启
                try {
                    List<Controller> controllers = controllerServiceImpl.list(new LambdaQueryWrapper<Controller>().eq(Controller::getFireTeamSeq, powerTransferCompanyDto.getCompanyId()));
                    if (controllers.size() > 0) {
                        ControllerDto[] controllerDtos = new ControllerDto[controllers.size()];
                        for (int i = 0; i < controllers.size(); i++) {
                            ControllerDto controllerDto = new ControllerDto();
                            BeanUtils.copyProperties(controllers.get(i), controllerDto);
                            controllerDtos[i] = controllerDto;
                        }
                        controllerServiceImpl.changeControllerState(controllerDtos);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                    log.error("车库门、警铃、广播的 联动 功能出现异常");
                }
            }
        }
    }

    @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.append(ptcr.getStatus()).append("、");
                            }
                        });
                        transferDetail.deleteCharAt(transferDetail.length() - 1);
                    }
                    transferDetail.append("；");
                }
            });
            transferDetail.deleteCharAt(transferDetail.length() - 1);
            if (transferDetail.toString().contains("、")) {
                String transfer = null;
                String taskStatus = null;
                String[] split = transferDetail.toString().split("、");
                if (split.length > 1) {
                    transfer = split[0];
                    taskStatus = split[1];
                }
                String transferDetails = templateContent.replace("departmentName-type-resourcesNum", transfer)
                        .replace("rescueGrid", rescueGrid == null ? "" : rescueGrid).replace("taskStatus",
                                taskStatus != null ? FireCarStatusEnum.getEnum(taskStatus).getName() : null);
                transferContent.add(transferDetails);
            } else {
                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();
        double 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, double 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 -> car.get("resourceList") != null ? ((List<Map<String, Object>>) car.get("resourceList")).stream()
                        .filter(res -> equipType.equals(res.get("equipType")))
                        .mapToDouble(c -> Double.parseDouble(ValidationUtil.isEmpty(c.get("equipCount") ) ? "0" : c.get("equipCount").toString())).sum() : 0)
                .sum();

        double agentCountArrived = arrivedCarList.stream().mapToDouble(
                car -> car.get("resourceList") != null ? ((List<Map<String, Object>>) car.get("resourceList")).stream()
                        .filter(res -> equipType.equals(res.get("equipType")))
                        .mapToDouble(c -> Double.parseDouble(ValidationUtil.isEmpty(c.get("equipCount") ) ? "0" : c.get("equipCount").toString())).sum() : 0)
                .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();
    }

}
