package com.zcxk.charge.web.service.impl;

import com.zcxk.charge.api.dto.query.HomePageReportDto;
import com.zcxk.charge.api.enums.DeviceParamTypeEnum;
import com.zcxk.charge.api.enums.SceneTypeEnum;
import com.zcxk.charge.api.vo.DeviceEntityVo;
import com.zcxk.charge.api.vo.SceneEntityVo;
import com.zcxk.charge.api.vo.WaterSupplyDataVo;
import com.zcxk.charge.web.client.UserCenterClient;
import com.zcxk.charge.core.dao.AppReportMonitorMapper;
import com.zcxk.charge.core.dao.HomePageReportMapper;
import com.zcxk.charge.api.dto.CompanySceneInfoDto;
import com.zcxk.charge.api.dto.OrgBaseTreeInfoDto;
import com.zcxk.charge.api.dto.generalview.WaterSupplyChart;
import com.zcxk.charge.web.service.AppReportMonitorService;
import com.zcxk.charge.web.service.MonitorDataReportService;
import com.zcxk.core.oauth2.pojo.LoginUser;
import com.zcxk.core.oauth2.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description
 * @author  wangli
 * @data 2021/3/19 11:29
 */
@Service
public class AppReportMonitorServiceImpl  implements AppReportMonitorService {

    @Resource
    private AppReportMonitorMapper appReportMonitorMapper;

    @Autowired
    private UserCenterClient userCenterClient;

    @Resource
    private HomePageReportMapper homePageReportMapper;

    @Autowired
    private MonitorDataReportService monitorDataReportService;


