package com.zcxk.service.impl;

import com.zcxk.client.UserCenterClient;
import com.zcxk.dao.AppReportMonitorMapper;
import com.zcxk.dao.HomePageReportMapper;
import com.zcxk.dto.CompanySceneInfoDto;
import com.zcxk.dto.OrgBaseTreeInfoDto;
import com.zcxk.dto.generalView.WaterSupplyChart;
import com.zcxk.dto.generalView.WaterSupplyData;
import com.zcxk.entity.DeviceEntity;
import com.zcxk.entity.SceneEntity;
import com.zcxk.model.LoginUser;
import com.zcxk.service.AppReportMonitorService;
import com.zcxk.service.MonitorDataReportService;
import com.zcxk.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
 * @auto 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<SceneEntity> 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<DeviceEntity> 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<SceneEntity> 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<DeviceEntity> 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 ) {

        LoginUser loginUser = UserUtil.getCurrentUser();
        String tenantId = loginUser.getTenantId();

        List<WaterSupplyData> waterSupplyDatas = homePageReportMapper.getWaterSupplyData(sceneId, "水源", tenantId, loginUser.getType(), loginUser.getPermissonType(), loginUser.getProgramItemList());

        LocalDate localDate = LocalDate.now();
        //当天数据
        BigDecimal waterDataCountDay = monitorDataReportService.getAmountCount(null, sceneId, "水源", 4, 1);
        BigDecimal powerDataCountDay = monitorDataReportService.getAmountCount(null, sceneId, "水源", 5, 1);
//        BigDecimal drugDataCountDay = monitorDataReportService.getAmountCount(null,sceneId, sceneType, 6,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));
//        waterSupplyChartToday.setDrugData(drugDataCountDay);


        List<WaterSupplyChart> waterSupplyCharts = new ArrayList<>();
        waterSupplyDatas.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() == 4 && waterSupplyData.getAmount() != null) { //供水
                            waterSupplyChart.setWaterData(waterSupplyData.getAmount().divide(new BigDecimal("10000"), 3, BigDecimal.ROUND_HALF_UP));
                        } else if (waterSupplyData.getParmType() == 5 && waterSupplyData.getAmount() != null) {//电耗
                            waterSupplyChart.setPowerData(waterSupplyData.getAmount().divide(new BigDecimal("10000"), 3, BigDecimal.ROUND_HALF_UP));
                        }
//                        else if (waterSupplyData.getParmType() == 6) {//药耗
//                            waterSupplyChart.setDrugData(waterSupplyData.getAmount());
//                        }
                    });
                    waterSupplyCharts.add(waterSupplyChart);
                });

        waterSupplyCharts.sort(Comparator.comparing(WaterSupplyChart::getSort));

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

        }
//        waterSupplyCharts.sort(Comparator.comparing(WaterSupplyChart::getSort).reversed());
        return waterSupplyCharts;
    }

    public List<WaterSupplyChart> getWaterLevelForWaterSource(Integer sceneId ){
        LoginUser loginUser = UserUtil.getCurrentUser();
        String tenantId = loginUser.getTenantId();

        List<WaterSupplyData> waterSupplyDatas = homePageReportMapper.getWaterSupplyData(sceneId,"水源",tenantId,loginUser.getType(),loginUser.getPermissonType(),loginUser.getProgramItemList());

        LocalDate localDate = LocalDate.now();
        //当天数据
        BigDecimal waterDataCountDay = monitorDataReportService.getAmountCount(null,sceneId, "水源", 12,1 );
//        BigDecimal drugDataCountDay = monitorDataReportService.getAmountCount(null,sceneId, sceneType, 6,1 );
        WaterSupplyChart waterSupplyChartToday = new WaterSupplyChart();
        waterSupplyChartToday.setSort(localDate.getDayOfMonth());
        waterSupplyChartToday.setDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate));
        waterSupplyChartToday.setWaterData(waterDataCountDay);



        List<WaterSupplyChart> waterSupplyCharts = new ArrayList<>();
        waterSupplyDatas.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() == 12) { //水位
                            waterSupplyChart.setWaterData(waterSupplyData.getAmount());
                        }
                    });
                    waterSupplyCharts.add(waterSupplyChart);
                });

        waterSupplyCharts.sort(Comparator.comparing(WaterSupplyChart::getSort));

        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)));
            }
        }
        return waterSupplyCharts;
    }


}
