package com.energy.manage.service.test;

import com.alibaba.fastjson.JSONArray;
import com.energy.manage.common.po.analysisdatarelationrecords.AnalysisDataRelationRecordsPo;
import com.energy.manage.common.po.analysispriorityrecords.AnalysisPriorityRecordsPo;
import com.energy.manage.common.reponse.ResultResp;
import com.energy.manage.service.config.AnalysisTypeConfig;
import com.energy.manage.service.config.annotations.UserLoginToken;
import com.energy.manage.service.constant.analysis.AnalysisConstants;
import com.energy.manage.service.controller.base.BaseServiceController;
import com.energy.manage.service.domain.dto.analysis.AnalysisDto;
import com.energy.manage.service.domain.vo.analysis.AnalysisTypeVo;
import com.energy.manage.service.domain.vo.datatransfer.DataTransferVo;
import com.energy.manage.service.mappers.analysis.AnalysisResultMapper;
import com.energy.manage.service.mappers.analysis.AnalysisTypeMapper;
import com.energy.manage.service.mappers.analysisdatarelationrecords.AnalysisDataRelationRecordsMapper;
import com.energy.manage.service.mappers.analysispriorityrecords.AnalysisPriorityRecordsMapper;
import com.energy.manage.service.mappers.datatransfer.DataTransferMapper;
import com.energy.manage.service.service.analysis.AnalysisService;
import com.energy.manage.service.service.analysis.AutoAnalysisService;
import com.energy.manage.service.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chy
 * @date 2024/6/19 11:22
 * @desc
 */
@Slf4j
@RestController
@RequestMapping("/test")
@RefreshScope
public class TestController extends BaseServiceController {

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private AutoAnalysisService autoAnalysisService;

    @Autowired
    private AnalysisTypeMapper typeMapper;


    @Autowired
    private AnalysisPriorityRecordsMapper priorityRecordsMapper;

    @Autowired
    private AnalysisResultMapper resultMapper;

    @Autowired
    private AnalysisDataRelationRecordsMapper dataRelationRecordsMapper;

    @Autowired
    private AnalysisTypeConfig analysisTypeConfig;

    @Value("${download.url}")
    private String downloadUrl;

    @UserLoginToken
    @PostMapping("/testAutoAnalysis")
    public ResultResp autoAnalysis() {
        log.info("触发自动分析定时任务开始");
        autoAnalysisService.autoAnalysis();
        log.info("触发自动分析定时任务结束");
        return success();
    }

    @UserLoginToken
    @PostMapping("/testRefresh")
    public ResultResp testRefresh() {
        return success(JSONArray.parseArray(analysisTypeConfig.getAnalysisTypeConfig()));
    }

    @UserLoginToken
    @PostMapping("/testIpUtils")
    public ResultResp testIpUtils(HttpServletRequest request) {
        return success(IPUtils.getIpAddr(request));
    }

    @PostMapping("/testAnalysisTask")
    public ResultResp testIpUtils() {
        log.info("触发自动分析定时任务开始");
        try{
            int analysisingCount = resultMapper.selectAnalysisProcessingCount();
            if (analysisingCount > 0){
                log.info("当前有正在分析的数据，排队分析返回");
                return success(111);
            }
            //获取要执行的分析任务
            AnalysisPriorityRecordsPo priorityRecordsPo = priorityRecordsMapper.queryFirstPriority();
            if (priorityRecordsPo == null){
                log.info("当前没有要分析的任务在排队中，分析返回");
                return success(222);
            }
            //调用分析
            analysisService.callAnalysis(getAnalysisDto(priorityRecordsPo));
            //更新任务优先级状态为已执行
            priorityRecordsMapper.updateExecuteStatus(priorityRecordsPo.getTaskId(), AnalysisConstants.ON_CALL);
        }catch (Exception e){
            log.error("触发自动分析定时任务异常",e);
        }
        log.info("触发自动分析定时任务结束");
        return success();
    }


    /**
     * 获取要执行的分析任务参数
     * @return
     */
    private AnalysisDto getAnalysisDto(AnalysisPriorityRecordsPo priorityRecordsPo){
        AnalysisDataRelationRecordsPo dataRelationRecordsPo = dataRelationRecordsMapper.selectByTaskId(priorityRecordsPo.getTaskId());
        AnalysisDto returnDto = new AnalysisDto();
        BeanUtils.copyProperties(dataRelationRecordsPo,returnDto);
        //设置分析类型
        returnDto.setConfigAnalysis(Arrays.asList(dataRelationRecordsPo.getConfigAnalysis().split(",")));
        //设置风机
        if(StringUtils.isNotEmpty(dataRelationRecordsPo.getTurbines())){
            returnDto.setTurbines(Arrays.asList(dataRelationRecordsPo.getTurbines().split(",")));
        }
        //设置排除月份
        if(StringUtils.isNotEmpty(dataRelationRecordsPo.getExcludingMonths())) {
            returnDto.setExcludingMonths(Arrays.asList(dataRelationRecordsPo.getExcludingMonths().split(",")));
        }
        //设置有功功率
        if(StringUtils.isNotEmpty(dataRelationRecordsPo.getValueActivePower())) {
            returnDto.setValueActivePower(getDoubleList(dataRelationRecordsPo.getValueActivePower()));
        }
        //设置风机转速
        if(StringUtils.isNotEmpty(dataRelationRecordsPo.getValueGeneratorSpeed())) {
            returnDto.setValueGeneratorSpeed(getDoubleList(dataRelationRecordsPo.getValueGeneratorSpeed()));
        }
        //设置桨距角
        if(StringUtils.isNotEmpty(dataRelationRecordsPo.getValuePitchAngle())) {
            returnDto.setValuePitchAngle(getDoubleList(dataRelationRecordsPo.getValuePitchAngle()));
        }
        //设置风速
        if(StringUtils.isNotEmpty(dataRelationRecordsPo.getValueWindSpeed())) {
            returnDto.setValueWindSpeed(getDoubleList(dataRelationRecordsPo.getValueWindSpeed()));
        }
        return returnDto;
    }

    private List<Double> getDoubleList(String value){
        if(StringUtils.isNotEmpty(value)){
            return Arrays.asList(value.split(",")).stream().map(Double::parseDouble).collect(Collectors.toList());
        }
        return null;
    }


    /**
     * 设置分析参数
     * @param dataTransferVo
     * @return
     */
    private AnalysisDto assignmentAnalysisDto(DataTransferVo dataTransferVo){
        AnalysisDto analysisDto = new AnalysisDto();
        analysisDto.setAutoOrManual(AnalysisConstants.AUTO_ANALYSIS);
        analysisDto.setDataBatchNum(dataTransferVo.getBatchCode());
        analysisDto.setPowerFarmID(dataTransferVo.getFieldCode());
        List<String> typeCodeList = typeMapper.selectAllVo().parallelStream().map(AnalysisTypeVo::getTypeFlag).collect(Collectors.toList());
        analysisDto.setConfigAnalysis(typeCodeList);
        return analysisDto;
    }


}
