package com.gyee.runeconomy.service.auto.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.common.model.StringUtils;
import com.gyee.common.util.DateUtils;
import com.gyee.common.vo.healthmanager.CompareVo;
import com.gyee.runeconomy.init.CacheContext;
import com.gyee.runeconomy.mapper.auto.ProEconEquipmentInfoDayTopMapper;
import com.gyee.runeconomy.model.auto.ProBasicPowerstation;
import com.gyee.runeconomy.model.auto.ProEconEquipmentInfoDayTop;
import com.gyee.runeconomy.model.auto.TurbineInfoDay;
import com.gyee.runeconomy.service.TokenService;
import com.gyee.runeconomy.service.auto.IProEconEquipmentInfoDayTopService;
import com.gyee.runeconomy.service.auto.ITurbineInfoDayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Year;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 风机日信息表排行 服务实现类
 * </p>
 *
 * @author shilin
 * @since 2022-11-09
 */
@Service
public class ProEconEquipmentInfoDayTopServiceImpl extends ServiceImpl<ProEconEquipmentInfoDayTopMapper, ProEconEquipmentInfoDayTop> implements IProEconEquipmentInfoDayTopService {


    @Resource
    private TokenService tokenService;
    @Resource
    private ProEconEquipmentInfoDayTopMapper proEconEquipmentInfoDayTopMapper;
    @Resource
    private ITurbineInfoDayService turbineInfoDayService;

    @Override
    public IPage<ProEconEquipmentInfoDayTop> getEquipmentInfoDayTopList(String companyId, String windpowerstationId, Integer types, String staType, String date, Integer pageNum, Integer pageSize) {

        IPage<TurbineInfoDay> andList = getTopAndList(windpowerstationId, date, pageNum, pageSize);
        IPage<ProEconEquipmentInfoDayTop> resultPage = getEquipmentInfoDayTopList_bf(companyId, windpowerstationId, types, staType, date, pageNum, pageSize);
        resultPage.setRecords(turbs2equipmentidt(resultPage.getRecords(),andList.getRecords()));
        return resultPage;
    }

    private List<ProEconEquipmentInfoDayTop> turbs2equipmentidt(List<ProEconEquipmentInfoDayTop> peeidtRecords, List<TurbineInfoDay> tidRecords) {
        if (peeidtRecords == null || peeidtRecords.isEmpty() || tidRecords == null || tidRecords.isEmpty()) return Collections.emptyList();
        Map<String, TurbineInfoDay> dayMap = tidRecords.stream().collect(Collectors.toMap(TurbineInfoDay::getTurbineId, Function.identity()));
        peeidtRecords.forEach(peeidt->{
            TurbineInfoDay day = dayMap.get(peeidt.getWindturbineId());
            peeidt.setDayfdl(NumberUtil.round(day.getRfdl(),2).doubleValue());
            peeidt.setDayllfdl(NumberUtil.round(day.getLlfdl(),2).doubleValue());
            peeidt.setDayfs(NumberUtil.round(day.getPjfs(),2).doubleValue());
            peeidt.setDaygzssdl(NumberUtil.round(day.getGzss(),2).doubleValue());
            peeidt.setDayxdssdl(NumberUtil.round(day.getXdss(),2).doubleValue());
            peeidt.setDaywhssdl(NumberUtil.round(day.getFjhjxss(),2).doubleValue());
            peeidt.setDayxnssdl(NumberUtil.round(day.getXnss(),2).doubleValue());
            peeidt.setDaylyxs(NumberUtil.round(day.getLyxs(),2).doubleValue());
            peeidt.setDaysbklyl(NumberUtil.round(day.getKlyl(),2).doubleValue());
            peeidt.setDayyxfss(NumberUtil.round(day.getYxfss(),2).doubleValue());
            peeidt.setDayjfpl(NumberUtil.round(day.getJfpl(),2).doubleValue());
        });
        return peeidtRecords;
    }

