package com.gyee.runeconomy.controller;/*
@author   谢生杰
@date   2023/3/28-15:47
*/

import com.gyee.common.model.PointData;
import com.gyee.common.model.StringUtils;
import com.gyee.runeconomy.dto.R;
import com.gyee.runeconomy.dto.ResultMsg;
import com.gyee.runeconomy.init.CacheContext;
import com.gyee.runeconomy.model.auto.ProBasicCompany;
import com.gyee.runeconomy.model.auto.ProBasicEquipmentPoint;
import com.gyee.runeconomy.model.auto.ProBasicPowerstationPoint;
import com.gyee.runeconomy.model.auto.ProBasicSubStation;
import com.gyee.runeconomy.service.TokenService;
import com.gyee.runeconomy.util.DateUtils;
import com.gyee.runeconomy.util.realtimesource.IEdosUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class CommonController {
    @Resource
    private IEdosUtil edosUtil;

    @Resource
    private TokenService tokenService;

    /**
     * 查询公司
     *
     * @return
     */
    @GetMapping("/findCompanys")
    @ResponseBody
    @ApiOperation(value = "查询公司", notes = "查询公司")
    public R findCompanys(@RequestParam(value = "regionid", required = false) String regionid) throws Exception {
        List<ProBasicCompany> cpls = CacheContext.cpls;
        if (StringUtils.isNotEmpty(regionid)) {
            cpls = cpls.stream().filter(i -> i.getRegionId().equals(regionid)).collect(Collectors.toList());
        }

        if (StringUtils.isNotNull(cpls)) {
            return R.data(ResultMsg.ok(cpls));
        } else {
            return R.error(ResultMsg.error());
        }
    }


    /**
     * 查询设备测点
     *
     * @return
     */
    @GetMapping("/findWtPoints")
    @ResponseBody
    @ApiOperation(value = "查询设备测点", notes = "查询设备测点")
    public R findWtPoints(@RequestParam(value = "uniformcodes", required = true) String unifromcodes,
                          @RequestParam(value = "wtid", required = true) String wtid) {

        Map<String, Map<String, ProBasicEquipmentPoint>> wtpAimap = CacheContext.wtpAimap;
        Map<String, ProBasicEquipmentPoint> equipmentPointMap = wtpAimap.get(wtid);

        List<ProBasicEquipmentPoint> resultList = new ArrayList<>();

//        String[] split = unifromcodes.split(",");
//        Arrays.stream(split).forEach(s -> {
//            resultList.add(equipmentPointMap.get(s));
//        });


        if (equipmentPointMap != null) {
            String[] split = unifromcodes.split(",");
            resultList = Arrays.stream(split)
                    .map(equipmentPointMap::get)  // 获取对应的 ProBasicEquipmentPoint
                    .filter(Objects::nonNull)    // 过滤掉 null 值
                    .collect(Collectors.toList());
        }
        if (StringUtils.isNotNull(resultList)) {
            return R.data(ResultMsg.ok(resultList));
        } else {
            return R.error(ResultMsg.error());
        }
    }

    /**
     * 查询场站测点
     *
     * @return
     */
    @GetMapping("/findWpPoints")
    @ResponseBody
    @ApiOperation(value = "查询场站测点", notes = "查询场站测点")
    public R findWpPoints(@RequestParam(value = "uniformcodes", required = true) String unifromcodes,
                          @RequestParam(value = "wpid", required = true) String wpid) {

        Map<String, Map<String, ProBasicPowerstationPoint>> wppointmap = CacheContext.wppointmap;
        Map<String, Map<String, ProBasicPowerstationPoint>> subwppointmap = CacheContext.subwppointmap;

        Map<String, ProBasicPowerstationPoint> powerstationPointMap = wppointmap.get(wpid);
        Map<String, ProBasicPowerstationPoint> substationPointMap = new HashMap<>();
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        List<ProBasicSubStation> subwpls = tokenService.getSubwpls(request);
        for (ProBasicSubStation sub : subwpls) {
            if (sub.getWindpowerstationId().equals(wpid)) {
                substationPointMap = subwppointmap.get(sub.getId());

                break;
            }

        }

        List<ProBasicPowerstationPoint> resultList = new ArrayList<>();

        String[] split = unifromcodes.split(",");

        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            if (powerstationPointMap.containsKey(s)) {
                resultList.add(powerstationPointMap.get(s));
            }

            if (substationPointMap.containsKey(s)) {
                resultList.add(substationPointMap.get(s));
            }
        }


        if (StringUtils.isNotNull(resultList)) {
            return R.data(ResultMsg.ok(resultList));
        } else {
            return R.error(ResultMsg.error());
        }
    }


    /**
     * 查询调度场站测点
     *
     * @return
     */
    @GetMapping("/findSubPoints")
    @ResponseBody
    @ApiOperation(value = "查询调度场站测点", notes = "查询调度场站测点")
    public R findSubPoints(@RequestParam(value = "uniformcodes", required = true) String unifromcodes,
                           @RequestParam(value = "wpid", required = true) String wpid) {

        Map<String, Map<String, ProBasicPowerstationPoint>> subwppointmap = CacheContext.subwppointmap;
        Map<String, ProBasicPowerstationPoint> powerstationPointMap = subwppointmap.get(wpid);

        List<ProBasicPowerstationPoint> resultList = new ArrayList<>();

        String[] split = unifromcodes.split(",");
        Arrays.stream(split).forEach(s -> {
            resultList.add(powerstationPointMap.get(s));
        });

        if (StringUtils.isNotNull(resultList)) {
            return R.data(ResultMsg.ok(resultList));
        } else {
            return R.error(ResultMsg.error());
        }
    }

    /**
     * 查询期次测点
     *
     * @return
     */
    @GetMapping("/findProPoints")
    @ResponseBody
    @ApiOperation(value = "查询期次测点", notes = "查询期次测点")
    public R findProPoints(@RequestParam(value = "uniformcodes", required = true) String unifromcodes,
                           @RequestParam(value = "wpid", required = true) String wpid) {

        Map<String, Map<String, ProBasicPowerstationPoint>> propointmap = CacheContext.propointmap;
        Map<String, ProBasicPowerstationPoint> powerstationPointMap = propointmap.get(wpid);

        List<ProBasicPowerstationPoint> resultList = new ArrayList<>();

        String[] split = unifromcodes.split(",");
        Arrays.stream(split).forEach(s -> {
            resultList.add(powerstationPointMap.get(s));
        });

        if (StringUtils.isNotNull(resultList)) {
            return R.data(ResultMsg.ok(resultList));
        } else {
            return R.error(ResultMsg.error());
        }
    }

    /**
     * 查询测点曲线
     *
     * @return
     */
    @GetMapping("/findPointFitting")
    @ResponseBody
    @ApiOperation(value = "查询测点曲线", notes = "查询测点曲线")
    public R findPointFitting(@RequestParam(value = "pointIds", required = true) String pointIds,
                              @RequestParam(value = "begin", required = true) String begin,
                              @RequestParam(value = "end", required = true) String end,
                              @RequestParam(value = "interval", required = true) String interval) {
        Date beginDate = DateUtils.parseDate1(begin);
        Date endDate = DateUtils.parseDate1(end);
        List<List<PointData>> resultList = new ArrayList<>();

        String[] points = pointIds.split(",");
        Arrays.stream(points).forEach(p -> {
            List<PointData> datasSnap = null;
            try {
                if (!p.equals("INITIAL")) {
                    datasSnap = edosUtil.getHistoryDatasSnap(p, beginDate.getTime() / 1000, endDate.getTime() / 1000, null, Long.parseLong(interval));
                }
                resultList.add(datasSnap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        if (StringUtils.isNotNull(resultList)) {
            return R.data(ResultMsg.ok(resultList));
        } else {
            return R.error(ResultMsg.error());
        }
    }

    /**
     * 查询测点值
     *
     * @return
     */
    @GetMapping("/findPointDatas")
    @ResponseBody
    @ApiOperation(value = "查询测点值", notes = "查询测点值")
    public R findPointDatas(@RequestParam(value = "pointIds", required = true) String pointIds) throws Exception {


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

        String[] points = pointIds.split(",");
        if (points == null || points.length == 0 || Arrays.stream(points).allMatch(String::isEmpty)) {
            return R.error(ResultMsg.error());
        }
        Arrays.stream(points).forEach(p -> {
            pointList.add(p);
        });
        List<PointData> resultList = edosUtil.getRealData(pointList);
        if (StringUtils.isNotNull(resultList)) {
            return R.data(ResultMsg.ok(resultList));
        } else {
            return R.error(ResultMsg.error());
        }
    }
}
