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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.ccs.api.dto.FireStationInfoDto;
import com.yeejoin.amos.boot.module.ccs.api.entity.FireFightingSystem;
import com.yeejoin.amos.boot.module.ccs.api.entity.FireStationInfo;
import com.yeejoin.amos.boot.module.ccs.api.enums.StationOrderByTypeEnum;
import com.yeejoin.amos.boot.module.ccs.api.mapper.FireEquipmentSignalLogMapper;
import com.yeejoin.amos.boot.module.ccs.api.mapper.FireFightingSystemMapper;
import com.yeejoin.amos.boot.module.ccs.api.mapper.FireStationInfoMapper;
import com.yeejoin.amos.boot.module.ccs.api.mapper.FireVehicleMapper;
import com.yeejoin.amos.boot.module.ccs.api.service.IFireStationInfoService;
import com.yeejoin.amos.boot.module.ccs.api.vo.AlarmCountVO;
import com.yeejoin.amos.boot.module.ccs.api.vo.CarInfoVO;
import com.yeejoin.amos.boot.module.ccs.api.vo.CarNumberVO;
import com.yeejoin.amos.boot.module.ccs.api.vo.DateAlarmCountVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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

/**
 * 站端信息表服务实现类
 *
 * @author system_generator
 * @date 2021-11-09
 */
@Service
public class FireStationInfoServiceImpl extends BaseService<FireStationInfoDto, FireStationInfo, FireStationInfoMapper> implements IFireStationInfoService {

    @Autowired
    private FireVehicleMapper fireVehicleMapper;

    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    private FireEquipmentSignalLogMapper fireEquipmentSignalLogMapper;

    /**
     * 列表查询 示例
     *
     * @param orderBy
     */
    public List<FireStationInfoDto> queryForFireStationInfoList(String orderBy) throws Exception {
        if (StringUtils.isNotBlank(orderBy)) {
            Optional<StationOrderByTypeEnum> op = StationOrderByTypeEnum.getEnum(orderBy);
            op.orElseThrow(() -> new Exception("不存在查询排序条件"));
            return this.baseMapper.queryStationListWithStatistics(op.get().getOrderBy());
        } else {
            return this.baseMapper.queryStationListWithStatistics(null);
        }
    }

    @Override
    public FireStationInfoDto getOneByCode(String code) {
        List<FireStationInfoDto> dtos = this.queryForList("", false, code);
        if (dtos.isEmpty()) {
            throw new RuntimeException("不存在指定数据");
        }
        return dtos.iterator().next();
    }

    public List<FireStationInfoDto> queryStationAlarmListByCode(String stationCode, Integer top) {
        List<FireStationInfoDto> fireStationInfoList = this.baseMapper.queryStationAlarmListByCode(stationCode);
        List<AlarmCountVO> alarmCountVOS = this.baseMapper.queryAlarmCountByCode();
        Map<String, AlarmCountVO> collect = alarmCountVOS.stream().collect(Collectors.toMap(AlarmCountVO::getStationCode, t -> t));
        fireStationInfoList.forEach(item -> {
            if (collect.containsKey(item.getCode())) {
                item.setAlarmNum(collect.get(item.getCode()).getAlarmNum());
                item.setConfirmTrueNum(collect.get(item.getCode()).getConfirmTrueNum());
                item.setConfirmFalseNum(collect.get(item.getCode()).getConfirmFalseNum());
            }
        });
        List<FireStationInfoDto> finalVoList = new ArrayList<>();
        if (null == top) {
            finalVoList = fireStationInfoList.stream().skip(0).sorted(Comparator.comparing(FireStationInfoDto::getAlarmNum).reversed()).collect(Collectors.toList());
        } else {
            finalVoList = fireStationInfoList.stream().skip(0).sorted(Comparator.comparing(FireStationInfoDto::getAlarmNum).reversed()).limit(top).collect(Collectors.toList());
        }
        return finalVoList;
    }

    public Map<String, Integer> getAlarmNumByDate(String stationCode) {
        Date date = DateUtil.date();
        String year = DateUtil.format(date, "YYYY");
        String currentMonth = DateUtil.format(date, DatePattern.NORM_MONTH_PATTERN);
        String yesterday = DateUtil.format(DateUtil.offsetDay(date, -1), DatePattern.NORM_DATE_PATTERN);
        Integer todayNum = this.baseMapper.queryAlarmCountByDateAndCode(stationCode, DateUtil.today());
        Integer currentYearNum = this.baseMapper.queryAlarmCountByDateAndCode(stationCode, year);
        Integer currentMonthNum = this.baseMapper.queryAlarmCountByDateAndCode(stationCode, currentMonth);
        Integer yesterdayNum = this.baseMapper.queryAlarmCountByDateAndCode(stationCode, yesterday);
        HashMap<String, Integer> resultMap = new HashMap<>();
        resultMap.put("todayNum", todayNum);
        resultMap.put("currentYearNum", currentYearNum);
        resultMap.put("currentMonthNum", currentMonthNum);
        resultMap.put("yesterdayNum", yesterdayNum);
        return resultMap;
    }

