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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledQueryDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledRecordDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertHandlerDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertHandlerInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertPaperInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.DutySeatDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.FormValue;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatMyBusinessListDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatMyBussinessDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchPaper;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.tzs.api.entity.Elevator;
import com.yeejoin.amos.boot.module.tzs.api.entity.VoiceRecordFile;
import com.yeejoin.amos.boot.module.tzs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.tzs.api.enums.DispatchPaperEnums;
import com.yeejoin.amos.boot.module.tzs.api.enums.TzsCommonParam;
import com.yeejoin.amos.boot.module.tzs.api.mapper.AlertCalledMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IAlertCalledService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 警情接警填报记录服务实现类
 *
 * @author litw
 * @date 2021-08-03
 */
@Service
public class AlertCalledServiceImpl extends BaseService<AlertCalledDto,AlertCalled,AlertCalledMapper> implements IAlertCalledService {

    @Autowired
    RedisUtils redisUtils;

    @Value("${redis.cache.failure.time}")
    private long time;

    @Autowired
    private AlertFormValueServiceImpl iAlertFormValueService;

    @Autowired
    TemplateServiceImpl templateService;

    @Autowired
    private ESAlertCalledService eSAlertCalledService;

    @Autowired
    private ElevatorServiceImpl iElevatorService;

    @Autowired
    AlertCalledMapper alertCalledMapper;

    @Autowired
    RescueProcessServiceImpl rescueProcessServiceImpl;

    @Autowired
    RepairConsultServiceImpl repairConsultServiceImpl;

    @Autowired
    DispatchPaperServiceImpl dispatchPaperService;

    @Autowired
    DispatchTaskServiceImpl dispatchTaskService;

    @Autowired
    ISourceFileService ISourceFileService;

    @Autowired
    VoiceRecordFileServiceImpl voiceRecordFileServiceImpl;

    private final Logger logger = LogManager.getLogger(AlertCalledServiceImpl.class);


    @Override
    public Object selectAlertCalledById(Long id) {
        if(redisUtils.hasKey(RedisKey.TZS_ALERTCALLED_ID+id)){
            Object obj= redisUtils.get(RedisKey.TZS_ALERTCALLED_ID+id);
            return obj;
        }else{
            // 警情基本信息
            AlertCalled alertCalled = this.getById(id);
            LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AlertFormValue::getAlertCalledId, id);
            // 警情动态表单数据
            List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
            List<FormValue> formValue = new ArrayList<FormValue>();
            if(list!=null&&list.size()>0) {
                for (AlertFormValue alertFormValue : list) {
                    FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(), "text", alertFormValue.getFieldValue(),alertFormValue.getBlock());
                    formValue.add(value);
                }
            }
            AlertCalledDto alertCalledDto = BeanDtoVoUtils.convert(alertCalled,AlertCalledDto.class);
            LambdaQueryWrapper<Elevator> elevatorQueryWrapper = new LambdaQueryWrapper<>();
            elevatorQueryWrapper.eq(Elevator::getRescueCode, alertCalled.getDeviceId());
            elevatorQueryWrapper.eq(Elevator::getRegisterCode, alertCalled.getRegistrationCode());
            Elevator elevator =  iElevatorService.getOne(elevatorQueryWrapper);
            if(null !=  elevator) {
                alertCalledDto.setAddress(elevator.getAddress());
                alertCalledDto.setProvince(elevator.getProvince());
                alertCalledDto.setCity(elevator.getCity());
                alertCalledDto.setDistrict(elevator.getDistrict());
                alertCalledDto.setUseStatus(elevator.getUseStatus());
                alertCalledDto.setUseSiteCategory(elevator.getUseSiteCategory());
                alertCalledDto.setUseUnit(elevator.getUseUnit());
                alertCalledDto.setRegionCode(elevator.getRegionCode());
            }
            String voiceRecord = "";
            VoiceRecordFile temp = voiceRecordFileServiceImpl.getOne(new LambdaQueryWrapper<VoiceRecordFile>().eq(VoiceRecordFile::getAlertId,id).eq(VoiceRecordFile::getAlertStageCode,"860").orderByAsc(VoiceRecordFile::getRecDate));
            if(temp != null) {
                voiceRecord = temp.getFilePath();
            }
            AlertCalledFormDto alertCalledFormVo = new AlertCalledFormDto(alertCalledDto, formValue,voiceRecord);

