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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
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.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
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.JpStationMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IJpStationService;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.DayGenerateMapper;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.MonthGenerateMapper;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.MonthPowerMapper;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.YearGenerateMapper;
import org.apache.activemq.util.MapHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 第三方场站服务实现类
 *
 * @author system_generator
 * @date 2023-09-19
 */
@Service
public class JpStationServiceImpl extends BaseService<JpStationDto, JpStation, JpStationMapper> implements IJpStationService {

    @Autowired
    JpStationMapper jpStationMapper;
    @Autowired
    JpInverterMapper jpInverterMapper;
    @Autowired
    JpCollectorMapper jpCollectorMapper;
    @Autowired
    MonthPowerMapper monthPowerMapper;
    @Autowired
    MonthPowerServiceImpl monthPowerServiceImpl;


    @Autowired
    DayGenerateMapper dayGenerateMapper;
    @Autowired
    MonthGenerateMapper monthGenerateMapper;
    @Autowired
    YearGenerateMapper yearGenerateMapper;

    private static double FDL = 0.001;
    private static int FD = 1000;

    /**
     * 分页查询
     */
    public Page<JpStationDto> queryForJpStationPage(int pageNum, int pageSize, JpStationDto reviewDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<JpStationDto> list = jpStationMapper.queryForDealerReviewPage(reviewDto);
        PageInfo<JpStationDto> page = new PageInfo(list);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(pageSize);
        pagenew.setRecords(page.getList());
        return pagenew;
    }

    @Async
    public void getMonthPower() {
        monthPowerServiceImpl.getMonthPower();
    }


    /**
     * 分页查询
     */

    public Page<JpStationDto> queryForJpStationPagenew(int pageNum, int pageSize, JpStationDto reviewDto) {
        Page<JpStationDto> pageNew = new Page<>(pageNum, pageSize);
//        com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto>();
        PageHelper.startPage(pageNum, pageSize);
        List<JpStationDto> list = jpStationMapper.queryForDealerReviewPagenew(reviewDto);
        PageInfo<JpStationDto> page = new PageInfo(list);
        pageNew.setCurrent(pageNum);
        pageNew.setTotal(page.getTotal());
        pageNew.setSize(pageSize);
        pageNew.setRecords(page.getList());
        return pageNew;
    }

    @Override
    public Map<String, List<Object>> getPowerqx(String date, String type, List<String> statioId) {
        List<PowerCurveDto> data = null;
        List<Object> listx = new ArrayList<>();
        List<Object> listy = new ArrayList<>();
        Map<String, List<Object>> map = new HashMap<>();
        try {

            if(type.equals("day")){
                map= gethourList();
                data =monthPowerMapper.getDayPowercount(date, statioId,null);
            }else if(type.equals("month")){
                map= getDayListOfMonth(date);
                data=monthPowerMapper.getMonthPower(date, statioId);

            }else if(type.equals("year")){
                map= getyearListOfMonth(date);
                data= monthPowerMapper.getYearPower(date,statioId);
            }else{
                map= getyearList();
                data= monthPowerMapper.getAllPower(date, statioId);
            }

            listx = map.get("x");
            listy = map.get("y");
            if (data != null && !data.isEmpty()) {
                for (PowerCurveDto datum : data) {
                    for (int i = 0; i < listx.size(); i++) {
                        if (datum.getDate().equals(listx.get(i).toString())) {
                            listy.remove(i);
                            String format = datum.getNum() != null ? new DecimalFormat("0.000").format(datum.getNum()) : null;
                            listy.add(i, format);
                            break;
                        }
                    }
                }
            }


            if (type.equals("month") || type.equals("year")) {

                listx = listx.stream().map(e -> String.valueOf(e).substring(String.valueOf(e).length() - 2)).collect(Collectors.toList());

            }

            map.put("x", listx);
            map.put("y", listy);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("系统异常！");
        }

        return map;
    }

    @Override
    @UserLimits
    public Map<String, Object> getcount(JpStationDto reviewDto) {
        return jpStationMapper.getcount(reviewDto);
    }

    @Override
    @UserLimits
    public List<Map<String, Object>> getcountState(JpStationDto reviewDto) {
        return jpStationMapper.getcountState(reviewDto);
    }

    @Override
    @UserLimits
    public Map<String, Object> getcountStatetc(JpStationDto reviewDto) {
        return jpStationMapper.getcountStatetc(reviewDto);
    }


    public List<JpStation> getJpStationList(JpStationDto reviewDto) {
        List<JpInverter> dataJpInverter = jpInverterMapper.selectList(new QueryWrapper<JpInverter>().isNotNull("third_station_id").isNotNull("sn_code"));
        Map<String, List<String>> inverterMap = dataJpInverter.stream().collect(Collectors.groupingBy(JpInverter::getThirdStationId, Collectors.mapping(JpInverter::getSnCode, Collectors.toList())));
        List<JpStation> list = jpStationMapper.getJpStationList(reviewDto);
        list.forEach(jpStation -> {

            if(inverterMap.containsKey(jpStation.getThirdStationId())){

                List<String> sncodes =inverterMap.get(jpStation.getThirdStationId())!=null?inverterMap.get(jpStation.getThirdStationId()).stream().distinct().collect(Collectors.toList()):null;
                sncodes = sncodes!=null?sncodes.stream().filter(s->s.trim().length()>1).collect(Collectors.toList()):null;
                jpStation.setSnCodes(sncodes);

            }



        });
        list =list.stream().filter(jpStation -> jpStation.getSnCodes()!=null&&jpStation.getSnCodes().size()>0).collect(Collectors.toList());
        return list;
    }

