package com.njcn.csdevice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.service.CsLinePOService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csdevice.mapper.CsDevCapacityPOMapper;
import com.njcn.csdevice.pojo.po.CsDevCapacityPO;
import com.njcn.csdevice.service.CsDevCapacityPOService;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2023/9/27  10:29【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class CsDevCapacityPOServiceImpl extends ServiceImpl<CsDevCapacityPOMapper, CsDevCapacityPO> implements CsDevCapacityPOService{

    private final CsLinePOService csLinePOService;
    private final DicDataFeignClient dicDataFeignClient;
    private final DecimalFormat df = new DecimalFormat("#0.000");

    @Override
    public void addList(List<CsDevCapacityPO> list) {
        String line = list.get(0).getLineId();
        LambdaQueryWrapper<CsDevCapacityPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CsDevCapacityPO::getLineId,line);
        this.remove(lambdaQueryWrapper);
        this.saveBatch(list);
    }

    @Override
    public Double getDevCapacity(String id) {
        List<CsLinePO> csLinePOS = csLinePOService.queryByDevId(id);

        String areaId =  dicDataFeignClient.getDicDataByCode(DicDataEnum.OUTPUT_SIDE.getCode()).getData().getId();

        Optional.ofNullable(csLinePOS).orElseThrow(()-> new BusinessException(AlgorithmResponseEnum.LINE_DATA_ERROR));
        List<CsLinePO> collect1 = csLinePOS.stream().filter(temp -> Objects.equals(areaId, temp.getPosition())).collect(Collectors.toList());
        /*治理侧监测点*/
        CsLinePO csLinePO = collect1.get(0);
        CsDevCapacityPO one = this.lambdaQuery().eq(CsDevCapacityPO::getLineId, csLinePO.getLineId()).eq(CsDevCapacityPO::getCldid, 0).one();
//        Optional.ofNullable(one).orElseThrow(()-> new BusinessException(AlgorithmResponseEnum.DATA_MISSING));
        if(Objects.isNull(one)){
            return 0.0;
        }
        return Double.valueOf(df.format(one.getCapacity()));
    }
}