            redisUtils.set(RedisKey.TZS_ALERTCALLED_ID+id, JSON.toJSON(alertCalledFormVo),time);
            return alertCalledFormVo;
        }
    }

    public void selectAlertCalledByIdNew(AlertPaperInfoDto alertCalled) {
        // 警情基本信息

        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertFormValue::getAlertCalledId, alertCalled.getAlertId());
        // 警情动态表单数据
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        if(list!=null&&list.size()>0) {
            for (AlertFormValue alertFormValue : list) {
                if(alertFormValue.getFieldCode().equals("trapped_num")) {
                    alertCalled.setTrappedNum(alertFormValue.getFieldValue());
                }
                if(alertFormValue.getFieldCode().equals("injured_num")) {
                    alertCalled.setInjuredNum(alertFormValue.getFieldValue());
                }
                if(alertFormValue.getFieldCode().equals("die_num")) {
                    alertCalled.setDieNum(alertFormValue.getFieldValue());
                }
            }
        }
    }

    @Override
    public AlertCalledFormDto selectAlertCalledByIdNoCache(Long id) {
        // 警情基本信息
        AlertCalled alertCalled = this.getById(id);
        LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertFormValue::getAlertCalledId, id);
        // 警情动态表单数据
        List<AlertFormValue> list = iAlertFormValueService.list(queryWrapper);
        List<FormValue> formValue = new ArrayList<FormValue>();
        if(list!=null&&list.size()>0) {
            for (AlertFormValue alertFormValue : list) {
                FormValue value = new FormValue(alertFormValue.getFieldCode(), alertFormValue.getFieldName(), "text", alertFormValue.getFieldValue(),alertFormValue.getBlock());
                formValue.add(value);
            }
        }
        AlertCalledDto alertCalledDto = BeanDtoVoUtils.convert(alertCalled,AlertCalledDto.class);
        LambdaQueryWrapper<Elevator> elevatorQueryWrapper = new LambdaQueryWrapper<>();
        elevatorQueryWrapper.eq(Elevator::getRescueCode, alertCalled.getDeviceId());
        elevatorQueryWrapper.eq(Elevator::getRegisterCode, alertCalled.getRegistrationCode());
        Elevator elevator =  iElevatorService.getOne(elevatorQueryWrapper);
        if(null !=  elevator) {
            alertCalledDto.setAddress(elevator.getAddress());
            alertCalledDto.setProvince(elevator.getProvince());
            alertCalledDto.setCity(elevator.getCity());
            alertCalledDto.setDistrict(elevator.getDistrict());
            alertCalledDto.setUseStatus(elevator.getUseStatus());
            alertCalledDto.setUseSiteCategory(elevator.getUseSiteCategory());
            alertCalledDto.setUseUnit(elevator.getUseUnit());
            alertCalledDto.setRegionCode(elevator.getRegionCode());
        }
        String voiceRecord = "";
        VoiceRecordFile temp = voiceRecordFileServiceImpl.getOne(new LambdaQueryWrapper<VoiceRecordFile>().eq(VoiceRecordFile::getAlertId,id).eq(VoiceRecordFile::getAlertStageCode,"860").orderByAsc(VoiceRecordFile::getRecDate));
        if(temp != null) {
            voiceRecord = temp.getFilePath();
        }
        AlertCalledFormDto alertCalledFormVo = new AlertCalledFormDto(alertCalledDto, formValue,voiceRecord);
        return alertCalledFormVo;
    }

    @Override
    public Page<AlertCalledQueryDto> queryAlertListByQueryDto(IPage<AlertCalledQueryDto> page,
                                                              String workOrderNumber,
                                                              String creator,
                                                              String emergency,
                                                              String emergencyTimeStart,
                                                              String emergencyTimeEnd,
                                                              String emergencyCall,
                                                              String deviceId,
                                                              String elevatorAddress,
                                                              String district,
                                                              String alertType,
                                                              String alertSource,
                                                              String alertStage,
                                                              String alertStatus,
                                                              String sortParam,
                                                              String sortRule
                                                              ) {
        Page<List<AlertCalledQueryDto>>list = alertCalledMapper.queryAlertListByQueryDto(page,
                workOrderNumber,creator,emergency,emergencyTimeStart,
                emergencyTimeEnd,emergencyCall,deviceId,elevatorAddress,district,alertType,
                alertSource,alertStage,alertStatus,sortParam,sortRule);
        Page<AlertCalledQueryDto> page1 = new Page<>();
        List<AlertCalledQueryDto> resultDtoList = JSONArray.parseArray(JSONArray.toJSONString(list.getRecords()),AlertCalledQueryDto.class);
        page1.setCurrent(page.getCurrent());
        page1.setSize(page.getSize());
        page1.setTotal(list.getTotal());
        page1.setRecords(resultDtoList);
        return page1;
    }

    @Override
    public Boolean updateAlertStage(AlertCalledDto alertCalledVo, DispatchPaperEnums stage) {
        LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AlertCalled::getSequenceNbr,alertCalledVo.getSequenceNbr());
        updateWrapper.set(AlertCalled::getAlertStageCode,stage.getId());
        alertCalledVo.setAlertStage(stage.getValue());
        alertCalledVo.setAlertStageCode(stage.getId());
        updateWrapper.set(AlertCalled::getAlertStage,stage.getValue());
        if(stage == DispatchPaperEnums.reportorBack || stage == DispatchPaperEnums.complainantBack) {
            updateWrapper.set(AlertCalled::getAlertStatus,true);
            alertCalledVo.setAlertStatus(true);
        } else if(stage == DispatchPaperEnums.repaired  && alertCalledVo.getAlarmTypeCode().equals(AlertStageEnums.KRJY.getId())) {
            updateWrapper.set(AlertCalled::getAlertStatus,true);
            alertCalledVo.setAlertStatus(true);
        }
        Boolean flag = this.update(updateWrapper);
        if(flag) { //更新redis 和 es 信息
            try {
                redisUtils.del(RedisKey.TZS_ALERTCALLED_ID+alertCalledVo.getSequenceNbr());
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("删除redis失败:" + e.getMessage());
            }
            try {
                eSAlertCalledService.updateEsAlertCalled(alertCalledVo);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("更新es失败:" + e.getMessage());
            }
        }
        return this.update(updateWrapper);
    }

    /**
     *  警情处置流程信息
     */
    @Override
    public AlertHandlerDto getHandlerInfo(String alertId) {
        AlertHandlerDto alertHandlerDto = new AlertHandlerDto();
        LinkedHashMap<String,Date> map = new LinkedHashMap<>();
        List<AlertHandlerInfoDto> list = new ArrayList<>();
        AlertHandlerInfoDto alertHandlerInfoDtoHead = new AlertHandlerInfoDto();
        alertHandlerInfoDtoHead.setAbProcess("处置流程");
        alertHandlerInfoDtoHead.setAcAnswerThePolice("接警");
        alertHandlerInfoDtoHead.setAcReport("上报");
        alertHandlerInfoDtoHead.setAdNotice("派遣/通知");
        alertHandlerInfoDtoHead.setAedArrive("到达");
        alertHandlerInfoDtoHead.setAfeComplete("完成");
        alertHandlerInfoDtoHead.setAgReturnVisit("回访");
        list.add(alertHandlerInfoDtoHead);

        AlertCalled called = this.getById(Long.valueOf(alertId));

        if(null == called) {
            throw new BadRequest("警情不存在");
        }
        map.put("acAnswerThePolice",called.getCallTime());
        map.put("acReport",called.getRecDate());

        LambdaQueryWrapper<DispatchPaper> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DispatchPaper::getAlertId,Long.valueOf(alertId));
        DispatchPaper dispatchPaper = dispatchPaperService.getOne(queryWrapper);
        List<DispatchTask> dispatchTask = null;
        if(!ValidationUtil.isEmpty(dispatchPaper)) {
            LambdaQueryWrapper<DispatchTask> queryWrapper1 = new LambdaQueryWrapper();
            queryWrapper1.eq(DispatchTask::getPaperId,Long.valueOf(dispatchPaper.getSequenceNbr()));
            dispatchTask  = dispatchTaskService.list(queryWrapper1);
        }

        String [] str = new String[]{"使用单位","一级响应","二级响应","三级响应","市级监督"};

        if(null != dispatchPaper) {
            map.put("adNotice",dispatchPaper.getDispatchTime());
            map.put("aedArrive",dispatchPaper.getArriveTime());
            map.put("afeComplete",dispatchPaper.getSaveTime());
            for(String s:str) {
                AlertHandlerInfoDto alertHandlerInfoDto = new AlertHandlerInfoDto();
                if(null != dispatchTask &&dispatchTask.size() > 0 ) {
                    List<DispatchTask> taskList =  dispatchTask.stream().filter(e->e.getOrgType().equals(s)).collect(Collectors.toList());
                    if(taskList.size() > 0) {
                        dataInit(alertHandlerInfoDto,s,"", "","已派遣",
                                dispatchTask.get(0).getArriveTime() == null ? "" : "已到达" ,dispatchTask.get(0).getSaveTime() == null ? "" : "已完成",
                                dispatchPaper.getFeedbackTime() != null || dispatchPaper.getFeedbackFinishTime() != null ? "已回访" : "");
                    } else {
                        dataInit(alertHandlerInfoDto,s,"","","","","","");
                    }
                }
                list.add(alertHandlerInfoDto);
            }
            map.put("agReturnVisit",dispatchPaper.getFeedbackFinishTime()); // 修复BUG 3439 by kongfm
        } else {
            for(String s:str) {
                AlertHandlerInfoDto alertHandlerInfoDto = new AlertHandlerInfoDto();
                dataInit(alertHandlerInfoDto,s,"","","","","","");
                list.add(alertHandlerInfoDto);
            }
            map.put("adNotice",null);
            map.put("aedArrive",null);
            map.put("afeComplete",null);
            map.put("agReturnVisit",null);
        }
        alertHandlerDto.setAlertHandlerInfoDto(list);
        alertHandlerDto.setHandlerTime(map);
        return alertHandlerDto;
    }

    @Override
    public Object getCalledInfo() {
        LambdaQueryWrapper<AlertCalled> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AlertCalled::getAlertStageCode,"860");
        queryWrapper.ge(AlertCalled::getCallTime,DateUtils.stampToDate(System.currentTimeMillis(),DateUtils.DATE_PATTERN));
        queryWrapper.le(AlertCalled::getCallTime,DateUtils.stampToDate(DateUtils.dateAddDays(new Date(),1).getTime(),DateUtils.DATE_PATTERN));
        Object list =   this.list(queryWrapper);
        return list;
    }

    @Override
    public WechatMyBussinessDto getBussinessInfoById(Long alertId) {
        return  baseMapper.getBussinessInfoById(alertId);
    }

    @Override
    public List<WechatMyBusinessListDto> getBussinessListByPhonePager(String phone, String bussinessCode, Long current) {
        return baseMapper.getBussinessListByPhonePager(phone, bussinessCode, current*5);
    }

    @Override
    public  List<AlertCalledRecordDto> queryAlertRecordListByQueryDto(String callTimeStart, String callTimeEnd, String type, String alertSource, String alarmType) {
        List<AlertCalledRecordDto> list = alertCalledMapper.queryAlertRecordListByQueryDto(callTimeStart,callTimeEnd,type,alertSource,alarmType);
        return list;
    }

    @Override
    public List<DutySeatDto> getSeatInfos() {
        // 获取人员信息
        FeignClientResult<List<AgencyUserModel>> userListResult = Privilege.agencyUserClient.list(null);
        List<AgencyUserModel> userList = userListResult.getResult();
        List<DutySeatDto> dutyList = new ArrayList<>();
        userList.stream().forEach(u -> {
            // 排除非系统中人员
            if(!u.getRealName().equals(u.getMobile())) { // 公众号创建
                DutySeatDto temp = new DutySeatDto();
                temp.setUserId(u.getUserId());
                temp.setUserName(u.getRealName());
                temp.setUserRole("管理员");
                temp.setSeatCode("1001");
                temp.setUserStatus("1");
                // 获取当日警情处理件数
                Calendar c = Calendar.getInstance();
                c.set(Calendar.SECOND,0);
                c.set(Calendar.HOUR_OF_DAY,0);
                c.set(Calendar.MINUTE,0);
                String beginDate = DateUtils.date2LongStr(c.getTime());
                c.set(Calendar.SECOND,59);
                c.set(Calendar.HOUR_OF_DAY,23);
                c.set(Calendar.MINUTE,59);
                String endDate = DateUtils.date2LongStr(c.getTime());
                List<AlertCalled> dealAlert = this.list(new LambdaQueryWrapper<AlertCalled>().eq(AlertCalled::getIsDelete,false).eq(AlertCalled::getRecUserId,u.getUserId())
                        .gt(AlertCalled::getCallTime,beginDate).lt(AlertCalled::getCallTime,endDate).eq(AlertCalled::getAlertStatus, true));
                int count = 0;
                if(dealAlert != null && dealAlert.size() > 0) {
                    count = dealAlert.size();
                }
                temp.setTodayDeal(count);
                temp.setServiceSocre("95");
                dutyList.add(temp);
            }

        });
        return dutyList;
    }

    private void dataInit(AlertHandlerInfoDto alertHandlerInfoDto, String process,String answerThePolice, String report, String notice, String arrive, String complete,String returnVisit) {
        alertHandlerInfoDto.setAbProcess(process);
        alertHandlerInfoDto.setAcAnswerThePolice(answerThePolice);
        alertHandlerInfoDto.setAcReport(report);
        alertHandlerInfoDto.setAdNotice(notice);
        alertHandlerInfoDto.setAedArrive(arrive);
        alertHandlerInfoDto.setAfeComplete(complete);
        alertHandlerInfoDto.setAgReturnVisit(returnVisit);
    }


    /**
     *
     * <pre>
     * 保存警情信息
     * </pre>
     *
     * @param alertCalledObjsDto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public AlertCalledObjsDto createAlertCalled(AlertCalledObjsDto alertCalledObjsDto, AgencyUserModel user) {
        try {
            // 警情基本信息

            AlertCalled alertCalled = BeanDtoVoUtils.convert(alertCalledObjsDto.getAlertCalledDto(),AlertCalled.class);
            alertCalled.setEquipmentClassification("电梯");
            alertCalled.setEquipmentClassificationCode("3000");
            alertCalled.setCallTime(DateUtils.longStr2Date(alertCalled.getCallTimeStr()));

            // 判断是否归并警情
            if (alertCalled.getFatherAlert() != null) {
                // 警情归并，设置当前警情状态为结束。
                alertCalled.setAlertStatus(true);
                alertCalled.setAlertStage(AlertStageEnums.JJ.getValue());
                alertCalled.setAlertStageCode(AlertStageEnums.JJ.getId());
                alertCalled.setType(AlertStageEnums.JQGB.getValue());
                alertCalled.setTypeCode(AlertStageEnums.JQGB.getId());
                this.save(alertCalled);
                // 动态表单
                List<AlertFormValue> alertFormValuelist = alertCalledObjsDto.getAlertFormValue();
                // 填充警情主键
                alertFormValuelist.stream().forEach(alertFormValue -> {
                    alertFormValue.setAlertCalledId(alertCalled.getSequenceNbr());
                    alertFormValue.setAlertTypeCode(alertCalled.getAlarmTypeCode());
                });
                // 保存动态表单数据
                iAlertFormValueService.saveBatch(alertFormValuelist);
                // 警情基本信息
                AlertCalled alertCalledFather = this.getById(alertCalled.getFatherAlert());
                alertCalledObjsDto.setAlertCalledDto(BeanDtoVoUtils.convert(alertCalledFather,AlertCalledDto.class));

            } else {
                // 警情报送
                // ****************************************************待确认开发
                alertCalled.setAlertStatus(false);
                alertCalled.setIsDelete(false);
                alertCalled.setAlertStage(AlertStageEnums.JJ.getValue());
                alertCalled.setAlertStageCode(AlertStageEnums.JJ.getId());
                alertCalled.setType(AlertStageEnums.JQCB.getValue());
                alertCalled.setTypeCode(AlertStageEnums.JQCB.getId());
                LambdaQueryWrapper<Elevator> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Elevator::getRescueCode,alertCalled.getDeviceId());
                Elevator elevator = iElevatorService.getOne(queryWrapper);
                alertCalled.setEquipmentId(elevator.getSequenceNbr());
                alertCalled.setCity(elevator.getCity());
                alertCalled.setDistrict(elevator.getDistrict());
                alertCalled.setRegionCode(elevator.getRegionCode());
                this.save(alertCalled);

                // 动态表单
                List<AlertFormValue> alertFormValuelist = alertCalledObjsDto.getAlertFormValue();
                // 填充警情主键
                alertFormValuelist.stream().forEach(alertFormValue -> {
                    alertFormValue.setAlertCalledId(alertCalled.getSequenceNbr());
                    alertFormValue.setAlertTypeCode(alertCalled.getAlarmTypeCode());
                });
                if(AlertStageEnums.KRJY.getId().equals(alertCalled.getAlarmTypeCode()) ) {
                    //困人救援创建警情时创建救援过程信息
                    rescueProcessServiceImpl.getProcessByAlertId(alertCalled.getSequenceNbr());
                }

                // 保存动态表单数据
                iAlertFormValueService.saveBatch(alertFormValuelist);
                alertCalledObjsDto.setAlertCalledDto(BeanDtoVoUtils.convert(alertCalled,AlertCalledDto.class));
                alertCalledObjsDto.setAlertFormValue(alertFormValuelist);
                //保存处置记录-接警
                repairConsultServiceImpl.saveRepairConsultByAlertIdType(alertCalled.getSequenceNbr(),AlertStageEnums.JJ.getCode(),null, user); //保存接警日志
            }

            /**
             * 同步保存ES
             */
            eSAlertCalledService.saveAlertCalledToES(alertCalled);

            return alertCalledObjsDto;
        } catch (Exception e) {
            logger.error("报送失败",e);
            throw new RuntimeException("报送失败，系统异常!");
        }
    }

    /**
     *
     * <pre>
     * 保存警情信息  公众号
     * </pre>
     *
     * @param alertCalledDto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public AlertCalledDto createAlertCalled(AlertCalledDto alertCalledDto) {
        try {
            // 警情基本信息
            AlertCalled alertCalled = BeanDtoVoUtils.convert(alertCalledDto,AlertCalled.class);

            alertCalled.setCallTime(new Date());

            // 警情报送
            alertCalled.setAlertStatus(false);
            alertCalled.setAlertSource(AlertStageEnums.APPJJ.getValue());
            alertCalled.setAlertSourceCode(AlertStageEnums.APPJJ.getId());
            alertCalled.setIsDelete(false);
            alertCalled.setAlertStage(AlertStageEnums.JJ.getValue());
            alertCalled.setAlertStageCode(AlertStageEnums.JJ.getId());
            alertCalled.setType(AlertStageEnums.JQCB.getValue());
            alertCalled.setTypeCode(AlertStageEnums.JQCB.getId());
            this.save(alertCalled);

            // 保存照片
            Map<String, List<AttachmentDto>> attachmentMap = new HashMap<>();
            attachmentMap.put("imgs",alertCalledDto.getImages());
            ISourceFileService.saveAttachments(alertCalled.getSequenceNbr(),attachmentMap);

            // 动态表单
            AlertFormValue  alertFormValue = new AlertFormValue();
            // 填充警情主键
            alertFormValue.setAlertCalledId(alertCalled.getSequenceNbr());
            alertFormValue.setAlertTypeCode(alertCalled.getAlarmTypeCode());
            if(AlertStageEnums.GZWX.getCode().equals(alertCalled.getAlarmTypeCode())) {
                alertFormValue.setFieldName("故障报修描述");
                alertFormValue.setFieldValue(alertCalledDto.getDescribe());
                alertFormValue.setAlertFormId(8L);
                alertFormValue.setFieldCode("fault_report");
            } else {
                alertFormValue.setFieldName("投诉咨询描述");
                alertFormValue.setFieldValue(alertCalledDto.getDescribe());
                alertFormValue.setFieldCode("complaint_consulttation");
                alertFormValue.setAlertFormId(9L);
            }

            // 保存动态表单数据
            iAlertFormValueService.save(alertFormValue);
            //保存处置记录-接警  保存接警日志
            repairConsultServiceImpl.saveRepairConsultByAlertIdType(alertCalled.getSequenceNbr(), TzsCommonParam.APPJJ,null, null);

            /**
             * 同步保存ES
             */
            eSAlertCalledService.saveAlertCalledToES(alertCalled);

            return alertCalledDto;
        } catch (Exception e) {
            logger.error("报送失败",e);
            throw new RuntimeException("报送失败，系统异常!");
        }
    }


    public Map<String, Object> getAlertInfoList(String beginDate, String endDate,String orgCode, String recUserId) {

        Map<String, Object> result = Maps.newHashMap();
        Map<String, Integer> statusCountMap = alertCalledMapper.queryAlertStatusCount(beginDate, endDate,orgCode,recUserId);

        result.put("calledCount",statusCountMap.get("calledCount"));
        result.put("majorAlertCount",statusCountMap.get("majorAlertCount"));
        result.put("sleepyIncidentCount",statusCountMap.get("sleepyIncidentCount"));
        result.put("faultRescueCount",statusCountMap.get("faultRescueCount"));
        result.put("suggestionsCount",statusCountMap.get("suggestionsCount"));

        return result;
    }

    public Map<String, Object> getNearlyInfo(String beginDate, String endDate,String orgCode, String recUserId) {

        Map<String, Object> result = Maps.newHashMap();
        List<Map<String, Integer>> statusCountMap = alertCalledMapper.queryNearlyCount(beginDate, endDate,orgCode,recUserId);
         for(int i = 0; i<statusCountMap.size();i++) {
             if(statusCountMap.get(i).size() > 1) {
                 result.put("dateTime"+i,statusCountMap.get(i).get("dateTime"));
                 result.put("majorAlertCount"+i,statusCountMap.get(i).get("majorAlertCount"));
             } else {
                 result.put("dateTime"+i,statusCountMap.get(i).get("dateTime"));
                 result.put("majorAlertCount"+i,0);
             }
         }
        return result;
    }

	public Object getTodayEmergencyCount(String regionCode) {
        Map<String,Integer> map = alertCalledMapper.getTodayEmergencyCount(regionCode);
        Map<String,Integer> map1  =  alertCalledMapper.getImportantEventCount(regionCode);
        map.put("importantEventCount",map1.get("importantEventCount"));
	    return	map;
	}