    @Override
    @UserLimits
    public Map<String, Object> getcountStatejs(JpStationDto reviewDto) {
        return jpStationMapper.getcountStatejs(reviewDto);
    }

    @Override
    @UserLimits
    public Map<String, Object> getcountStatejr(JpStationDto reviewDto) {
        return jpStationMapper.getcountStatejr(reviewDto);
    }

    @Override
    @UserLimits
    public List<JpStation> getJpStation(JpStationDto reviewDto) {
        return jpStationMapper.getJpStation(reviewDto);
    }

    @Override
    @UserLimits
    public Map<String, List<Object>> getGenerateqx(String date, String type, JpStationDto reviewDto) {

//        List<String> statioId=new ArrayList();
//        List<JpStation> dataJpStation=jpStationMapper.getJpStation(reviewDto);
//        for (JpStation jpStation : dataJpStation) {
//            statioId.add(jpStation.getThirdStationId());
//        }

        List<PowerCurveDto> data = null;
        List<Object> listx = new ArrayList<>();
        List<Object> listy = new ArrayList<>();
        Map<String, List<Object>> map = new HashMap<>();
        Map<String, List<Object>> map1 = new HashMap<>();
        try {

            if(type.equals("month")){
                map= getDayListOfMonth(reviewDto.getTimeDateMonth());
//                if(statioId!=null&&!statioId.isEmpty()) {

                    data = dayGenerateMapper.getDayGeneratqx(reviewDto.getTimeDateMonth(),reviewDto.getRegionalCompaniesCode(), reviewDto.getAmosCompanyCode(), reviewDto.getStationType(),reviewDto.getThirdStationId(), null);
//                }
            }else if(type.equals("year")){
                map= getyearListOfMonth(reviewDto.getTimeDateYear());
//                if(statioId!=null&&!statioId.isEmpty()) {
                    data = dayGenerateMapper.getMonthGenerateqx(reviewDto.getTimeDateYear(),reviewDto.getRegionalCompaniesCode(), reviewDto.getAmosCompanyCode(), reviewDto.getStationType(),reviewDto.getThirdStationId(), null);
//                }
            }else{
                map= getyearList();
//                if(statioId!=null&&!statioId.isEmpty()) {
                    data = dayGenerateMapper.getYearGenerateqx(null,reviewDto.getRegionalCompaniesCode(), reviewDto.getAmosCompanyCode(), reviewDto.getStationType(),reviewDto.getThirdStationId(), null);
//                }
            }
            listx = map.get("x");
            listy = map.get("y");
            if (data != null && !data.isEmpty()) {
                for (PowerCurveDto datum : data) {
                    for (int i = 0; i < listx.size(); i++) {
                        if (datum.getDate().equals(listx.get(i).toString())) {
                            listy.remove(i);
                            String format = datum.getNum() != null ? new DecimalFormat("0.000").format(datum.getNum() * FDL) : null;
                            listy.add(i, format);
                            break;
                        }
                    }
                }
            }
            if (type.equals("month") || type.equals("year")) {

                listx = listx.stream().map(e -> String.valueOf(e).substring(String.valueOf(e).length() - 2)).collect(Collectors.toList());
            }
            map1.put("axisData", listx);
            map1.put("seriesData", listy);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("系统异常！");
        }

        return map1;
    }

    @Override
    @UserLimits
    public Map<String, List<Object>> getPowerqxnew(String date,JpStationDto reviewDto) {
         date = DateUtil.format(new Date(), "yyyy-MM-dd");
     //   List<String> statioId=new ArrayList();
//        List<JpStation> dataJpStation= jpStationMapper.getJpStation(reviewDto);
//        for (JpStation jpStation : dataJpStation) {
//            statioId.add(jpStation.getThirdStationId());
//        }
        List<PowerCurveDto>  data=null;
        List<Object> listx =new  ArrayList<>();
        List<Object> listy =new ArrayList<>();
        Map<String, List<Object>> map =new HashMap<>();
        map= gethourList();
        data =monthPowerMapper.getDayPowercount(date, null,reviewDto.getThirdStationId());
        listx =map.get("x");
        listy =map.get("y");
        if(data!=null&&!data.isEmpty()){
            for (PowerCurveDto datum : data) {
                for (int i = 0; i < listx.size(); i++) {
                    if (datum.getDate().equals(listx.get(i).toString())) {
                        listy.remove(i);
                        String format = datum.getNum() != null ? new DecimalFormat("0.000").format(datum.getNum()) : null;
                        listy.add(i, format);
                        break;
                    }
                }
            }
        }
        map.put("axisData", listx);
        map.put("seriesData", listy);
        return map;
    }


