package com.gyee.runeconomy.controller;


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.gyee.runeconomy.dto.AjaxResult;
import com.gyee.runeconomy.dto.R;
import com.gyee.runeconomy.dto.ResultCode;
import com.gyee.runeconomy.dto.ResultMsg;
import com.gyee.runeconomy.init.CacheContext;
import com.gyee.runeconomy.model.auto.ProBasicEquipment;
import com.gyee.runeconomy.model.auto.ProEconEquipmentInfoDayTop;
import com.gyee.runeconomy.model.auto.TurbineInfoDay;
import com.gyee.runeconomy.model.vo.SingleAnalysisVo;
import com.gyee.runeconomy.service.auto.ITurbineInfoDayService;
import com.gyee.runeconomy.service.singleanalysis.SingleAnalysisService;
import com.gyee.runeconomy.util.DateUtils;
import com.gyee.runeconomy.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/singleanalysis")
@Api(value = "单机性能分析", tags = "单机性能分析")
public class SingleAnalysisController {

    @Resource
    private SingleAnalysisService singleAnalysisService;
    @Resource
    private ITurbineInfoDayService turbineInfoDayService;

    @PostMapping("/singleanalysisMain")
    @ResponseBody
    @ApiOperation(value = "查询单机性能分析首页", notes = "查询单机性能分析首页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "cmId", value = "公司编号或者区域编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "0全部、光伏(-2)、风场(-1)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "wpId", value = "风场编号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "month", value = "月份", required = true, dataType = "string", paramType = "query")})

    public R singleanalysisMain(Integer pageNum, Integer pageSize, String cmId, String type, String wpId, String year, String month) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.empty(year) && StringUtils.empty(month)) return R.data(ResultMsg.ok(map));

        Calendar cal = Calendar.getInstance();
        int newyear = cal.get(Calendar.YEAR);
        int newmonth = cal.get(Calendar.MONTH) + 1;
        Date recordDate = null;
        if (Integer.valueOf(year) == newyear && Integer.valueOf(month) == newmonth) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
            recordDate = DateUtils.truncate(cal.getTime());
        } else {
            cal.set(Calendar.YEAR, Integer.valueOf(year));
            cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            recordDate = DateUtils.truncate(cal.getTime());
        }

        map = singleAnalysisService.SingleAnalysisList(pageNum, pageSize, cmId, type, wpId, recordDate);

        List<SingleAnalysisVo> subList = (List<SingleAnalysisVo>) map.get("values");
        QueryWrapper<TurbineInfoDay> qw = new QueryWrapper<>();
        qw.lambda().eq(TurbineInfoDay::getStationId, wpId).eq(TurbineInfoDay::getRecordDate, recordDate).orderByAsc(TurbineInfoDay::getTurbineId);
        IPage<TurbineInfoDay> page = new Page<>(pageNum, pageSize);
        IPage<TurbineInfoDay> page1 = turbineInfoDayService.page(page, qw);
        Map<String, TurbineInfoDay> dayMap = page1.getRecords().stream().collect(Collectors.toMap(TurbineInfoDay::getTurbineId, Function.identity()));
        List<SingleAnalysisVo> subList2 = subList.stream().filter(s -> null != s.getWindturbineid()).collect(Collectors.toList());
        List<SingleAnalysisVo> subList3 = subList.stream().filter(s -> null == s.getWindturbineid()).collect(Collectors.toList());
        if (subList3.size() == 1) {
            List<TurbineInfoDay> list = turbineInfoDayService.list(qw);
            SingleAnalysisVo sav = subList3.get(0);
            double fdl = list.stream().mapToDouble(TurbineInfoDay::getRfdl).sum();
            sav.setFdl(NumberUtil.round(fdl,2).doubleValue());
            double fs = list.stream().mapToDouble(TurbineInfoDay::getPjfs).average().orElse(0.0);
            sav.setFs(NumberUtil.round(fs,2).doubleValue());
            double gzss = list.stream().mapToDouble(TurbineInfoDay::getGzss).sum();
            sav.setGzss(NumberUtil.round(gzss,2).doubleValue());
            double jxss = list.stream().mapToDouble(TurbineInfoDay::getJhjxss).sum();
            sav.setJxss(NumberUtil.round(jxss,2).doubleValue());
            double xdss = list.stream().mapToDouble(TurbineInfoDay::getXdss).sum();
            sav.setXdss(NumberUtil.round(xdss,2).doubleValue());
            double xnss = list.stream().mapToDouble(TurbineInfoDay::getXnss).sum();
            sav.setXnss(NumberUtil.round(xnss,2).doubleValue());
            double slss = list.stream().mapToDouble(TurbineInfoDay::getSlss).sum();
            sav.setSlss(NumberUtil.round(slss,2).doubleValue());
            double llfdl = list.stream().mapToDouble(TurbineInfoDay::getLlfdl).sum();
            sav.setLlfdl(NumberUtil.round(llfdl,2).doubleValue());
            double gzmin = list.stream().mapToDouble(TurbineInfoDay::getGzMin).sum();
            sav.setGzxs(NumberUtil.round(gzmin / 60, 2).doubleValue());
            double jxmin = list.stream().mapToDouble(TurbineInfoDay::getJxMin).sum();
            sav.setJxxs(NumberUtil.round(jxmin / 60, 2).doubleValue());
            double tjmin = list.stream().mapToDouble(TurbineInfoDay::getTjMin).sum();
            sav.setTjxs(NumberUtil.round(tjmin / 60, 2).doubleValue());
            double yxmin = list.stream().mapToDouble(TurbineInfoDay::getYxMin).sum();
            sav.setYxxs(NumberUtil.round(yxmin / 60, 2).doubleValue());
            double djmin = list.stream().mapToDouble(TurbineInfoDay::getDjMin).sum();
            sav.setDjxs(NumberUtil.round(djmin / 60, 2).doubleValue());
            double lyxs = list.stream().mapToDouble(TurbineInfoDay::getLyxs).sum();
            sav.setLyxs(NumberUtil.round(lyxs,2).doubleValue());
            double sbklyl = list.stream().mapToDouble(TurbineInfoDay::getKlyl).average().orElse(0.0);
            sav.setSbklyl(NumberUtil.round(sbklyl,2).doubleValue());
            double xfqrfs = list.stream().mapToDouble(TurbineInfoDay::getXfqrfs).average().orElse(0.0);
            sav.setXfqr(NumberUtil.round(xfqrfs,2).doubleValue());
            double yxfss = list.stream().mapToDouble(TurbineInfoDay::getYxfss).sum();
            sav.setYxfss(NumberUtil.round(yxfss,2).doubleValue());
            double jfpl = list.stream().mapToDouble(TurbineInfoDay::getJfpl).sum();
            sav.setJfpl(NumberUtil.round(jfpl,2).doubleValue());
        }
        subList2.forEach(sav -> {
            TurbineInfoDay day = dayMap.get(sav.getWindturbineid());
            sav.setFdl(NumberUtil.round(day.getRfdl(),2).doubleValue());
            sav.setFs(NumberUtil.round(day.getPjfs(),2).doubleValue());
            sav.setGzss(NumberUtil.round(day.getGzss(),2).doubleValue());
            sav.setJxss(NumberUtil.round(day.getJhjxss(),2).doubleValue());
            sav.setXdss(NumberUtil.round(day.getXdss(),2).doubleValue());
            sav.setXnss(NumberUtil.round(day.getXnss(),2).doubleValue());
            sav.setSlss(NumberUtil.round(day.getSlss(),2).doubleValue());
            sav.setLlfdl(NumberUtil.round(day.getLlfdl(),2).doubleValue());
            sav.setGzxs(NumberUtil.round(day.getGzMin() / 60, 2).doubleValue());
            sav.setJxxs(NumberUtil.round(day.getJxMin() / 60, 2).doubleValue());
            sav.setTjxs(NumberUtil.round(day.getTjMin() / 60, 2).doubleValue());
            sav.setYxxs(NumberUtil.round(day.getYxMin() / 60, 2).doubleValue());
            sav.setDjxs(NumberUtil.round(day.getDjMin() / 60, 2).doubleValue());
            sav.setLyxs(NumberUtil.round(day.getLyxs(),2).doubleValue());
            sav.setSbklyl(NumberUtil.round(day.getKlyl(),2).doubleValue());
            sav.setXfqr(NumberUtil.round(day.getXfqrfs(),2).doubleValue());
            sav.setYxfss(NumberUtil.round(day.getYxfss(),2).doubleValue());
            sav.setJfpl(NumberUtil.round(day.getJfpl(),2).doubleValue());
        });

        return R.data(ResultMsg.ok(map));

    }

    public R singleanalysisMain_bf(Integer pageNum, Integer pageSize, String cmId, String type, String wpId, String year, String month) throws Exception {

        Map<String, Object> map = new HashMap<>();
        List<SingleAnalysisVo> vos = new ArrayList<>();

        if (StringUtils.notEmp(year) && StringUtils.notEmp(month)) {

            Calendar cal = Calendar.getInstance();
            int newyear = cal.get(Calendar.YEAR);
            int newmonth = cal.get(Calendar.MONTH) + 1;
            Date recordDate = null;
            if (Integer.valueOf(year) == newyear && Integer.valueOf(month) == newmonth) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
                recordDate = DateUtils.truncate(cal.getTime());
            } else {
                cal.set(Calendar.YEAR, Integer.valueOf(year));
                cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
                cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
                recordDate = DateUtils.truncate(cal.getTime());
            }


            map = singleAnalysisService.SingleAnalysisList(pageNum, pageSize, cmId, type, wpId, recordDate);


        }

        return R.data(ResultMsg.ok(map));

    }

    /**
     * 单机信息总览子页面
     *
     * @param wtId
     * @param year
     * @param month
     * @return
     * @throws Exception
     */
    @GetMapping("/singleanalysisSub")
    @ResponseBody
    @ApiOperation(value = "查询单机性能分析子页面", notes = "查询单机性能分析子页面")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "wtId", value = "风机编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "month", value = "月份", required = true, dataType = "string", paramType = "query")})

    public R singleanalysisSub(String wtId, String year, String month) throws Exception {

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

        if (StringUtils.notEmp(wtId) && StringUtils.notEmp(year) && StringUtils.notEmp(month)) {
            Calendar cal = Calendar.getInstance();
            int newyear = cal.get(Calendar.YEAR);
            int newmonth = cal.get(Calendar.MONTH) + 1;
            Date recordDate = null;
            if (Integer.valueOf(year) == newyear && Integer.valueOf(month) == newmonth) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
                recordDate = DateUtils.truncate(cal.getTime());
            } else {
                cal.set(Calendar.YEAR, Integer.valueOf(year));
                cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
                cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
                recordDate = DateUtils.truncate(cal.getTime());
            }

            String wtcode = null;
            if (CacheContext.wtmap.containsKey(wtId)) {
                ProBasicEquipment wt = CacheContext.wtmap.get(wtId);
                wtcode = wt.getAname();

            }

            SingleAnalysisVo byzb = singleAnalysisService.SingleAnalysisListByWtId(wtId, recordDate);

            byzb.setWtcode(wtcode);
            SingleAnalysisVo singleAnalysisVo = singleAnalysisService.SingleAnalysisTurbineinfoday(wtId, year, month, byzb);

            cal.add(Calendar.YEAR, -1);
            Date lastYear = DateUtils.truncate(cal.getTime());

            SingleAnalysisVo tqzb = singleAnalysisService.SingleAnalysisListByWtId(wtId, lastYear);
            SingleAnalysisVo tqzbNew = singleAnalysisService.SingleAnalysisTurbineinfoday(wtId, lastYear.toString(), month, tqzb);

            SingleAnalysisVo tbzb = singleAnalysisService.SingleAnalysisListByWtId(byzb, tqzb);

            tqzb.setWtcode(wtcode);
            tbzb.setWtcode(wtcode);

            cal.setTime(recordDate);
            cal.add(Calendar.MONTH, -1);

            Date lastMonth = DateUtils.truncate(cal.getTime());
            SingleAnalysisVo hqzb = singleAnalysisService.SingleAnalysisListByWtId(wtId, lastMonth);
            SingleAnalysisVo hbzb = singleAnalysisService.SingleAnalysisListByWtId(byzb, hqzb);

            hqzb.setWtcode(wtcode);
            hbzb.setWtcode(wtcode);

            map.put("byzb", byzb);//本月指标
            map.put("tqzb", tqzb);//全年同期
            map.put("tbzb", tbzb);//同比指标
            map.put("hqzb", hqzb);//上月同期
            map.put("hbzb", hbzb);//环比指标
        }

        //        if (null!=map) {
        //            return AjaxResult.successData(ResultCode.SUCCESS, map);
        //        } else {
        //            return AjaxResult.successData(ResultCode.SUCCESS, map);
        //        }

        return R.data(ResultMsg.ok(map));
    }


    /**
     * 单机信息总览图表接口(3个)
     *
     * @param wtId
     * @param year
     * @param month
     * @return
     * @throws Exception
     */
    @GetMapping("/singleanalysisChart")
    @ResponseBody
    @ApiOperation(value = "单机信息总览图表接口(3个) 发电量和风速、五项损失、静风频率和待机时间", notes = "单机信息总览图表接口(3个) 发电量和风速、五项损失、静风频率和待机时间")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "wtId", value = "风机编号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "month", value = "月份", required = true, dataType = "string", paramType = "query")})

    public AjaxResult singleanalysisChart(String wtId, String year, String month) throws Exception {

        Map<String, List<SingleAnalysisVo>> map = new HashMap<>();

        if (StringUtils.notEmp(wtId) && StringUtils.notEmp(year) && StringUtils.notEmp(month)) {

            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);

            cal.set(Calendar.YEAR, Integer.valueOf(year));
            cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
            Date beginDate = cal.getTime();
            cal.add(Calendar.MONTH, 1);
            Date endDate = cal.getTime();

            map = singleAnalysisService.SingleAnalysisListByWtIdDetiml(wtId, beginDate, endDate);

        }

        //        map.put("ff",fdlfsls);//发电量和风速
        //        map.put("ws",wsls);//五项损失，绑定五个
        //        map.put("jd",jfpldjsjls);//静风频率和待机时间

        if (null != map) {
            return AjaxResult.successData(ResultCode.SUCCESS, map);
        } else {
            return AjaxResult.successData(ResultCode.SUCCESS, map);
        }

    }


}
