package com.chinaitop.depot.intelligent.pushs.service.impl;

import com.chinaitop.depot.intelligent.basicdata.model.TDcsqtinfo;
import com.chinaitop.depot.intelligent.basicdata.model.TQtdevinfo;
import com.chinaitop.depot.intelligent.basicdata.model.TWarningThreshold;
import com.chinaitop.depot.intelligent.basicdata.service.GaseousService;
import com.chinaitop.depot.intelligent.basicdata.service.WarningThresholdService;
import com.chinaitop.depot.intelligent.grainsituation.mapper.TQtdevinfoValueMapper;
import com.chinaitop.depot.intelligent.grainsituation.mapper.TWarningThresholdHistoryMapper;
import com.chinaitop.depot.intelligent.grainsituation.model.TDcsdata;
import com.chinaitop.depot.intelligent.grainsituation.model.TQtdevinfoValue;
import com.chinaitop.depot.intelligent.grainsituation.model.TWarningThresholdHistory;
import com.chinaitop.depot.intelligent.grainsituation.service.GasDetectionService;
import com.chinaitop.depot.intelligent.pushs.controller.PushsController;
import com.chinaitop.depot.intelligent.pushs.service.GasPushsService;
import com.chinaitop.depot.intelligent.utils.DateUtils;
import com.chinaitop.depot.intelligent.utils.JsonToObjectUtils;
import com.chinaitop.depot.intelligent.utils.UuidUtils;
import com.chinaitop.depot.intelligent.utils.VerificationSourceUtils;
import com.google.common.collect.Lists;
import com.unissoft.model.ResponseEntity;
import com.unissoft.model.TypeEnum;
import com.unissoft.webservice.GassService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings("all")
public class GasPushsServiceImpl implements GasPushsService {
    final static Logger logger = LoggerFactory.getLogger(GasPushsServiceImpl.class);

    @Resource
    private TQtdevinfoValueMapper tQtdevinfoValueMapper;

    @Resource
    private GasDetectionService gasDetectionService;

    @Resource
    private GaseousService gaseousService;

    @Resource
    private WarningThresholdService warningThresholdService;

    @Resource
    private TWarningThresholdHistoryMapper tWarningThresholdHistoryMapper;