    public IPage<TurbineInfoDay> getTopAndList(String windpowerstationId, String date, Integer pageNum, Integer pageSize) {
        QueryWrapper<TurbineInfoDay> qw = new QueryWrapper<>();
        qw.lambda().eq(TurbineInfoDay::getStationId, windpowerstationId)
                .eq(TurbineInfoDay::getRecordDate, DateUtils.parseDate(date)).orderByAsc(TurbineInfoDay::getTurbineId);
        IPage<TurbineInfoDay> page = new Page<>(pageNum, pageSize);
        turbineInfoDayService.page(page, qw);
        return page;
    }
    public IPage<ProEconEquipmentInfoDayTop> getEquipmentInfoDayTopList_bf(String companyId, String windpowerstationId, Integer types, String staType, String date, Integer pageNum, Integer pageSize) {

        QueryWrapper<ProEconEquipmentInfoDayTop> qw = new QueryWrapper<>();
        Page<ProEconEquipmentInfoDayTop> page = new Page<>(pageNum, pageSize);
        LocalDate today = LocalDate.now();
        Calendar calendar = Calendar.getInstance();
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        Year currentYear = Year.now();

        String str1 = null;
        String str = date;
        str1 = str.substring(0, 4);
        //        int index = str.indexOf("-");
        //        String result = str.substring(index + 1);

        int index = str.indexOf("-");
        String result;
        if (index != -1 && index + 1 < str.length() && str.charAt(index + 1) == '0') {
            result = str.substring(index + 2);
        } else {
            result = str.substring(index + 1);
        }

        List<String> wpids = new ArrayList<>();

        //        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        //        List<ProBasicPowerstation> wplist = tokenService.getWpls(request);
        List<ProBasicPowerstation> wplist = CacheContext.wpls;
        //场站模糊查询
        if (StringUtils.isNotEmpty(companyId)) {
            wplist = wplist.stream().filter(wp -> wp.getRegionId().equals(companyId) || wp.getCompanyId().equals(companyId)).collect(Collectors.toList());
        }

        if (StringUtils.isNotEmpty(staType) && !staType.equals("0")) {
            String finalType = staType.equals("-1") ? "_FDC" : "_GDC";
            wplist = wplist.stream().filter(wp -> wp.getId().indexOf(finalType) >= 0).collect(Collectors.toList());
        }

        if (StringUtils.isNotEmpty(windpowerstationId)) {
            wpids.add(windpowerstationId);
        } else {
            wpids = wplist.stream().map(ProBasicPowerstation::getId).collect(Collectors.toList());
        }

        //匹配场站条件
        if (wpids.size() > 0) {
            qw.lambda().in(ProEconEquipmentInfoDayTop::getWindpowerstationId, wpids);
        }
        //        if (StringUtils.isNotEmpty(date)) {
        //            qw.lambda().eq(ProEconEquipmentInfoDayTop::getRecordDate, DateUtils.parseDate(date));
        //        }
        if (null != types && types.equals(1)) {
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getRecordDate, DateUtils.parseDate(date));
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getTypes, 1);
        }
        if (null != types && types.equals(2)) {

            //            Calendar c= Calendar.getInstance();
            //            c.set(Calendar.YEAR,Integer.valueOf(str1));
            //            c.set(Calendar.MONTH,Integer.valueOf(result)-1);
            //            c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));


            qw.lambda().eq(ProEconEquipmentInfoDayTop::getRecordDate, DateUtils.parseDate(date));
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getTypes, 2);

            qw.lambda().orderByDesc(ProEconEquipmentInfoDayTop::getRecordDate);
        }
        if (null != types && types.equals(3)) {
            //            Calendar c= Calendar.getInstance();
            //            c.set(Calendar.YEAR,Integer.valueOf(str1));
            //            c.set(Calendar.DAY_OF_YEAR, c.getActualMaximum(Calendar.DAY_OF_YEAR));
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getRecordDate, DateUtils.parseDate(date));
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getTypes, 3);
            qw.lambda().orderByDesc(ProEconEquipmentInfoDayTop::getRecordDate);
        }


        qw.lambda().orderByAsc(ProEconEquipmentInfoDayTop::getWindturbineId);

        //        Page<ProEconEquipmentInfoDayTop> resultPage = proEconEquipmentInfoDayTopMapper.selectPage(page, qw);
        //        List<ProEconEquipmentInfoDayTop> list = resultPage.getRecords();
        IPage<ProEconEquipmentInfoDayTop> resultPage = getBaseMapper().selectPage(page, qw);
        List<ProEconEquipmentInfoDayTop> list = resultPage.getRecords();

        //        List<ProEconEquipmentInfoDayTop> list = baseMapper.selectList(qw);
        resultPage.getRecords().stream().forEach(i -> {
            i.setNemCode(CacheContext.wtmap.get(i.getWindturbineId()).getAname());
        });
        return resultPage;
    }

    public List<TurbineInfoDay> getTopAndList(String windturbineId, String beginDate, String endDate) {
        QueryWrapper<TurbineInfoDay> qw = new QueryWrapper<>();
        qw.lambda().eq(TurbineInfoDay::getTurbineId, windturbineId).orderByAsc(TurbineInfoDay::getRecordDate)
                .between(TurbineInfoDay::getRecordDate, DateUtils.parseDate(beginDate), DateUtils.parseDate(endDate));
        List<TurbineInfoDay> list = turbineInfoDayService.list(qw);
        return list;
    }

    @Override
    public List<ProEconEquipmentInfoDayTop> getEquipmentInfoDayTopHistoryList(String windturbineId, Integer types, String beginDate, String endDate) {
        List<ProEconEquipmentInfoDayTop> listBf = getEquipmentInfoDayTopHistoryList_bf(windturbineId, types, beginDate, endDate);
        List<TurbineInfoDay> andList = getTopAndList(windturbineId, beginDate, endDate);
        return turbs2equipmentidt2(listBf, andList);
    }

    private List<ProEconEquipmentInfoDayTop> turbs2equipmentidt2(List<ProEconEquipmentInfoDayTop> peeidtRecords, List<TurbineInfoDay> tidRecords) {
        if (peeidtRecords == null || peeidtRecords.isEmpty() || tidRecords == null || tidRecords.isEmpty()) return Collections.emptyList();
        Map<Date, TurbineInfoDay> dayMap = tidRecords.stream().collect(Collectors.toMap(TurbineInfoDay::getRecordDate, Function.identity()));
        peeidtRecords.forEach(peeidt->{
            TurbineInfoDay day = dayMap.get(peeidt.getRecordDate());
            peeidt.setDayfdl(NumberUtil.round(day.getRfdl(),2).doubleValue());
            peeidt.setDayllfdl(NumberUtil.round(day.getLlfdl(),2).doubleValue());
            peeidt.setDayfs(NumberUtil.round(day.getPjfs(),2).doubleValue());
            peeidt.setDaygzssdl(NumberUtil.round(day.getGzss(),2).doubleValue());
            peeidt.setDayxdssdl(NumberUtil.round(day.getXdss(),2).doubleValue());
            peeidt.setDaywhssdl(NumberUtil.round(day.getFjhjxss(),2).doubleValue());
            peeidt.setDayxnssdl(NumberUtil.round(day.getXnss(),2).doubleValue());
            peeidt.setDaylyxs(NumberUtil.round(day.getLyxs(),2).doubleValue());
            peeidt.setDaysbklyl(NumberUtil.round(day.getKlyl(),2).doubleValue());
            peeidt.setDayyxfss(NumberUtil.round(day.getYxfss(),2).doubleValue());
            peeidt.setDayjfpl(NumberUtil.round(day.getJfpl(),2).doubleValue());
        });
        return peeidtRecords;
    }

    public List<ProEconEquipmentInfoDayTop> getEquipmentInfoDayTopHistoryList_bf(String windturbineId, Integer types, String beginDate, String endDate) {

        QueryWrapper<ProEconEquipmentInfoDayTop> qw = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(windturbineId)) {
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getWindturbineId, windturbineId);
        }
        if (null != types) {
            qw.lambda().eq(ProEconEquipmentInfoDayTop::getTypes, types);
        }

        if (StringUtils.isNotEmpty(beginDate) && StringUtils.isNotEmpty(endDate))
            qw.lambda().ge(ProEconEquipmentInfoDayTop::getRecordDate, DateUtils.parseDate(beginDate)).
                    le(ProEconEquipmentInfoDayTop::getRecordDate, DateUtils.parseDate(endDate));

        qw.orderByAsc("record_date");
        List<ProEconEquipmentInfoDayTop> list = baseMapper.selectList(qw);
        list.stream().forEach(i -> {
            i.setNemCode(CacheContext.wtmap.get(i.getWindturbineId()).getAname());
        });
        return list;
    }

    @Override
    public Map<String, Object> getEquipmentInfoDayTopCompareList(List<Long> ids, Integer types) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> chartsMap = new HashMap<>();
        QueryWrapper<ProEconEquipmentInfoDayTop> qw = new QueryWrapper<>();


        if (null != ids && ids.size() > 0) {
            qw.lambda().in(ProEconEquipmentInfoDayTop::getId, ids);
        }
        List<ProEconEquipmentInfoDayTop> list = baseMapper.selectList(qw);
        list.stream().forEach(i -> {
            i.setNemCode(CacheContext.wtmap.get(i.getWindturbineId()).getAname());
        });
        resultMap.put("data", list);


        list.stream().forEach(wtd -> {
            List<CompareVo> compareList = new ArrayList<>();

            for (int i = 0; i < 10; i++) {
                CompareVo vo = new CompareVo();

                switch (i) {
                    case 0:
                        vo.setTarget("平均切入风速");
                        vo.setData(wtd.getYearxfqr());
                        break;
                    case 1:
                        vo.setTarget("性能损失电量");
                        vo.setData(wtd.getYearxnssdl());
                        break;
                    case 2:
                        vo.setTarget("拟合优度");
                        vo.setData(wtd.getYearnhyd());
                        break;
                    case 3:
                        vo.setTarget("功率一致性系数");
                        vo.setData(wtd.getYearglyzxxs());
                        break;
                    case 4:
                        vo.setTarget("利用小时");
                        vo.setData(wtd.getYearlyxs());
                        break;
                    case 5:
                        vo.setTarget("设备可利用率");
                        vo.setData(wtd.getYearsbklyl());
                        break;
                    case 6:
                        vo.setTarget("等效可利用系数");
                        vo.setData(wtd.getYeardxkyxs());
                        break;
                    case 7:
                        vo.setTarget("有效风时数");
                        vo.setData(wtd.getYearyxfss());
                        break;
                    case 8:
                        vo.setTarget("平均风速");
                        vo.setData(wtd.getYearfs());
                        break;
                    case 9:
                        vo.setTarget("静风频率");
                        vo.setData(wtd.getYearjfpl());
                        break;
                    default:
                        break;
                }
                compareList.add(vo);
            }
            chartsMap.put(wtd.getNemCode(), compareList);

        });
        resultMap.put("charts", chartsMap);
        return resultMap;
    }


}
