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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.module.jcs.api.dto.*;
import com.yeejoin.amos.boot.module.jcs.api.enums.DutyInfoEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
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.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
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.FireBrigadeTypeEnum;
import com.yeejoin.amos.boot.module.jcs.api.enums.FireCarStatusEnum;
import com.yeejoin.amos.boot.module.jcs.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.IPowerTransferService;

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

    @Autowired
    AlertCalledServiceImpl alertCalledService;

    @Autowired
    PowerTransferCompanyServiceImpl powerTransferCompanyService;

    @Autowired
    PowerTransferCompanyResourcesServiceImpl powerTransferCompanyResourcesService;

    @Autowired
    TemplateServiceImpl templateService;

    @Autowired
    AlertFormValueServiceImpl alertFormValueService;

    @Autowired
    EquipFeignClient equipFeignService;

    @Autowired
    FireTeamServiceImpl fireTeamService;

    @Autowired
    PowerTransferMapper powerTransferMapper;
    @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) {
        // 获取调派ID
        Long alertCalledId = powerTransferDto.getAlertCalledId();
        int count = count(new QueryWrapper<PowerTransfer>().eq("alert_called_id", alertCalledId));
        String dispatch_num = alertCalledId.toString() + (count + 1);

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

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

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

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

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

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

        // 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);
                });
            }
        }

        // 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();
        FireBrigadeResourceDto monitorResourceDto = new FireBrigadeResourceDto();
        monitorResourceDto.setId("0");
        monitorResourceDto.setName(FireBrigadeTypeEnum.监控大队.getName());
        monitorResourceDto.setType(FireBrigadeTypeEnum.监控大队.getKey());
        monitorResourceDto.setChildren(monitorFireBrigadeList);

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

        return fireBrigadeResourceList;
    }



    private List<PowerTransferCompanyResources> DtoEntityBatchConvert(List<PowerTransferCompanyResourcesDto> powerTransferCompanyResourcesDtoList, Long powerTransferCompanySequenceNbr) {
        ArrayList<PowerTransferCompanyResources> powerTransferCompanyResourcesList = new ArrayList<>();
        PowerTransferCompanyResources powerTransferCompanyResources;
        for (PowerTransferCompanyResourcesDto powerTransferCompanyResourcesDto : powerTransferCompanyResourcesDtoList) {
            powerTransferCompanyResources = new PowerTransferCompanyResources();
            BeanUtils.copyProperties(powerTransferCompanyResourcesDto, powerTransferCompanyResources);
            powerTransferCompanyResources.setPowerTransferCompanyId(powerTransferCompanySequenceNbr);
            powerTransferCompanyResourcesList.add(powerTransferCompanyResources);
        }
        return powerTransferCompanyResourcesList;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

        return transferInfo;
    }

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