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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.module.hygf.api.dto.JpStationDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.TdHygfJpInverterWarnDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.HYGFMaintenanceTickets;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpStation;
import com.yeejoin.amos.boot.module.hygf.api.entity.StdUserEmpower;
import com.yeejoin.amos.boot.module.hygf.api.entity.TdHygfJpInverterWarn;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HYGFMaintenanceTicketsMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.JpCollectorMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.JpInverterMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserEmpowerMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.ITdHygfJpInverterWarnService;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.TdHygfJpInverterWarnMapper;
import com.yeejoin.amos.boot.module.hygf.api.util.TimeUtil;

import cn.hutool.core.util.ObjectUtil;

/**
 * 户用光伏监盘逆变器报警表服务实现类
 *
 * @author system_generator
 * @date 2023-09-19
 */
@Service
public class TdHygfJpInverterWarnServiceImpl
        extends BaseService<TdHygfJpInverterWarnDto, TdHygfJpInverterWarn, TdHygfJpInverterWarnMapper>
        implements ITdHygfJpInverterWarnService {

    @Autowired
    JpStationServiceImpl jpStationServiceImpl;

    @Autowired
    HYGFMaintenanceTicketsMapper hygfMaintenanceTicketsMapper;
    @Autowired
    TdHygfJpInverterWarnMapper tdHygfJpInverterWarnMapper;
    @Autowired
    JpInverterMapper jpInverterMapper;
    @Autowired
    JpCollectorMapper jpCollectorMapper;
    @Autowired
    private UserEmpowerMapper userEmpowerMapper;
    /**
     * 分页查询
     */
    public Page<TdHygfJpInverterWarnDto> queryForTdHygfJpInverterWarnPage(Page<TdHygfJpInverterWarnDto> pageParam,
                                                                          TdHygfJpInverterWarnDto tdHygfJpInverterWarnDto) {
        int pageNum = (int) pageParam.getCurrent();
        int pageSize = (int) pageParam.getSize();
        PageHelper.startPage(pageNum, pageSize);
        if (tdHygfJpInverterWarnDto.getState() != null) {
            String[] s = tdHygfJpInverterWarnDto.getState().split(",");
            tdHygfJpInverterWarnDto.setStates(Arrays.asList(s));
        }
        if (tdHygfJpInverterWarnDto.getStationName() != null) {
            LambdaQueryWrapper<JpStation> wapper = new LambdaQueryWrapper<JpStation>().like(JpStation::getName,
                    tdHygfJpInverterWarnDto.getStationName());
            if (!tdHygfJpInverterWarnDto.getStationIds().isEmpty()) {
                wapper.in(JpStation::getThirdStationId, tdHygfJpInverterWarnDto.getStationIds());
            }
            List<JpStation> sList = jpStationServiceImpl.list(wapper);
            List<String> ids = sList.stream().map(i -> i.getThirdStationId()).collect(Collectors.toList());
            tdHygfJpInverterWarnDto.setStationIds(ids);
        }
//				if (tdHygfJpInverterWarnDto.getHandlerStatus() != null) {
//			String[] s = tdHygfJpInverterWarnDto.getHandlerStatus().split(",");
//			tdHygfJpInverterWarnDto.setListHandlerStatus(Arrays.asList(s));
//		}
        List<TdHygfJpInverterWarnDto> list = new ArrayList<>();
        if (tdHygfJpInverterWarnDto.getStationIds().isEmpty()) {

        } else {

            list = this.baseMapper.list(tdHygfJpInverterWarnDto);

            if (!list.isEmpty()) {
                list.forEach(i -> {
                    JpStation jpStation = jpStationServiceImpl.getOne(new LambdaQueryWrapper<JpStation>()
                            .eq(JpStation::getThirdStationId, i.getThirdStationId()));
                    if (jpStation != null) {
                        i.setAddress(jpStation.getAddress());
                        i.setStationName(jpStation.getName());
                        i.setArea(jpStation.getArea());
                    }
                    if (i.getStartTime() != null) {
                        i.setStartTimeFormat(TimeUtil.dateFormat(i.getStartTime()));
                    }
                });
            }
        }
        List<Long> waringIds = list.stream().map(tdHygfJpInverterWarnDto1 -> tdHygfJpInverterWarnDto1.getCreatedTime()).collect(Collectors.toList());
        if (waringIds.size() == 0) {
            waringIds = Arrays.asList(0L);
        }
        List<HYGFMaintenanceTickets> hygfMaintenanceTicketsList = hygfMaintenanceTicketsMapper.selectList(new QueryWrapper<HYGFMaintenanceTickets>().in("warning_id", waringIds));
        if (hygfMaintenanceTicketsList.size() > 0) {
            list.forEach(i -> {
                List<HYGFMaintenanceTickets> ticketsList = hygfMaintenanceTicketsList.stream().filter(hygfmaintenanceTickets -> i.getCreatedTime().equals(hygfmaintenanceTickets.getWarningId())).collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(ticketsList)) {
                    Set<String> status = ticketsList.stream().map(HYGFMaintenanceTickets::getHandlerStatus).collect(Collectors.toSet());
                    if (status.contains("未处理")) {
                        i.setTicketStatus("处理中");
                    }
                    if (status.contains("已处理") && status.size() == 1) {
                        i.setTicketStatus("已处理");
                    }
                }
            });
        }
        PageInfo<TdHygfJpInverterWarnDto> page = new PageInfo(list);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<TdHygfJpInverterWarnDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<TdHygfJpInverterWarnDto>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(pageSize);
        pagenew.setRecords(page.getList());
        return pagenew;
    }

    /**
     * 列表查询 示例
     */
    public List<TdHygfJpInverterWarnDto> queryForTdHygfJpInverterWarnList() {
        return this.getBaseMapper().listAll();
    }

    public TdHygfJpInverterWarnDto queryByCreatedTime(long createdTime) {
        Map map = new HashMap<>();
        map.put("created_time", createdTime);
        TdHygfJpInverterWarnDto tdHygfJpInverterWarnDto = this.baseMapper.getByTime(createdTime);
        JpStation jpStation = jpStationServiceImpl.getOne(new LambdaQueryWrapper<JpStation>()
                .eq(JpStation::getThirdStationId, tdHygfJpInverterWarnDto.getThirdStationId()));
        List<HYGFMaintenanceTickets> hygfMaintenanceTickets = hygfMaintenanceTicketsMapper.
                selectList(new QueryWrapper<HYGFMaintenanceTickets>()
                        .eq("warning_id", String.valueOf(tdHygfJpInverterWarnDto.getCreatedTime()))
                        .eq("inverter_sn", String.valueOf(tdHygfJpInverterWarnDto.getSnCode())));
        if (jpStation != null) {
            tdHygfJpInverterWarnDto.setStationName(jpStation.getName());
            tdHygfJpInverterWarnDto.setStationContact(jpStation.getStationContact());
            tdHygfJpInverterWarnDto.setUserName(jpStation.getUserName());
            tdHygfJpInverterWarnDto.setUserPhone(jpStation.getUserPhone());
            tdHygfJpInverterWarnDto.setEmail(jpStation.getEmail());
            tdHygfJpInverterWarnDto.setAddress(jpStation.getAddress());
            tdHygfJpInverterWarnDto.setArea(jpStation.getArea());
            if (tdHygfJpInverterWarnDto.getRecoverTime() != null) {
                tdHygfJpInverterWarnDto
                        .setRecoverTimeFormat(TimeUtil.dateFormat(tdHygfJpInverterWarnDto.getRecoverTime()));
                tdHygfJpInverterWarnDto.setTimeLongFormat(TimeUtil
                        .longFormat(tdHygfJpInverterWarnDto.getRecoverTime() - tdHygfJpInverterWarnDto.getStartTime()));
            }
            if (tdHygfJpInverterWarnDto.getStartTime() != null) {
                tdHygfJpInverterWarnDto.setStartTimeFormat(TimeUtil.dateFormat(tdHygfJpInverterWarnDto.getStartTime()));
            }
        }
        if (hygfMaintenanceTickets.size() > 0) {
            Set<String> status = hygfMaintenanceTickets.stream().filter(hygfmaintenanceTickets -> tdHygfJpInverterWarnDto.getCreatedTime().equals(hygfmaintenanceTickets.getWarningId())).map(HYGFMaintenanceTickets::getHandlerStatus).collect(Collectors.toSet());
            if (status.contains("未处理")) {
                tdHygfJpInverterWarnDto.setTicketStatus("处理中");
            }
            if (status.contains("已处理") && status.size() == 1) {
                tdHygfJpInverterWarnDto.setTicketStatus("已处理");
            }
            tdHygfJpInverterWarnDto.setListTickets(hygfMaintenanceTickets);
        }
        return tdHygfJpInverterWarnDto;
    }

    public List<TdHygfJpInverterWarnDto> selectWarnList(List<String> state,String regionalCompaniesCode,String amosCompanyCode,String thirdStationId,String type, String level, String minvalue, String maxValue, String snCode, List<String> stationId, String startTime, String endTime, String content, Integer current, Integer size, String handlerStatus, String stationName,String isDeal) {
        List<TdHygfJpInverterWarnDto> list = tdHygfJpInverterWarnMapper.selectWarnList(state,regionalCompaniesCode,amosCompanyCode,thirdStationId,type, level, minvalue, maxValue, snCode, stationId, startTime, endTime, content, (current - 1) * size, size, handlerStatus, stationName,isDeal);
        list.forEach(i -> {
            JpStation jpStation = jpStationServiceImpl.getOne(new LambdaQueryWrapper<JpStation>()
                    .eq(JpStation::getThirdStationId, i.getThirdStationId()));
            if (ObjectUtil.isNotNull(jpStation)) {
                i.setAddress(jpStation.getAddress());
                i.setArea(jpStation.getArea());
                i.setStationName(jpStation.getName());
            }
        });
        return list;
    }

    public Integer selectWarnListTotal(List<String> state,String regionalCompaniesCode, String amosCompanyCode, String thirdStationId, String type, String level, String minvalue, String maxValue, String snCode, List<String> stationId, String startTime, String endTime, String content, String handlerStatus, String stationName,String isDeal) {
        Integer count = tdHygfJpInverterWarnMapper.selectWarnListTotal(state, regionalCompaniesCode, amosCompanyCode, thirdStationId, type, level, minvalue, maxValue, snCode, stationId, startTime, endTime, content, handlerStatus, stationName, isDeal);
        return count == null ? 0:count;
    }

    public Integer selectWarnTotal(List<String> state,String regionalCompaniesCode,
                               String amosCompanyCode,
                               String thirdStationId,
                               String type) {
        Integer count = tdHygfJpInverterWarnMapper.selectWarnTotal(state, regionalCompaniesCode, amosCompanyCode, thirdStationId, type);
        return count == null ? 0:count;
    }

    public Map<String, Object> queryAlarmNumber(String regionalCompaniesCode, String amosCompanyCode, String thirdStationId, String type) {
//        查询所有场站
        List<JpStationDto> jpStationDtos = jpStationServiceImpl.queryAllPowerStation(regionalCompaniesCode, amosCompanyCode, thirdStationId, type);

        Map<String, Object> result = new HashMap<>();


        if (!CollectionUtils.isEmpty(jpStationDtos)) {
            //        获取thirdStationId集合
            Set<String> regionalCompaniesCodes = jpStationDtos.stream().map(JpStation -> JpStation.getRegionalCompaniesCode()).collect(Collectors.toSet());


            List<TdHygfJpInverterWarnDto> tdHygfJpInverterWarnDtos = tdHygfJpInverterWarnMapper.queryAlarmNumber(regionalCompaniesCodes);


            ArrayList<String> yclArray = new ArrayList<>();
            ArrayList<String> wclArray = new ArrayList<>();

            tdHygfJpInverterWarnDtos.stream().forEach(tdHygfJpInverterWarnDto -> {
                if (tdHygfJpInverterWarnDto.getState().equals("已恢复") || tdHygfJpInverterWarnDto.getState().equals("已处理")) {
                    yclArray.add(tdHygfJpInverterWarnDto.getState());
                } else {
                    wclArray.add(tdHygfJpInverterWarnDto.getState());
                }
            });


            result.put("ycl", yclArray.size());
            result.put("wcl", wclArray.size());

        }else {
            result.put("ycl", 0);
            result.put("wcl", 0);
        }

        return result;

    }


    public Map<String, Object> queryStateNumber(String regionalCompaniesCode, String amosCompanyCode, String thirdStationId, String type) {
        
   	 List<String> thirdStationIds=null;
	  String userid=RequestContext.getExeUserId();
    LambdaQueryWrapper<StdUserEmpower> qu=new LambdaQueryWrapper();
    qu.eq(StdUserEmpower::getAmosUserId,userid);
    qu.eq(StdUserEmpower::getPermissionType,"HYGF");
    StdUserEmpower stdUserEmpower= userEmpowerMapper.selectOne(qu);
	 
	if(regionalCompaniesCode==null&&amosCompanyCode==null&&stdUserEmpower!=null&&stdUserEmpower.getAmosOrgCode().contains("all")) 
	{
		 thirdStationIds=null;
	}
	else 
	{
//     查询所有场站
       List<JpStationDto> jpStationDtos = jpStationServiceImpl.queryAllPowerStation(regionalCompaniesCode, amosCompanyCode, thirdStationId, type);

      
       if (!CollectionUtils.isEmpty(jpStationDtos)) {
		 thirdStationIds = jpStationDtos.stream().map(JpStation -> JpStation.getThirdStationId()).collect(Collectors.toList());
       }
	}

    	


            Map<String, Object> result = new HashMap<>();
       

            //在线
            List<Integer> online = new ArrayList<>();
            //报警
            List<Integer> warn = new ArrayList<>();
            //离线
            List<Integer> offline = new ArrayList<>();

            //逆变器
            List<Map<String, Object>> map = jpInverterMapper.selectInverterState(thirdStationIds);
            map.forEach(e->{
                if (e.get("status").equals("在线")){
                    online.add(Integer.valueOf(e.get("count").toString()));
                }else if (e.get("status").equals("报警")){
                    warn.add(Integer.valueOf(e.get("count").toString()));
                }else {
                    offline.add(Integer.valueOf(e.get("count").toString()));
                }
            });

            //采集器
            List<Map<String, Object>> maps = jpCollectorMapper.selectInverterState(thirdStationIds);
            maps.forEach(e->{
                if (e.get("status").equals("在线")){
                    online.add(Integer.valueOf(e.get("count").toString()));
                }else if (e.get("status").equals("报警")){
                    warn.add(Integer.valueOf(e.get("count").toString()));
                }else {
                    offline.add(Integer.valueOf(e.get("count").toString()));
                }
            });
            //目前系统无气象仪及电表
            List<Integer> kong = new ArrayList<>(Arrays.asList(0,0));
            online.addAll(kong);
            warn.addAll(kong);
            offline.addAll(kong);

            Map<String, Object> resultNumMap = new HashMap<>();
            resultNumMap.put("online",online);
            resultNumMap.put("warn",warn);
            resultNumMap.put("offline",offline);

            result.put("xData",Arrays.asList("在线","报警","离线"));
            result.put("yData",resultNumMap);

        return result;

    }
}