    @Override
    public List<SceneEntityVo> getSceneByCompany(String sceneTypeName, Integer companyOrgId) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        return appReportMonitorMapper.getSceneByCompany(sceneTypeName,companyOrgId,loginUser.getTenantId(),loginUser.getType(),loginUser.getPermissonType(),loginUser.getProgramItemList());
    }

    @Override
    public List<DeviceEntityVo> getDeviceByCompany(String typeName, Integer companyOrgId) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        return appReportMonitorMapper.getDeviceByCompany(typeName,companyOrgId,loginUser.getTenantId(),loginUser.getType(),loginUser.getPermissonType(),loginUser.getProgramItemList());
    }
    @Override
    public CompanySceneInfoDto getSceneByCompanyBySearch(String sceneTypeName, String condition) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        //先查询公司
        //模糊查询场景所属公司id
        List<Integer> companyIds = appReportMonitorMapper.getCompanyBySceneCondition(sceneTypeName,condition,loginUser.getTenantId(),loginUser.getType(),loginUser.getPermissonType(),loginUser.getProgramItemList());
        //根据公司id和输入条件查询公司
        List<OrgBaseTreeInfoDto> orgBaseTreeInfoDtos = userCenterClient.getCompanyByUser(condition,companyIds);
        //有公司的展示第一个公司信息
        if(orgBaseTreeInfoDtos.size() > 0){
            List<SceneEntityVo> sceneEntities = appReportMonitorMapper.getSceneByCompany(sceneTypeName,orgBaseTreeInfoDtos.get(0).getId(),loginUser.getTenantId(),loginUser.getType(),loginUser.getPermissonType(),loginUser.getProgramItemList());
            return new CompanySceneInfoDto(orgBaseTreeInfoDtos,sceneEntities,null);
        }

        return new CompanySceneInfoDto();
    }

    @Override
    public CompanySceneInfoDto getDeviceByCompanyBySearch(String typeName,String condition) {
        LoginUser loginUser = UserUtil.getCurrentUser();
        //模糊查询设备所属公司id
        List<Integer> companyIds = appReportMonitorMapper.getCompanyByDeviceCondition(condition,loginUser.getTenantId(),loginUser.getType(),loginUser.getPermissonType(),loginUser.getProgramItemList());
        //先查询公司
        List<OrgBaseTreeInfoDto> orgBaseTreeInfoDtos = userCenterClient.getCompanyByUser(condition,companyIds);
        //有公司的展示第一个公司信息
        if(orgBaseTreeInfoDtos.size() > 0) {
            List<DeviceEntityVo> deviceEntities = appReportMonitorMapper.getDeviceByCompany(typeName, orgBaseTreeInfoDtos.get(0).getId(), loginUser.getTenantId(), loginUser.getType(), loginUser.getPermissonType(), loginUser.getProgramItemList());
            return new CompanySceneInfoDto(orgBaseTreeInfoDtos, null, deviceEntities);
        }


        return new CompanySceneInfoDto();
    }

    @Override
    public List<WaterSupplyChart> waterEnergyConsumption(Integer sceneId ) {
        HomePageReportDto dto = new HomePageReportDto();
        dto.setSceneId(sceneId);
        dto.setSceneType(SceneTypeEnum.WATER_SOURCE.getMessage());
        List<WaterSupplyDataVo> dataVos = homePageReportMapper.getWaterSupplyData(dto, UserUtil.getCurrentUser().getUserCondition());
        LocalDate localDate = LocalDate.now();
        //当天数据
        BigDecimal waterDataCountDay = monitorDataReportService.getAmountCount(null, sceneId, "水源", 4, 1);
        BigDecimal powerDataCountDay = monitorDataReportService.getAmountCount(null, sceneId, "水源", 5, 1);
        WaterSupplyChart waterSupplyChartToday = new WaterSupplyChart();
        waterSupplyChartToday.setSort(localDate.getDayOfMonth());
        waterSupplyChartToday.setDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate));
        waterSupplyChartToday.setWaterData(waterDataCountDay.divide(new BigDecimal("10000"), 3, BigDecimal.ROUND_HALF_UP));
        waterSupplyChartToday.setPowerData(powerDataCountDay.divide(new BigDecimal("10000"), 3, BigDecimal.ROUND_HALF_UP));
        final int gongShuiType = 4;
        List<WaterSupplyChart> waterSupplyCharts = new ArrayList<>();
        dataVos.stream()
                .collect(Collectors.groupingBy(item -> item.getYear() + "-" + item.getMonth() + "-" + item.getDay()))
                .forEach((key, value) -> {
                    WaterSupplyChart waterSupplyChart = new WaterSupplyChart();
                    waterSupplyChart.setDate(key);
                    value.stream().forEach(waterSupplyData -> {
                        waterSupplyChart.setSort(waterSupplyData.getDay());
                         // 供水
                        if (waterSupplyData.getParmType() == gongShuiType && waterSupplyData.getAmount() != null) {
                            waterSupplyChart.setWaterData(waterSupplyData.getAmount().divide(new BigDecimal("10000"), 3, BigDecimal.ROUND_HALF_UP));

                        }  //电耗
                        else if (waterSupplyData.getParmType() == DeviceParamTypeEnum.KWH.getCode() && waterSupplyData.getAmount() != null) {
                            waterSupplyChart.setPowerData(waterSupplyData.getAmount().divide(new BigDecimal("10000"), 3, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    waterSupplyCharts.add(waterSupplyChart);
                });

        waterSupplyCharts.sort(Comparator.comparing(WaterSupplyChart::getSort));
        convertWaterSupplyCharts(localDate, waterSupplyCharts, waterSupplyChartToday);
        return waterSupplyCharts;
    }

    @Override
    public List<WaterSupplyChart> getWaterLevelForWaterSource(Integer sceneId ){
        HomePageReportDto dto = new HomePageReportDto();
        dto.setSceneId(sceneId);
        dto.setSceneType(SceneTypeEnum.WATER_SOURCE.getMessage());
        List<WaterSupplyDataVo> dataVos = homePageReportMapper.getWaterSupplyData(dto, UserUtil.getCurrentUser().getUserCondition());
        LocalDate localDate = LocalDate.now();
        //当天数据
        BigDecimal waterDataCountDay = monitorDataReportService.getAmountCount(null,sceneId, "水源", 12,1 );
        WaterSupplyChart waterSupplyChartToday = new WaterSupplyChart();
        waterSupplyChartToday.setSort(localDate.getDayOfMonth());
        waterSupplyChartToday.setDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate));
        waterSupplyChartToday.setWaterData(waterDataCountDay);
        final int shuiWei = 12;
        List<WaterSupplyChart> waterSupplyCharts = new ArrayList<>();
        dataVos.stream()
                .collect(Collectors.groupingBy(item -> item.getYear() + "-" + item.getMonth() + "-" + item.getDay()))
                .forEach((key, value) -> {
                    WaterSupplyChart waterSupplyChart = new WaterSupplyChart();
                    waterSupplyChart.setDate(key);
                    value.stream().forEach(waterSupplyData -> {
                        waterSupplyChart.setSort(waterSupplyData.getDay());
                        // 水位
                        if (waterSupplyData.getParmType() == shuiWei)  {
                            waterSupplyChart.setWaterData(waterSupplyData.getAmount());
                        }
                    });
                    waterSupplyCharts.add(waterSupplyChart);
                });

        waterSupplyCharts.sort(Comparator.comparing(WaterSupplyChart::getSort));
        convertWaterSupplyCharts(localDate, waterSupplyCharts, waterSupplyChartToday);
        return waterSupplyCharts;
    }

    private void convertWaterSupplyCharts (LocalDate localDate, List<WaterSupplyChart> waterSupplyCharts, WaterSupplyChart waterSupplyChartToday){
        Integer maxDay =  LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
        for(int i = 0;i < maxDay; i++) {
            if (i + 1 == localDate.getDayOfMonth()){
                waterSupplyCharts.add(i,waterSupplyChartToday);
            }else if (i == waterSupplyCharts.size() || !waterSupplyCharts.get(i).getSort().equals(i+1)){
                waterSupplyCharts.add(i,new WaterSupplyChart(i+1, localDate.getYear()+"-"+localDate.getMonthValue()+"-"+(i+1)));
            }
        }
    }

}