    public Map<String, List<String>> getAlarmNumByDateTimePeriod(String stationCode, String beginDateTime, String endDateTime) {
        HashMap<String, List<String>> resultMap = new HashMap<>();
        if (StrUtil.isEmpty(beginDateTime) || StrUtil.isEmpty(endDateTime)) {
            throw new BadRequest("开始时间和结束时间不能为空");
        }
        if (StrUtil.isEmpty(stationCode)) {
            List<String> stationNameList = new ArrayList<>();
            List<String> alarmNumList = new ArrayList<>();
            List<FireStationInfoDto> fireStationInfoList = this.baseMapper.queryStationAlarmListByCode(stationCode);
            List<AlarmCountVO> alarmCountVOS = this.baseMapper.queryAllAlarmCountByCode(beginDateTime, endDateTime);
            Map<String, AlarmCountVO> collect = alarmCountVOS.stream().collect(Collectors.toMap(AlarmCountVO::getStationCode, t -> t));
            fireStationInfoList.forEach(item -> {
                if (collect.containsKey(item.getCode())) {
                    item.setAlarmNum(collect.get(item.getCode()).getAlarmNum());
                }
                stationNameList.add(item.getName());
                alarmNumList.add(String.valueOf(item.getAlarmNum()));
            });
            resultMap.put("stationNames", stationNameList);
            resultMap.put("alarmNums", alarmNumList);
        } else {
            List<String> dateList = new ArrayList<>();
            List<String> alarmNumList = new ArrayList<>();
            List<DateAlarmCountVO> alarmNumByDateTimePeriodByStationCode = this.baseMapper.getAlarmNumByDateTimePeriodByStationCode(stationCode, beginDateTime, endDateTime);
            alarmNumByDateTimePeriodByStationCode.forEach(item -> {
                dateList.add(item.getDate());
                alarmNumList.add(item.getAlarmNums());
            });
            resultMap.put("date", dateList);
            resultMap.put("alarmNum", alarmNumList);
        }
        return resultMap;
    }

    public Map<String, List<String>> getAlarmTrendByDatePeriod(String stationCode, String beginDate, String endDate) {
        HashMap<String, List<String>> resultMap = new HashMap<>();
        List<String> dateList = new ArrayList<>();
        List<String> alarmNumList = new ArrayList<>();
        List<DateAlarmCountVO> alarmTrendByDatePeriod = this.baseMapper.getAlarmTrendByDatePeriod(stationCode, beginDate, endDate);
        alarmTrendByDatePeriod.forEach(item -> {
            dateList.add(item.getDate());
            alarmNumList.add(item.getAlarmNums());
        });
        resultMap.put("date", dateList);
        resultMap.put("alarmNum", alarmNumList);
        return resultMap;
    }

    public List<CarInfoVO> getCarInfoByStationCode(String stationCode) {
        List<CarInfoVO> carInfoByStationCode = fireVehicleMapper.getCarInfoByStationCode(stationCode);
        carInfoByStationCode.forEach(item -> {
            if (StrUtil.isNotEmpty(item.getStrCarNumber())) {
                List<CarNumberVO> carNumberVOS = new ArrayList<>();
                List<String> list = Arrays.asList(item.getStrCarNumber().split(","));
                list.forEach(carNum -> {
                    CarNumberVO carNumberVO = new CarNumberVO();
                    carNumberVO.setCarNum(carNum);
                    carNumberVOS.add(carNumberVO);
                });
                item.setCarList(carNumberVOS);
            }
        });
        return carInfoByStationCode;
    }

    public List<Map<String, String>> getFireSystemByStationCode(String stationCode) {
        List<Map<String, String>> resultList= new ArrayList<>();
        List<FireFightingSystem> mridList = fireFightingSystemMapper.getMridByCode(stationCode);
        mridList.forEach(item -> {
            HashMap<String, String> resultMap = new HashMap<>();
            resultMap.put("systemName", item.getName());
            resultMap.put("alarmNum", String.valueOf(fireEquipmentSignalLogMapper.getAlarmCountByMrid(item.getMrid())));
            resultList.add(resultMap);
        });
        return resultList;
    }
}