    @Resource
    private UuidUtils uuidUtils;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseEntity uploadGasData(String dataSource, String gasData, String isMany) {
        if (!VerificationSourceUtils.verificationSource(dataSource)) {
            return ResponseEntity.failed("验证失败！");
        }
        //数据来源
        String dataSource2 = VerificationSourceUtils.sourceMap().get(dataSource);
        logger.info(gasData);
        try {
            if (StringUtils.isNotBlank(gasData)) {
                ArrayList<TQtdevinfoValue> tQtdevinfoValues = Lists.newArrayList();
                ArrayList<TDcsdata> tDcsdatas = Lists.newArrayList();
                ArrayList<Object> ts = JsonToObjectUtils.jsonToObjects(gasData, TDcsdata.class);
                ts.forEach(obj -> {
                    TDcsdata tCcinfo = (TDcsdata) obj;
                    tDcsdatas.add(tCcinfo);
                });
                List<String> cDcsCodes = tDcsdatas.stream().map(TDcsdata::getvDcsCode).collect(Collectors.toList());
                List<Date> cTimes = tDcsdatas.stream().map(TDcsdata::getvUpdateTime).collect(Collectors.toList());
                //校验重复数据
                List<TDcsdata> byCodeAndTimes = gasDetectionService.getByCodeAndTimes(cDcsCodes, cTimes);
                if (byCodeAndTimes != null && byCodeAndTimes.size() > 0) {
                    return ResponseEntity.failed("上传数据重复！");
                }
                if (tDcsdatas.size() > 0) {
                    //报警数据
                    ArrayList<TWarningThresholdHistory> tWarningThresholdHistorieList = Lists.newArrayList();
                    //获取仓房信息
                    List<TQtdevinfo> byCode = null;
                    List<TDcsqtinfo> byCodeMany = null;
                    if (StringUtils.isBlank(isMany)) {
                        byCode = gasDetectionService.getByCode(cDcsCodes);
                        if (byCode.size() == 0) {
                            return ResponseEntity.failed("没有该设备code！");
                        }
                    } else {
                        byCodeMany = gaseousService.getByCode(cDcsCodes);
                        if (byCodeMany.size() == 0) {
                            return ResponseEntity.failed("没有该设备code！");
                        }
                    }
                    Map<String, Map<String, List<TDcsdata>>> codeTDcsdatas = tDcsdatas.stream().collect(Collectors.groupingBy(tDcsdata -> tDcsdata.getvDcsCode(), Collectors.groupingBy(tDcsdata -> tDcsdata.getvDevKindCode())));
                   /* String orgId = "";
                    String vcfcode = "";*/

                    for (Map.Entry<String, Map<String, List<TDcsdata>>> entry : codeTDcsdatas.entrySet()) {
                        String desCode = entry.getKey();
                        Map<String, List<TDcsdata>> value = entry.getValue();
                        String org_id = "";
                        String vcfcode = "";
                        if (byCode != null) {
                            TQtdevinfo tQtdevinfo1 = byCode.stream().filter(tQtdevinfo -> tQtdevinfo.getVdevcode().equals(desCode)).findFirst().get();
                            org_id = tQtdevinfo1.getOrgId();
                            vcfcode = tQtdevinfo1.getVcfcode();
                        }
                        if (byCodeMany != null) {
                            TDcsqtinfo tDcsqtinfoMany = byCodeMany.stream().filter(tDcsqtinfo -> tDcsqtinfo.getvDcsCode().equals(desCode)).findFirst().get();
                            org_id = tDcsqtinfoMany.getOrgId();
                            vcfcode = tDcsqtinfoMany.getvCfCode();
                        }
                        String orgId = org_id;
                        //获取报警阈值信息 6971测气 6979二氧化碳 6980氧气 6981磷化氢
                        TWarningThreshold thresholdph3 = warningThresholdService.getByCfCodeAndwName(vcfcode, 0, "6971", "6981");
                        TWarningThreshold thresholdco2 = warningThresholdService.getByCfCodeAndwName(vcfcode, 0, "6971", "6980");
                        TWarningThreshold thresholdo2 = warningThresholdService.getByCfCodeAndwName(vcfcode, 0, "6971", "6979");
                        for (Map.Entry<String, List<TDcsdata>> en : value.entrySet()) {
                            TQtdevinfoValue tQtdevinfoValue = new TQtdevinfoValue();
                            String devKindCode = en.getKey();
                            List<TDcsdata> value1 = en.getValue();
                            if (value1.size() > 0) {
                                value1.forEach(t -> {
                                    t.setId(uuidUtils.getCodeId(orgId, "t_dcsdata"));
                                    t.setOrgId(orgId);
                                    t.setDataSource(dataSource2);
                                });
                                Date date = value1.stream().map(TDcsdata::getvUpdateTime).distinct().collect(Collectors.toList()).get(0);
                                BigDecimal reduce = value1.stream().map(TDcsdata::getiValue).reduce(BigDecimal.ZERO, BigDecimal::add);
                                double rSum = reduce.doubleValue();
                                double avg_ = rSum / value1.size();
                                BigDecimal avg = new BigDecimal(avg_);
                                avg = avg.setScale(2, BigDecimal.ROUND_DOWN);
                                tQtdevinfoValue.setCpoAvg(avg);
                                //获取报警阈值信息
                                if (thresholdph3 != null) {
                                    BigDecimal threshold1 = thresholdph3.getThreshold();
                                    //-1 小于 0 等于 1 大于
                                    for (TDcsdata t : value1) {
                                        if (avg.compareTo(threshold1) == 1 && t.getvDevKindCode().equals("6965")) {
                                            TWarningThresholdHistory tt = saveWThreshold(vcfcode, thresholdph3, avg, threshold1, date, "整仓磷化氢", dataSource2);
                                            tWarningThresholdHistorieList.add(tt);
                                        }
                                    }
                                }
                                if (thresholdco2 != null) {
                                    BigDecimal threshold1 = thresholdco2.getThreshold();
                                    //-1 小于 0 等于 1 大于
                                    for (TDcsdata t : value1) {
                                        if (avg.compareTo(threshold1) == 1 && t.getvDevKindCode().equals("6964")) {
                                            TWarningThresholdHistory tt = saveWThreshold(vcfcode, thresholdco2, avg, threshold1, date, "整仓氧气", dataSource2);
                                            tWarningThresholdHistorieList.add(tt);
                                        }
                                    }
                                }
                                if (thresholdo2 != null) {
                                    BigDecimal threshold1 = thresholdo2.getThreshold();
                                    //-1 小于 0 等于 1 大于
                                    for (TDcsdata t : value1) {
                                        if (avg.compareTo(threshold1) == 1 && t.getvDevKindCode().equals("6962")) {
                                            TWarningThresholdHistory tt = saveWThreshold(vcfcode, thresholdo2, avg, threshold1, date, "整仓二氧化碳", dataSource2);
                                            tWarningThresholdHistorieList.add(tt);
                                        }
                                    }
                                }
                            }
                            tQtdevinfoValue.setId(uuidUtils.getCodeId(orgId, "t_qtdevinfo_value"));
                            tQtdevinfoValue.setvCfCode(vcfcode);
                            tQtdevinfoValue.setvDevCode(desCode);
                            tQtdevinfoValue.setvDevKindCode(devKindCode);
                            tQtdevinfoValue.setvValueTime(value1.stream().map(TDcsdata::getvUpdateTime).distinct().collect(Collectors.toList()).get(0));
                            tQtdevinfoValue.setOrgId(orgId);
                            tQtdevinfoValue.setDataSource(dataSource2);
                            tQtdevinfoValues.add(tQtdevinfoValue);
                        }
                    }
                    if (tDcsdatas.size() > 0) {
                        gasDetectionService.insertBatch(tDcsdatas);
                    }
                    if (tQtdevinfoValues.size() > 0) {
                        tQtdevinfoValueMapper.insertBatch(tQtdevinfoValues);
                    }
                    if (tWarningThresholdHistorieList.size() > 0) {
                        tWarningThresholdHistoryMapper.insertBatch(tWarningThresholdHistorieList);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            throw new RuntimeException(TypeEnum.ED.getCode() + "  " + TypeEnum.ED.getDesc());
        }
        return ResponseEntity.ok();
    }

    private TWarningThresholdHistory saveWThreshold(String cfCdoe, TWarningThreshold threshold, BigDecimal avg, BigDecimal threshold1, Date date, String desc, String dataSource) {
        TWarningThresholdHistory tt = new TWarningThresholdHistory();
        tt.setId(uuidUtils.getCodeId(threshold.getOrgId(), "t_warning_threshold_history"));
        tt.setOrgId(threshold.getOrgId());
        tt.setvCfCode(cfCdoe);
        tt.setwModule(threshold.getwModule());
        tt.setwName(threshold.getwName());
        tt.setThreshold(avg);
        tt.setwThreshold(threshold1);
        tt.setwTime(date);
        tt.setwUpdateTime(DateUtils.getDate());
        tt.setDataSource(dataSource);
        tt.setwRemark(desc + "(" + avg + ")高于阈值(" + threshold1 + ")");
        return tt;
    }

}
