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


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

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
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 com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferCompanyResourcesMapper;
import lombok.extern.slf4j.Slf4j;
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.springframework.web.client.HttpClientErrorException;
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.exception.instance.BadRequest;
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.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.*;
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;


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


    @Autowired
    PowerTransferCompanyResourcesMapper powerTransferCompanyResourcesMapper;
    @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 DutyShiftMapper dutyShiftMapper;

    private static final  String PERSON="person";

    private static final  String USERNAME="userName";
    private static final  String COUNT= "count";
    private static final  String TOTAL= "total";


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

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

            // 封装调派任务的集合，以便于实现任务规则校验

            packagePowerTransferDetail(powerTransferDto);


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

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


        // 查询车辆当前任务状态
        QueryWrapper<PowerTransferCompanyResources> queryWrapper = new QueryWrapper<>();
        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) {
                            //bug: 6268
                            String state = appleMap.containsKey(car.get("id")) ? appleMap.get(car.get("id")) : FireCarStatusEnum.执勤.getCode();
                            fireCarDto.setCarState(state);
                            fireCarDto.setCarStateDesc(state != null ? FireCarStatusEnum.getEnum(state).getName() : null);
                        } else {
                            //bug: 6268
                            fireCarDto.setCarState(FireCarStatusEnum.执勤.getCode());
                            fireCarDto.setCarStateDesc(FireCarStatusEnum.执勤.getName());
                        }
                    }

                    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(), null);
                                        if (specifyDateList == null || specifyDateList.size() < 1 || specifyDateList.get(0) == null) {
                                            continue;
                                        }
                                       
                                        int num=0;
                                        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(",");
                                                    num = num+ userNames.length;
                                                    infoMap_1.put(dutyDetail.get("name").toString(), userNames.length + "");
                                                } else {
                                                  num = num +1 ;
                                                    infoMap_1.put(dutyDetail.get("name").toString(), "1");
                                                }
                                                resultList.add(infoMap_1);
                                            }
                                        }
                                        fireCarDto.setPersonCount(num);
                                    }
                                }
                            }
                        }


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

        /* 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<String> 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 BadRequest("已选车辆有已调派车辆！");
        } else {
            for (PowerTransferCompanyResourcesDto powerTransferCompanyResourcesDto : powerTransferCompanyResourcesDtoList) {

                powerTransferCompanyResources = new PowerTransferCompanyResources();
                BeanUtils.copyProperties(powerTransferCompanyResourcesDto, powerTransferCompanyResources);
                powerTransferCompanyResources.setPowerTransferCompanyId(powerTransferCompanySequenceNbr);
                // 资源状态
                powerTransferCompanyResources.setStatus(FireCarStatusEnum.执行中.getCode());
                // 资源状态
                powerTransferCompanyResources.setCarStatus(FireCarStatusEnum.出动.getCode());
                //车辆随车人员（车辆今日值班人数）
                List<Map<String, Object>> equipmentList = iDutyCarService.getDutyCaruser(Long.valueOf(powerTransferCompanyResources.getResourcesId()));

                if (!ValidationUtil.isEmpty(equipmentList)) {

                    powerTransferCompanyResources.setCarUser(equipmentList.size()+"");
                }else{
                    powerTransferCompanyResources.setCarUser("0");
                }

                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()));
        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) {
                    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()));

                    //bug 5863 打印日志 调派车辆后对应警铃未打开
                    log.info("消防车队伍ID：{}， 根据队伍ID查出来的jc_controller数据：{}，查出来的数据量size：{}", powerTransferCompanyDto.getCompanyId(), JSON.toJSONString(controllers), controllers.size());

                    if (controllers.size() > 0) {

                        log.info("开始执行车库、警铃、广播等联动代码");

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



        // 调派-已到达车辆id列表
        List<Long> arrivedCarIdList = Lists.newArrayList();

        List<PowerTransferResourceDto> tot=null;
        if(carResourcePage.getRecords()!=null&&carResourcePage.getRecords().size()>0){
            carResourcePage.getRecords().forEach(c -> {
                if (FireCarStatusEnum.到场.getCode().equals(c.getCarState())) {
                    arrivedCarIdList.add(c.getSequenceNbr());
                }
            });

        }

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

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

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

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

        //  车载药剂统计 车载水量统计

        waterCount(carIdList,resourceStatistics,carTotal,"water");

        return resourceStatistics;
    }

    public void carCount( List<Long> arrivedCarList, JSONObject resourceStatistics, double carTotal,
                         String jsoKey) {
        JSONObject car = new JSONObject();
        int total=0;
        if(carTotal>0){
            total=arrivedCarList.size();
        }
        car.put(TOTAL,total);
        car.put(COUNT, total);
        resourceStatistics.put(jsoKey, car);
    }

    //泡沫和水车载统计
    public void waterCount(  List<Long> carIds,JSONObject resourceStatistics, double carTotal,
                           String jsoKey) {
        JSONObject obj = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        if(carTotal>0){
            // 泡沫和水车载统计 获取调用车辆的车载资源
            ResponseModel<Map<String, Object>> carPropertyByCarIds = equipFeignService.getCarPropertyByCarIds(carIds);
            obj.put(TOTAL, carTotal);
            obj.put(COUNT, carPropertyByCarIds.getResult().get("waterNum")!=null?carPropertyByCarIds.getResult().get("waterNum"):0);


            jsonObject.put(TOTAL, carTotal);
            jsonObject.put(COUNT, carPropertyByCarIds.getResult().get("foamNum")!=null?carPropertyByCarIds.getResult().get("foamNum"):0);

        }else{
            obj.put(TOTAL, 0);
            obj.put(COUNT, 0);
            jsonObject.put(TOTAL, 0);
            jsonObject.put(COUNT,0);

        }
        resourceStatistics.put("medicament", jsonObject);
        resourceStatistics.put(jsoKey, obj);
    }

    public void dutyPersonCount(List<Long> carIdList, List<Long> arrivedCarIdList, JSONObject resourceStatistics) {
        JSONObject person = new JSONObject();
        if(arrivedCarIdList!=null&&arrivedCarIdList.size()>0){


            int num=0;
            for (Long aLong : arrivedCarIdList) {
                List<Map<String, Object>> equipmentList = iDutyCarService.getDutyCaruser(aLong);
                num=num+equipmentList.size();
            }


             person.put(TOTAL, num);
             person.put(COUNT, num);

         }else{
            person.put(TOTAL, 0);
            person.put(COUNT, 0);
         }

        resourceStatistics.put(PERSON, person);
    }

    public void fireAgentOnCarCount(List<Map<String, Object>> totalCarList,  List<Long> arrivedCarList,
                                    JSONObject resourceStatistics, String equipType, String jsonKey) {



        JSONObject jsonObject = new JSONObject();
        if(totalCarList!=null&&totalCarList.size()>0){
            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();


            jsonObject.put(TOTAL, agentCountAll);
            jsonObject.put(COUNT, agentCountAll);
        }else{
            jsonObject.put(TOTAL, 0);
            jsonObject.put(COUNT, 0);
        }

        resourceStatistics.put(jsonKey, jsonObject);
    }

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

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

}