//	public Object getImportantEventCount() {
//		return
//	}

	public Object getImportantEventOrTodayEmergencyCount(String type,String regionCode) {
//		List<Map<String, Object>> map=null;
//        List<Map<String, Object>> map1= new LinkedList<>();
//		LambdaQueryWrapper<AlertCalled> queryWrapper=new LambdaQueryWrapper<AlertCalled>();
//		queryWrapper.eq(AlertCalled::getIsDelete, 0);
//		queryWrapper.eq(AlertCalled::getAlarmTypeCode, "960");
//		if("rescueTotal".equals(type)) {
//			queryWrapper.in(AlertCalled::getAlertStageCode,Arrays.asList("861","862"));
//		}else if("rescueComplete".equals(type)) {
//			queryWrapper.in(AlertCalled::getAlertStageCode,Arrays.asList("864","865","866"));
//		}
		if("importantEventCount".equals(type)) {
            return alertCalledMapper.getImportantEventDetail(type,regionCode);
		} else {
            if("rescueTotal".equals(type)) {
                return alertCalledMapper.getTodayEmergencyDetail(type,null,regionCode);
            } else if("rescueComplete".equals(type))  {
                return alertCalledMapper.getTodayEmergencyDetail(null,type,regionCode);
            } else {
                return alertCalledMapper.getTodayEmergencyDetail(null,null,regionCode);
            }
        }

//        for (Map<String,Object> m:  map
//             ) {
//            LambdaQueryWrapper<Elevator> queryWrapper1=new LambdaQueryWrapper<>();
//            queryWrapper1.eq(Elevator::getIsDelete, 0);
//            queryWrapper1.eq(Elevator::getSequenceNbr, m.get("equipment_id"));
//            Elevator elevator = iElevatorService.getOne(queryWrapper1);
//            m.put("injured","无伤亡");
//            if(null != elevator) {
//                m.put("longitude",elevator.getLongitude());
//                m.put("latitude",elevator.getLatitude());
//                m.put("regionCode",elevator.getRegionCode());
//
//                if(elevator.getRegionCode().contains(regionCode)) {
//                    map1.add(m);
//                }
//            }
//        }
	}

    public List<AlertPaperInfoDto> getAlertPaperInfoList(List<String> regionCodes, Boolean isHistory) {
        List<AlertPaperInfoDto> temp = baseMapper.getAlertPaperInfoList(regionCodes, isHistory);
        temp.stream().forEach(t -> {
            DispatchPaper paper = dispatchPaperService.getOne(new LambdaQueryWrapper<DispatchPaper>().eq(DispatchPaper::getIsDelete,false).eq(DispatchPaper::getAlertId,t.getAlertId()));
            if(paper != null) {
                t.setFinishTime(paper.getFeedbackFinishTime());
            }
        });
        return temp;
    }

    @Override
    public List<AlertPaperInfoDto> getEquipmentHistory(List<String> regionCodes, String equipmentClassCode, Integer current, Integer pageNum, String equipmentCode) {
        current = pageNum * ( current - 1);
        List<AlertPaperInfoDto> temp = baseMapper.getEquipmentHistory(regionCodes, equipmentClassCode,current,pageNum ,equipmentCode);
        return temp;
    }

    @Override
    public Integer getEquipmentHistoryCount(List<String> useRegionCode, String equipmentClassCode, String equipmentCode) {
        return baseMapper.getEquipmentHistoryCount(useRegionCode,equipmentClassCode,equipmentCode);
    }
}