    public static Map<String, List<Object>> getDayListOfMonth(String date) {
        Map<String, List<Object>> map = new HashMap<>();
        try {
            List<Object> listx = new ArrayList<>();
            List<Object> listy = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date dat = sdf.parse(date);
            Calendar aCalendar = Calendar.getInstance();
            aCalendar.setTime(dat);
            int month = aCalendar.get(Calendar.MONTH) + 1;//月份
            int day = aCalendar.getActualMaximum(Calendar.DATE);
            for (int i = 1; i <= day; i++) {
                String aDate = null;
                if (i < 10) {
                    aDate = date + "-0" + i;
                } else {
                    aDate = date + "-" + i;
                }

                listx.add(aDate);
                listy.add(null);
            }
            map.put("x", listx);
            map.put("y", listy);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("系统异常！");
        }
        return map;
    }

    public static Map<String, List<Object>> getyearListOfMonth(String date) {
        Map<String, List<Object>> map = new HashMap<>();
        List<Object> listx = new ArrayList<>();
        List<Object> listy = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String aDate = null;
            if (i < 10) {
                aDate = date + "-0" + i;
            } else {
                aDate = date + "-" + i;
            }

            listx.add(aDate);
            listy.add(null);
        }
        map.put("x", listx);
        map.put("y", listy);
        return map;
    }

    public static Map<String, List<Object>> getyearList() {
        Map<String, List<Object>> map = new HashMap<>();
        List<Object> listx = new ArrayList<>();
        List<Object> listy = new ArrayList<>();
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int year = aCalendar.get(Calendar.YEAR);//年份
        for (int i = 1; i <= 10; i++) {
            int aDate = year - (10 - i);
            listx.add(String.valueOf(aDate));
            listy.add(null);
        }
        map.put("x", listx);
        map.put("y", listy);
        return map;
    }

    public static Map<String, List<Object>> gethourList() {
        Map<String, List<Object>> map = new HashMap<>();
        List<Object> listx = new ArrayList<>();
        List<Object> listy = new ArrayList<>();
        try {
            ArrayList<String> dates = new ArrayList<String>();
            for (int i = 0; i < 24; i++) {
                String s1 = i + ":00";
                listx.add(s1);
                listy.add(null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequest("系统异常！");
        }
        map.put("x", listx);
        map.put("y", listy);
        return map;
    }


        @UserLimits
    public Page<JpStationDto> queryReport(int pageNum, int pageSize, JpStationDto reviewDto,String type)   {
        //权限
        List<String> statioId=new ArrayList();

        //查出权限下电站
        List<JpStation> dataJpStation= jpStationMapper.getJpStation(reviewDto);

        

        List<JpStationDto> list = null;
            int count=0;
            if(dataJpStation!=null&&dataJpStation.size()>0){
        switch (type){
            case"day":
                if (StringUtils.isEmpty(reviewDto.getTimeDate())){
                    reviewDto.setTimeDate(DateUtil.format(new Date(),"yyyy-MM-dd"));
                }
                LambdaQueryWrapper<DayGenerate> wapper = new LambdaQueryWrapper<DayGenerate>();
                wapper.in(reviewDto.getThirdStationId()!=null&&!reviewDto.getThirdStationId().isEmpty(),DayGenerate::getThirdStationId,reviewDto.getThirdStationIds());
                wapper.eq(reviewDto.getTimeDate()!=null&&!reviewDto.getTimeDate().equals(""),DayGenerate::getDayTime,reviewDto.getTimeDate());
               //拦截拼接权限
                count= dayGenerateMapper.selectCount(wapper);
                //拦截拼接权限
                List<DayGenerate> listday=   dayGenerateMapper.selectPagenewDayGenerate((pageNum-1)*pageSize,pageSize,reviewDto.getThirdStationIds(),reviewDto.getTimeDate(),reviewDto.getState());
                list = getJpStationDtoday(  dataJpStation,   listday);
                break;
            case"month":
                if (StringUtils.isEmpty(reviewDto.getTimeDate())){
                    reviewDto.setTimeDate(DateUtil.format(new Date(),"yyyy-MM"));
                }
                LambdaQueryWrapper<MonthGenerate> wapper1 = new LambdaQueryWrapper<MonthGenerate>();
                wapper1.in(reviewDto.getThirdStationId()!=null&&!reviewDto.getThirdStationId().isEmpty(),MonthGenerate::getThirdStationId,reviewDto.getThirdStationIds());
                wapper1.eq(reviewDto.getTimeDate()!=null&&!reviewDto.getTimeDate().equals(""),MonthGenerate::getMonthTime,reviewDto.getTimeDate());
                //拦截拼接权限
                count= monthGenerateMapper.selectCount(wapper1);
                //拦截拼接权限
               List<MonthGenerate> listmonth=   monthGenerateMapper.selectPagenewMonthGenerate((pageNum-1)*pageSize,pageSize,reviewDto.getThirdStationIds(),reviewDto.getTimeDate(),reviewDto.getState());

                list = getJpStationDtomonth(  dataJpStation,   listmonth);
                break;
            case"year":
                if (StringUtils.isEmpty(reviewDto.getTimeDate())){
                    reviewDto.setTimeDate(DateUtil.format(new Date(),"yyyy"));
                }
                LambdaQueryWrapper<YearGenerate> wapper2 = new LambdaQueryWrapper<YearGenerate>();
                wapper2.in(reviewDto.getThirdStationId()!=null&&!reviewDto.getThirdStationId().isEmpty(),YearGenerate::getThirdStationId,reviewDto.getThirdStationIds());
                wapper2.eq(reviewDto.getTimeDate()!=null&&!reviewDto.getTimeDate().equals(""),YearGenerate::getYear,reviewDto.getTimeDate());
                //拦截拼接权限
                count= yearGenerateMapper.selectCount(wapper2);
                //拦截拼接权限
                List<YearGenerate> listyear=   yearGenerateMapper.selectPagenewYearGenerate((pageNum-1)*pageSize,pageSize,reviewDto.getThirdStationIds(),reviewDto.getTimeDate(),reviewDto.getState());

                    list = getJpStationDtoyear(dataJpStation, listyear);
                    break;
                default:

                count= reviewDto.getThirdStationIds()!=null?reviewDto.getThirdStationIds().size():0;
                PageHelper.startPage(pageNum, pageSize);

                List<JpStationDto> listJ=  jpStationMapper.queryForDealerReviewPage(reviewDto);

                    list = getJpStationDtoAlldto(listJ);
            }
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(count);
        pagenew.setSize(pageSize);
        pagenew.setRecords(list);
        return pagenew;
    }
























//    @UserLimits
//    public Page<JpStationDto> queryReport(int pageNum, int pageSize, JpStationDto reviewDto,String type)   {
//        //权限
//        List<String> statioId=new ArrayList();
//
//        List<JpStation> dataJpStation= jpStationMapper.getJpStation(reviewDto);
//            if(reviewDto.getThirdStationIds()==null||reviewDto.getThirdStationIds().isEmpty()){
//                for (JpStation jpStation : dataJpStation) {
//                    statioId.add(jpStation.getThirdStationId());
//                }
//                reviewDto.setThirdStationIds(statioId);
//            }
//
//
//        List<JpStationDto> list = null;
//            int count=0;
//            if(dataJpStation!=null&&dataJpStation.size()>0){
//        switch (type){
//            case"day":
//                if (StringUtils.isEmpty(reviewDto.getTimeDate())){
//                    reviewDto.setTimeDate(DateUtil.format(new Date(),"yyyy-MM-dd"));
//                }
//                LambdaQueryWrapper<DayGenerate> wapper = new LambdaQueryWrapper<DayGenerate>();
//                wapper.in(DayGenerate::getThirdStationId,reviewDto.getThirdStationIds());
//                wapper.eq(reviewDto.getTimeDate()!=null&&!reviewDto.getTimeDate().equals(""),DayGenerate::getDayTime,reviewDto.getTimeDate());
//                count= dayGenerateMapper.selectCount(wapper);
//                List<DayGenerate> listday=   dayGenerateMapper.selectPagenewDayGenerate((pageNum-1)*pageSize,pageSize,reviewDto.getThirdStationIds(),reviewDto.getTimeDate());
//                list = getJpStationDtoday(  dataJpStation,   listday);
//                break;
//            case"month":
//                if (StringUtils.isEmpty(reviewDto.getTimeDate())){
//                    reviewDto.setTimeDate(DateUtil.format(new Date(),"yyyy-MM"));
//                }
//                LambdaQueryWrapper<MonthGenerate> wapper1 = new LambdaQueryWrapper<MonthGenerate>();
//                wapper1.in(MonthGenerate::getThirdStationId,reviewDto.getThirdStationIds());
//                wapper1.eq(reviewDto.getTimeDate()!=null&&!reviewDto.getTimeDate().equals(""),MonthGenerate::getMonthTime,reviewDto.getTimeDate());
//                count= monthGenerateMapper.selectCount(wapper1);
//                List<MonthGenerate> listmonth=   monthGenerateMapper.selectPagenewMonthGenerate((pageNum-1)*pageSize,pageSize,reviewDto.getThirdStationIds(),reviewDto.getTimeDate());
//
//                list = getJpStationDtomonth(  dataJpStation,   listmonth);
//                break;
//            case"year":
//                if (StringUtils.isEmpty(reviewDto.getTimeDate())){
//                    reviewDto.setTimeDate(DateUtil.format(new Date(),"yyyy"));
//                }
//                LambdaQueryWrapper<YearGenerate> wapper2 = new LambdaQueryWrapper<YearGenerate>();
//                wapper2.in(YearGenerate::getThirdStationId,reviewDto.getThirdStationIds());
//                wapper2.eq(reviewDto.getTimeDate()!=null&&!reviewDto.getTimeDate().equals(""),YearGenerate::getYear,reviewDto.getTimeDate());
//                count= yearGenerateMapper.selectCount(wapper2);
//                List<YearGenerate> listyear=   yearGenerateMapper.selectPagenewYearGenerate((pageNum-1)*pageSize,pageSize,reviewDto.getThirdStationIds(),reviewDto.getTimeDate());
//
//
//                list = getJpStationDtoyear(  dataJpStation,   listyear);
//                break;
//            default:
//
//                count= reviewDto.getThirdStationIds()!=null?reviewDto.getThirdStationIds().size():0;
//                PageHelper.startPage(pageNum, pageSize);
//                List<JpStationDto> listJ=  jpStationMapper.queryForDealerReviewPage(reviewDto);
//
//                list = getJpStationDtoAlldto(listJ);
//        }
//            }
//        com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<JpStationDto>();
//        pagenew.setCurrent(pageNum);
//        pagenew.setTotal(count);
//        pagenew.setSize(pageSize);
//        pagenew.setRecords(list);
//        return pagenew;
//    }






    public List<JpStationDto> getJpStationDtoAlldto( List<JpStationDto>  da){
        List<JpStationDto> ld=new ArrayList<>();
            for (JpStationDto jpStation : da) {
                    JpStationDto hd=new JpStationDto();
                    hd.setSequenceNbr(jpStation.getSequenceNbr());
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setState(jpStation.getState());
                    hd.setThirdStationId(jpStation.getThirdStationId());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower()!=null?Double.valueOf(String.format("%.3f",jpStation.getAccumulatedPower())):null);
                    hd.setFullhour(Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower()*FD/jpStation.getCapacity())));
                    hd.setCumulativeIncome(jpStation.getCumulativeIncome()!=null?Double.valueOf(String.format("%.3f",jpStation.getCumulativeIncome())):null);
                    ld.add(hd);
            }

        return ld;
    }

    public List<JpStationDto> getJpStationDtoAll(List<JpStation> da) {
        List<JpStationDto> ld = new ArrayList<>();


        for (JpStation jpStation : da) {
            JpStationDto hd = new JpStationDto();
            hd.setSequenceNbr(jpStation.getSequenceNbr());
            hd.setCode(jpStation.getCode());
            hd.setName(jpStation.getName());
            hd.setUserName(jpStation.getUserName());
            hd.setStationContact(jpStation.getStationContact());
            hd.setState(jpStation.getState());
            hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);
            hd.setFullhour(Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() / jpStation.getCapacity())));

            hd.setCumulativeIncome(jpStation.getCumulativeIncome() != null ? Double.valueOf(String.format("%.3f", jpStation.getCumulativeIncome())) : null);
            ld.add(hd);
        }

        return ld;
    }

    public List<JpStationDto> getJpStationDtoday(List<JpStation> da, List<DayGenerate> listday) {
        List<JpStationDto> ld = new ArrayList<>();
        for (DayGenerate dayGenerate : listday) {
            JpStationDto hd = new JpStationDto();
            for (JpStation jpStation : da) {
                if (jpStation.getThirdStationId().equals(dayGenerate.getThirdStationId())) {
                    hd.setSequenceNbr(jpStation.getSequenceNbr());
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setState(jpStation.getState());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);
                    hd.setThirdStationId(jpStation.getThirdStationId());
                    hd.setFullhour(dayGenerate.getFullhour() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getFullhour())) : null);
                    hd.setDayGenerate(dayGenerate.getGenerate() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getGenerate())) : null);
                    hd.setTimeDate(dayGenerate.getDayTime());
                    hd.setDayIncome(dayGenerate.getIncome() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getIncome())) : null);
                    break;
                }
            }
            ld.add(hd);
        }
        return ld;
    }

    public List<JpStationDto> getJpStationDtomonth(List<JpStation> da, List<MonthGenerate> listmonth) {
        List<JpStationDto> ld = new ArrayList<>();
        for (MonthGenerate dayGenerate : listmonth) {
            JpStationDto hd = new JpStationDto();
            for (JpStation jpStation : da) {
                if (jpStation.getThirdStationId().equals(dayGenerate.getThirdStationId())) {
                    hd.setSequenceNbr(jpStation.getSequenceNbr());
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setState(jpStation.getState());
                    hd.setThirdStationId(jpStation.getThirdStationId());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);
                    hd.setMonthGenerate(dayGenerate.getGenerate() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getGenerate())) : null);
                    hd.setMonthIncome(dayGenerate.getIncome() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getIncome())) : null);
                    hd.setTimeDate(dayGenerate.getMonthTime());
                    hd.setFullhour(dayGenerate.getFullhour() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getFullhour())) : null);
                    break;
                }
            }
            ld.add(hd);
        }
        return ld;
    }

    public List<JpStationDto> getJpStationDtoyear(List<JpStation> da, List<YearGenerate> listyear) {
        List<JpStationDto> ld = new ArrayList<>();
        for (YearGenerate dayGenerate : listyear) {
            JpStationDto hd = new JpStationDto();
            for (JpStation jpStation : da) {
                if (jpStation.getThirdStationId().equals(dayGenerate.getThirdStationId())) {
                    hd.setSequenceNbr(jpStation.getSequenceNbr());
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setState(jpStation.getState());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);

                    hd.setThirdStationId(jpStation.getThirdStationId());
                    hd.setFullhour(dayGenerate.getFullhour() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getFullhour())) : null);
                    hd.setYearGenerate(dayGenerate.getGenerate() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getGenerate())) : null);
                    hd.setYearIncome(dayGenerate.getIncome() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getIncome())) : null);
                    hd.setTimeDate(dayGenerate.getYearTime());
                    break;
                }
            }
            ld.add(hd);
        }
        return ld;
    }



    @UserLimits
    public List<JpStationDto> selectReportDate(JpStationDto reviewDto, String type, HttpServletResponse response) {
        //权限
        //权限
        List<String> statioId=new ArrayList();

        List<JpStation> dataJpStation= jpStationMapper.getJpStation(reviewDto);



        List<JpStationDto> list = null;
        try {
            if (dataJpStation != null && dataJpStation.size() > 0) {
                switch (type) {
                    case "day":
                        LambdaQueryWrapper<DayGenerate> wapper = new LambdaQueryWrapper<DayGenerate>();
                        wapper.in(reviewDto.getThirdStationId()!=null&&!reviewDto.getThirdStationId().isEmpty(),DayGenerate::getThirdStationId, reviewDto.getThirdStationIds());
                        wapper.eq(reviewDto.getTimeDate() != null&&!reviewDto.getTimeDate().equals(""), DayGenerate::getDayTime, reviewDto.getTimeDate());
                        wapper.eq(reviewDto.getState() != null&&!reviewDto.getState().equals(""), DayGenerate::getStationState, reviewDto.getState());

                        List<DayGenerate> listday = dayGenerateMapper.selectList(wapper);
                        List<DayGenerateEX> listne = getJpStationDtodaynew(dataJpStation, listday);
                        setResponseHeadForDowload(response, "电站日报表.xls");
                        EasyExcel.write(response.getOutputStream()).head(DayGenerateEX.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")

                                .doWrite(listne);
                        break;
                    case "month":
                        LambdaQueryWrapper<MonthGenerate> wapper1 = new LambdaQueryWrapper<MonthGenerate>();
                        wapper1.in(reviewDto.getThirdStationId()!=null&&!reviewDto.getThirdStationId().isEmpty(),MonthGenerate::getThirdStationId, reviewDto.getThirdStationIds());
                        wapper1.eq(reviewDto.getTimeDate() != null&&!reviewDto.getTimeDate().equals(""), MonthGenerate::getMonthTime, reviewDto.getTimeDate());
                        wapper1.eq(reviewDto.getState() != null&&!reviewDto.getState().equals(""), MonthGenerate::getStationState, reviewDto.getState());

                        List<MonthGenerate> listmonth = monthGenerateMapper.selectList(wapper1);
                        List<MonthGenerateEX> lo = getJpStationDtomonthnew(dataJpStation, listmonth);
                        setResponseHeadForDowload(response, "电站月报表.xls");
                        EasyExcel.write(response.getOutputStream()).head(MonthGenerateEX.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")

                                .doWrite(lo);
                        break;
                    case "year":
                        LambdaQueryWrapper<YearGenerate> wapper2 = new LambdaQueryWrapper<YearGenerate>();
                        wapper2.in(reviewDto.getThirdStationId()!=null&&!reviewDto.getThirdStationId().isEmpty(),YearGenerate::getThirdStationId, reviewDto.getThirdStationIds());
                        wapper2.eq(reviewDto.getTimeDate() != null&&!reviewDto.getTimeDate().equals(""), YearGenerate::getYear, reviewDto.getTimeDate());
                        wapper2.eq(reviewDto.getState() != null&&!reviewDto.getState().equals(""), YearGenerate::getStationState, reviewDto.getState());

                        List<YearGenerate> listyear = yearGenerateMapper.selectList(wapper2);
                        List<YearGenerateEX> listy = getJpStationDtoyearnew(dataJpStation, listyear);
                        setResponseHeadForDowload(response, "电站年报表.xls");
                        EasyExcel.write(response.getOutputStream()).head(YearGenerateEX.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")

                                .doWrite(listy);
                        break;
                    default:
                        list = getJpStationDtoAll(dataJpStation);
                        setResponseHeadForDowload(response, "电站累计报表.xls");
                        EasyExcel.write(response.getOutputStream()).head(JpStationDto.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")

                                .doWrite(list);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }


//    @UserLimits
//    public List<JpStationDto> selectReportDate(JpStationDto reviewDto,String type,HttpServletResponse response) {
//        //权限
//        //权限
//        List<String> statioId=new ArrayList();
////        if(reviewDto.getThirdStationIds()!=null){
////            List<String>   dd= reviewDto.getThirdStationIds()!=null? JSON.parseArray(reviewDto.getThirdStationIds().get(0),String.class):null;
////            reviewDto.setThirdStationIds(dd);
////        }
//        List<JpStation> dataJpStation= jpStationMapper.getJpStation(reviewDto);
//        if(reviewDto.getThirdStationIds()==null||reviewDto.getThirdStationIds().isEmpty()){
//            for (JpStation jpStation : dataJpStation) {
//                statioId.add(jpStation.getThirdStationId());
//            }
//            reviewDto.setThirdStationIds(statioId);
//        }
//
//
//        List<JpStationDto> list = null;
//        try {
//            if(dataJpStation!=null&&dataJpStation.size()>0) {
//                switch (type) {
//                    case "day":
//                        LambdaQueryWrapper<DayGenerate> wapper = new LambdaQueryWrapper<DayGenerate>();
//                        wapper.in(DayGenerate::getThirdStationId, reviewDto.getThirdStationIds());
//                        wapper.eq(reviewDto.getTimeDate() != null&&!reviewDto.getTimeDate().equals(""), DayGenerate::getDayTime, reviewDto.getTimeDate());
//
//                        List<DayGenerate> listday = dayGenerateMapper.selectList(wapper);
//                        List<DayGenerateEX> listne = getJpStationDtodaynew(dataJpStation, listday);
//                        setResponseHeadForDowload(response, "电站日报表.xls");
//                        EasyExcel.write(response.getOutputStream()).head(DayGenerateEX.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")
//
//                                .doWrite(listne);
//                        break;
//                    case "month":
//                        LambdaQueryWrapper<MonthGenerate> wapper1 = new LambdaQueryWrapper<MonthGenerate>();
//                        wapper1.in(MonthGenerate::getThirdStationId, reviewDto.getThirdStationIds());
//                        wapper1.eq(reviewDto.getTimeDate() != null&&!reviewDto.getTimeDate().equals(""), MonthGenerate::getMonthTime, reviewDto.getTimeDate());
//
//                        List<MonthGenerate> listmonth = monthGenerateMapper.selectList(wapper1);
//                        List<MonthGenerateEX> lo = getJpStationDtomonthnew(dataJpStation, listmonth);
//                        setResponseHeadForDowload(response, "电站月报表.xls");
//                        EasyExcel.write(response.getOutputStream()).head(MonthGenerateEX.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")
//
//                                .doWrite(lo);
//                        break;
//                    case "year":
//                        LambdaQueryWrapper<YearGenerate> wapper2 = new LambdaQueryWrapper<YearGenerate>();
//                        wapper2.in(YearGenerate::getThirdStationId, reviewDto.getThirdStationIds());
//                        wapper2.eq(reviewDto.getTimeDate() != null&&!reviewDto.getTimeDate().equals(""), YearGenerate::getYear, reviewDto.getTimeDate());
//                        List<YearGenerate> listyear = yearGenerateMapper.selectList(wapper2);
//                        List<YearGenerateEX> listy = getJpStationDtoyearnew(dataJpStation, listyear);
//                        setResponseHeadForDowload(response, "电站年报表.xls");
//                        EasyExcel.write(response.getOutputStream()).head(YearGenerateEX.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")
//
//                                .doWrite(listy);
//                        break;
//                    default:
//                        list = getJpStationDtoAll(dataJpStation);
//                        setResponseHeadForDowload(response, "电站累计报表.xls");
//                        EasyExcel.write(response.getOutputStream()).head(JpStationDto.class).excelType(ExcelTypeEnum.XLS).sheet("电站报表")
//
//                                .doWrite(list);
//                }
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return list;
//    }

    public List<DayGenerateEX> getJpStationDtodaynew( List<JpStation>  da,  List<DayGenerate> listday){
        List<DayGenerateEX> ld=new ArrayList<>();
        for (DayGenerate dayGenerate : listday) {
            DayGenerateEX hd = new DayGenerateEX();
            for (JpStation jpStation : da) {
                if (jpStation.getThirdStationId().equals(dayGenerate.getThirdStationId())) {
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setState(jpStation.getState());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);

                    hd.setFullhour(dayGenerate.getFullhour() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getFullhour())) : null);
                    hd.setDayGenerate(dayGenerate.getGenerate() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getGenerate())) : null);
                    hd.setTimeDate(dayGenerate.getDayTime());
                    hd.setDayIncome(dayGenerate.getIncome() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getIncome())) : null);
                    break;
                }
            }
            ld.add(hd);
        }
        return ld;
    }

    public List<MonthGenerateEX> getJpStationDtomonthnew(List<JpStation> da, List<MonthGenerate> listmonth) {
        List<MonthGenerateEX> ld = new ArrayList<>();
        for (MonthGenerate dayGenerate : listmonth) {
            MonthGenerateEX hd = new MonthGenerateEX();
            for (JpStation jpStation : da) {
                if (jpStation.getThirdStationId().equals(dayGenerate.getThirdStationId())) {
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);
                    hd.setMonthGenerate(dayGenerate.getGenerate() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getGenerate())) : null);
                    hd.setMonthIncome(dayGenerate.getIncome() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getIncome())) : null);
                    hd.setTimeDate(dayGenerate.getMonthTime());
                    hd.setFullhour(dayGenerate.getFullhour() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getFullhour())) : null);
                    break;
                }
            }
            ld.add(hd);
        }
        return ld;
    }

    public List<YearGenerateEX> getJpStationDtoyearnew(List<JpStation> da, List<YearGenerate> listyear) {
        List<YearGenerateEX> ld = new ArrayList<>();
        for (YearGenerate dayGenerate : listyear) {
            YearGenerateEX hd = new YearGenerateEX();
            for (JpStation jpStation : da) {
                if (jpStation.getThirdStationId().equals(dayGenerate.getThirdStationId())) {
                    hd.setCode(jpStation.getCode());
                    hd.setName(jpStation.getName());
                    hd.setUserName(jpStation.getUserName());
                    hd.setStationContact(jpStation.getStationContact());
                    hd.setAccumulatedPower(jpStation.getAccumulatedPower() != null ? Double.valueOf(String.format("%.3f", jpStation.getAccumulatedPower() * FDL)) : null);

                    hd.setFullhour(dayGenerate.getFullhour() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getFullhour())) : null);
                    hd.setYearGenerate(dayGenerate.getGenerate() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getGenerate())) : null);
                    hd.setYearIncome(dayGenerate.getIncome() != null ? Double.valueOf(String.format("%.3f", dayGenerate.getIncome())) : null);
                    hd.setTimeDate(dayGenerate.getYearTime());
                    break;
                }
            }
            ld.add(hd);
        }
        return ld;
    }


    public void setResponseHeadForDowload(HttpServletResponse response, String dowloadFileName) {

        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(dowloadFileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


//    @Override
//    public Page<PowerStationStatistics> getRegionStatistics(Integer current, Integer size, String regionName) {
//
//
//        PageHelper.startPage(current, size);
//        List<PowerStationStatistics> regionPage = jpStationMapper.getRegionPage(regionName);
//        PageInfo<PowerStationStatistics> page = new PageInfo(regionPage);
//        Page<PowerStationStatistics> pagenew = new Page<PowerStationStatistics>();
//
//        List<PowerStationStatistics> resultPage = new ArrayList<>();
//        page.getList().stream().forEach(powerStationStatistics -> {
//            PowerStationStatistics regionStatistics = jpStationMapper.getRegionStatistics(powerStationStatistics.getCode(),null);
//            regionStatistics.setName(powerStationStatistics.getName());
//            regionStatistics.setCode(powerStationStatistics.getCode());
//            resultPage.add(regionStatistics);
//        });
//
//        pagenew.setCurrent(current);
//        pagenew.setTotal(page.getTotal());
//        pagenew.setSize(size);
//        pagenew.setRecords(resultPage);
//
//
//        return pagenew;
//    }

//    @Override
//    public Page<PowerStationStatistics> getDealerStatistics(Integer current, Integer size, String regionalCompaniesCode, String dealerName) {
//        PageHelper.startPage(current, size);
////        根据区域公司orgCode查询区域公司下自己的经销商
//        List<PowerStationStatistics> dealerPage = jpStationMapper.getDealerPage(regionalCompaniesCode, dealerName);
//        PageInfo<PowerStationStatistics> page = new PageInfo(dealerPage);
//        Page<PowerStationStatistics> pagenew = new Page<PowerStationStatistics>();
//
//        List<PowerStationStatistics> resultPage = new ArrayList<>();
//        page.getList().stream().forEach(powerStationStatistics -> {
//            PowerStationStatistics regionStatistics = jpStationMapper.getRegionStatistics(null,powerStationStatistics.getCode());
//            regionStatistics.setName(powerStationStatistics.getName());
//            regionStatistics.setCode(powerStationStatistics.getCode());
//            resultPage.add(regionStatistics);
//        });
//
//        pagenew.setCurrent(current);
//        pagenew.setTotal(page.getTotal());
//        pagenew.setSize(size);
//        pagenew.setRecords(resultPage);
//
//        return pagenew;
//
//
//    }

    public List<JpStationDto> queryAllPowerStation(String regionalCompaniesCode, String amosCompanyCode, String thirdStationId, String type) {
        List<JpStationDto> powerStationList =  jpStationMapper.queryAllPowerStation(regionalCompaniesCode, amosCompanyCode, thirdStationId, type);
        return powerStationList;
    }

    public Map<String,Object> selectStateCount(String regionalCompaniesCode, String amosCompanyCode, String type){
        Map<String, Object> resultNumMap = new HashMap<>();
        List<Map<String, Object>> map = jpStationMapper.selectStateCount(regionalCompaniesCode, amosCompanyCode, type);
        map.forEach(e->{
            if (e.get("status").equals("在线")){
                resultNumMap.put("online",(Integer.valueOf(e.get("count").toString())));
            }else if (e.get("status").equals("报警")){
                resultNumMap.put("warn",(Integer.valueOf(e.get("count").toString())));
            }else {
                resultNumMap.put("offline",(Integer.valueOf(e.get("count").toString())));
            }
        });
        return resultNumMap;
    }

    public  Map<String,Object> queryEquipInfo(String thirdStationId ){
        LambdaQueryWrapper<JpInverter> inverQuery = new LambdaQueryWrapper<>();
        inverQuery.eq(JpInverter::getThirdStationId,thirdStationId);
        List<JpInverter> jpInverters = jpInverterMapper.selectList(inverQuery);

        LambdaQueryWrapper<JpCollector> collectorQuery = new LambdaQueryWrapper<>();
        collectorQuery.eq(JpCollector::getThirdStationId,thirdStationId);
        List<JpCollector> jpCollectors = jpCollectorMapper.selectList(collectorQuery);

        Map<String, Object> map = MapBuilder.<String, Object>create().put("inverter", jpInverters).put("collector", jpCollectors).put("ammeter",new ArrayList<>()).put("meteorograph",new ArrayList<>()).build();
        return map;

    }



}