package cn.cecep.talroad.service.strategy.support.gt;

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.BasDeviceConfig;
import cn.cecep.talroad.domain.MonDevReal;
import cn.cecep.talroad.domain.STaskYieldTrend;
import cn.cecep.talroad.enums.DeviceParamTypeEnum;
import cn.cecep.talroad.enums.ProblemTypeEnum;
import cn.cecep.talroad.enums.YieldTypeEnum;
import cn.cecep.talroad.service.IBasDeviceConfigService;
import cn.cecep.talroad.service.IBasDeviceParamService;
import cn.cecep.talroad.vo.BasDeviceParamVo;
import cn.cecep.talroad.vo.FactoryDeviceVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: cjh
 * @Date: 2023-03-29 18:32
 * @Class: GtJlCountAdapter
 * @Deseription: 任务调度-每小时统计一次装煤次数，推焦次数，并计算产量
 * @Version V1.0
 */
@Slf4j
@Service("GTJLJL")
public class GtJlCountAdapter extends GtYieldStrategyAdapter {


    @Autowired
    private IBasDeviceConfigService basDeviceConfigService;

    @Override
    protected void doProcessYieldData(FactoryDeviceVo vo, List<MonDevReal> currList, List<MonDevReal> oldList, Date lastHour, boolean flag) {
        List<STaskYieldTrend> yieldList = new ArrayList<>();
        if(currList!=null&&currList.size()>0){

            AtomicReference<String> last = new AtomicReference<>();
            last.set(currList.stream().findFirst().get().getZmTime());
            AtomicInteger it  = new AtomicInteger();
            currList.forEach(real ->{
                if(StringUtils.isNotEmpty(real.getZmTime())){
                    if(Double.valueOf(0).compareTo(Double.valueOf(last.get()))==0&&Double.valueOf(1).compareTo(Double.valueOf(real.getZmTime()))==0){
                        it.getAndIncrement();
                    }
                    last.set(real.getZmTime());
                }
            });

            AtomicReference<String> lastTm = new AtomicReference<>();
            lastTm.set(currList.stream().findFirst().get().getTmTime());
            AtomicInteger itTm  = new AtomicInteger();
            currList.forEach(real ->{
                if(StringUtils.isNotEmpty(real.getTmTime())){
                    if(Double.valueOf(0).compareTo(Double.valueOf(lastTm.get()))==0&&Double.valueOf(1).compareTo(Double.valueOf(real.getTmTime()))==0){
                        itTm.getAndIncrement();
                    }
                    lastTm.set(real.getTmTime());
                }
            });


            long tmcs = itTm.get();
            long zmcs = it.get();

            //根据企业、设备编号、时间查询表里是否存在分析结果，存在则更新装煤次数、推焦次数，不存在则保存
            Date analyseTime = DateUtils.parseFormatDate("yyyy-MM-dd HH", lastHour);
            // 保存装煤次数、推焦次数
            super.doSaveAnalysisCoal(vo, zmcs, tmcs, analyseTime);

            BigDecimal cl = new BigDecimal(0);
            // 炭化室有效容积
            AtomicReference<Double> yxrj = new AtomicReference<>(0d);
            AtomicReference<String> jlType = new AtomicReference<>("");

            QueryWrapper<BasDeviceConfig> configQueryWrapper = new QueryWrapper<>();
            configQueryWrapper.eq("factory_id", vo.getFactoryId());
            configQueryWrapper.eq("device_id", vo.getDeviceId());
            configQueryWrapper.eq("industry", vo.getIndustry());
            configQueryWrapper.eq("device_type", vo.getDeviceType());
            List<BasDeviceConfig> configList = basDeviceConfigService.list(configQueryWrapper);
            //遍历配置查询炭化室有效容积 和焦炉类型
            if (configList != null && configList.size() > 0) {
                configList.forEach(p -> {
                    // 判断是否炭化室有效容积
                    if (DeviceParamTypeEnum.TH_TYPE.getCode()
                        .equalsIgnoreCase(p.getParamCode())) {
                        yxrj.set(Double.valueOf(p.getNormalValue()));
                    } else if (DeviceParamTypeEnum.JL_TYPE.getCode()
                        .equalsIgnoreCase(p.getParamCode())) {
                        jlType.set(p.getNormalValue());
                    }
                });
            }
            // 焦炉类型不为空、炭化室有效容积不为空
            if (StringUtils.isNotEmpty(jlType.get()) && yxrj.get() > 0) {
                // 焦炉产量公式，1:顶装焦炉 2：侧装焦炉
                if ("1".equals(jlType.get())) {
                    cl = new BigDecimal(yxrj.get()).multiply(new BigDecimal(0.75))
                        .multiply(new BigDecimal(0.8)).multiply(new BigDecimal(tmcs))
                        .setScale(2,
                            RoundingMode.HALF_UP);
                } else if ("2".equals(jlType.get())) {
                    cl = new BigDecimal(yxrj.get()).multiply(new BigDecimal(0.8))
                        .multiply(new BigDecimal(tmcs)).setScale(2,
                            RoundingMode.HALF_UP);
                }
                // 保存钢铁焦炉产量
                super.doSaveAnalysisCokeData(vo, tmcs, analyseTime, cl, yxrj);

                // 保存钢铁焦炉产量趋势数据
                STaskYieldTrend clYield = super.doBuildTrenData(vo.getFactoryId(), vo.getDeviceId(),YieldTypeEnum.GT_002,lastHour,cl,flag);
                yieldList.add(clYield);
            }
            // 推焦次数趋势数据
            STaskYieldTrend tmYield = super.doBuildTrenData(vo.getFactoryId(), vo.getDeviceId(),YieldTypeEnum.GT_007,lastHour,new BigDecimal(tmcs),flag);
            yieldList.add(tmYield);

            // 装煤次数趋势
            STaskYieldTrend zmYield = super.doBuildTrenData(vo.getFactoryId(), vo.getDeviceId(),YieldTypeEnum.GT_006,lastHour,new BigDecimal(zmcs),flag);
            yieldList.add(zmYield);
        }
        // 批量保存更新
        super.doSaveBatchYieldTrendData(yieldList);
        // 调用公共处理方法，布袋除尘器，压差是否频繁超高报警分析
        try {
            super.doProcessPressData(vo,currList,lastHour);
        } catch (Exception e) {
            log.error("布袋除尘器，压差是否频繁超高报警分析异常"+e.getMessage());
        }

    }

}
