package com.njcn.csharmonic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.DataSetFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.dto.LineParamDTO;
import com.njcn.csdevice.pojo.po.CsDataSet;
import com.njcn.csdevice.pojo.po.CsLedger;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.utils.DataChangeUtil;
import com.njcn.csharmonic.param.DevicDataTrendQueryParam;
import com.njcn.csharmonic.pojo.vo.ThdDataVO;
import com.njcn.csharmonic.service.DeviceDataTrendService;
import com.njcn.csharmonic.util.InfluxDbParamUtil;
import com.njcn.influx.pojo.bo.CommonQueryParam;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.influx.service.CommonService;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.po.EleEpdPqd;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.njcn.csharmonic.constant.HarmonicConstant.POWER_LIST;

/**
 * Description:
 * Date: 2023/6/26  9:14【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class DeviceDataTrendServiceImpl implements DeviceDataTrendService {
    private final CommonService commonService;
    private final CsLedgerFeignClient csLedgerFeignClient;
    private final CsLineFeignClient csLineFeignClient;
    private final EquipmentFeignClient equipmentFeignClient;
    private final InfluxDbParamUtil influxDbParamUtil;
    private final EpdFeignClient epdFeignClient;
    private final DataSetFeignClient dataSetFeignClient;

    @Override
    public List<List<ThdDataVO>> queryDataTrend(DevicDataTrendQueryParam devicDataTrendQueryParam) {
        List<List<ThdDataVO>> result = new ArrayList<>();

        if(CollectionUtils.isEmpty(devicDataTrendQueryParam.getStatisticalParams())){
            return result;
        }
        LineParamDTO lineParamDTO = new LineParamDTO();
        lineParamDTO.setLineId(devicDataTrendQueryParam.getLineId());
        List<CsLedger> data = csLedgerFeignClient.queryLine(lineParamDTO).getData();
        List<CsEquipmentDeliveryDTO> data1 = equipmentFeignClient.queryDeviceById(Stream.of((data == null || data.isEmpty()) ? devicDataTrendQueryParam.getDevId() : data.get(0).getPid()).collect(Collectors.toList())).getData();
        //根据lineId获取监测点pt、ct变比
        CsLinePO linePo = csLineFeignClient.queryLineById(Collections.singletonList(devicDataTrendQueryParam.getLineId())).getData().get(0);
        List<CsDataSet> csDataSetList = dataSetFeignClient.getDataSetBySetIds(Stream.of(linePo.getDataSetId()).collect(Collectors.toList())).getData();
        if(CollUtil.isEmpty(csDataSetList) || StrUtil.isBlank(csDataSetList.get(0).getDataLevel())){
            throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
        }
        devicDataTrendQueryParam.getStatisticalParams().forEach(temp->{
            CommonQueryParam commonQueryParam = new CommonQueryParam();
            commonQueryParam.setLineId(devicDataTrendQueryParam.getLineId());
            commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(temp.getClassId()));
            commonQueryParam.setColumnName(temp.getName());
            commonQueryParam.setPhasic(temp.getPhase());
            commonQueryParam.setStartTime( devicDataTrendQueryParam.getStartTime() + " 00:00:00");
            commonQueryParam.setEndTime(devicDataTrendQueryParam.getEndTime() + " 23:59:59");
            commonQueryParam.setDataType(temp.getStatMethod());
            commonQueryParam.setProcess(data1.get(0).getProcess()+"");
            commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(devicDataTrendQueryParam.getLineId()));
            EleEpdPqd epdPqd = epdFeignClient.selectByIds(Collections.singletonList(temp.getDataId())).getData().get(0);
            List<StatisticalDataDTO> deviceRtData = commonService.getDeviceRtDataByTime(Stream.of(commonQueryParam).collect(Collectors.toList()));
            List<ThdDataVO> collect1 = deviceRtData.stream().map(statisticalDataDTO -> {
                ThdDataVO vo = new ThdDataVO();
                vo.setLineId(statisticalDataDTO.getLineId());
                vo.setPhase(statisticalDataDTO.getPhaseType());
                vo.setTime(statisticalDataDTO.getTime());
                vo.setStatMethod(statisticalDataDTO.getValueType());
                //判断监测点类型 针对治理设备 模块数据是一次值、电能质量设备是二次值
                double value;
                if (ObjectUtil.isNotNull(epdPqd.getPrimaryFormula()) && !Objects.equals(devicDataTrendQueryParam.getDataLevel(),csDataSetList.get(0).getDataLevel())) {
                    if("Primary".equals(csDataSetList.get(0).getDataLevel())){
                        value = DataChangeUtil.primaryToSecondary(epdPqd.getPrimaryFormula(), statisticalDataDTO.getValue(), linePo.getPtRatio(), linePo.getCtRatio());
                    }else {
                        value = DataChangeUtil.secondaryToPrimary(epdPqd.getPrimaryFormula(), statisticalDataDTO.getValue(), linePo.getPtRatio(), linePo.getCtRatio());
                    }
                } else {
                    value= statisticalDataDTO.getValue();
                }
                if (changePower(epdPqd.getShowName())) {
                    value =  value/1000;
                }
                vo.setStatisticalData(BigDecimal.valueOf(value).setScale(4, RoundingMode.HALF_UP).doubleValue());

                vo.setStatisticalIndex(temp.getDataId());
                vo.setStatisticalName(temp.getName());

                if (changePower(epdPqd.getShowName())) {
                    vo.setUnit("k" + temp.getUnit());
                } else {
                    vo.setUnit(temp.getUnit());
                }
                vo.setAnotherName(temp.getAnotherName());
                return vo;
            }).collect(Collectors.toList());
            result.add(collect1);
        });
        return result;
    }



    //判断指标是否需要转换
    public boolean changePower(String name) {
        if(name.contains("相角")) {
            return false;
        }
        return POWER_LIST.stream()
                .anyMatch(name::contains);
    }


}
