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

import com.chinaitop.depot.intelligent.basicdata.model.TCcinfo;
import com.chinaitop.depot.intelligent.basicdata.model.TWarningThreshold;
import com.chinaitop.depot.intelligent.basicdata.service.WarningThresholdService;
import com.chinaitop.depot.intelligent.grainsituation.mapper.TCcvalueMapper;
import com.chinaitop.depot.intelligent.grainsituation.mapper.TWarningThresholdHistoryMapper;
import com.chinaitop.depot.intelligent.grainsituation.model.TCcdata;
import com.chinaitop.depot.intelligent.grainsituation.model.TCcvalue;
import com.chinaitop.depot.intelligent.grainsituation.model.TWarningThresholdHistory;
import com.chinaitop.depot.intelligent.grainsituation.service.InsectPestDetectionService;
import com.chinaitop.depot.intelligent.pushs.service.InsectPushsService;
import com.chinaitop.depot.intelligent.utils.*;
import com.google.common.collect.Lists;
import com.unissoft.model.ResponseEntity;
import com.unissoft.model.TypeEnum;

import org.apache.commons.lang.ObjectUtils;
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.*;
import java.util.stream.Collectors;

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

    @Resource
    private TCcvalueMapper tCcvalueMapper;

    @Resource
    private InsectPestDetectionService insectPestDetectionService;

    @Resource
    WarningThresholdService warningThresholdService;

    @Resource
    TWarningThresholdHistoryMapper tWarningThresholdHistoryMapper;

    @Resource
    private UuidUtils uuidUtils;

    @Resource
    private WarningMessage warningMessage;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseEntity uploadInsectPestData(String dataSource, String insectPestData) {
        if (!VerificationSourceUtils.verificationSource(dataSource)) {
            return ResponseEntity.failed("验证失败！");
        }
        //数据来源
        String dataSource2 = VerificationSourceUtils.sourceMap().get(dataSource);
        logger.info(insectPestData);
        try {
            if (StringUtils.isNotBlank(insectPestData)) {
                ArrayList<TCcdata> tCcdatas = Lists.newArrayList();
                ArrayList<Object> ts = JsonToObjectUtils.jsonToObjects(insectPestData, TCcdata.class);
                ts.forEach(obj -> {
                    TCcdata tCcdata = (TCcdata) obj;
                    tCcdatas.add(tCcdata);
                });
                List<String> cDcsCodes = tCcdatas.stream().map(TCcdata::getvCcCode).collect(Collectors.toList());
                List<Date> cTimes = tCcdatas.stream().map(TCcdata::getvUpdateTime).collect(Collectors.toList());
                List<Integer> tdhs = tCcdatas.stream().map(TCcdata::getiTdh).collect(Collectors.toList());
                //校验重复数据
                List<TCcdata> byCodeAndTimes = insectPestDetectionService.getByCodeAndTimes(cDcsCodes, cTimes, tdhs);
                if (byCodeAndTimes != null && byCodeAndTimes.size() > 0) {
                    return ResponseEntity.failed("上传数据重复！");
                }

                //获取测虫设备code
                if (tCcdatas.size() > 0) {
                    ArrayList<TCcvalue> tCcvalues = Lists.newArrayList();
                    //报警数据
                    ArrayList<TWarningThresholdHistory> tWarningThresholdHistorieList = Lists.newArrayList();
                    Set<String> cccodes = tCcdatas.stream().map(TCcdata::getvCcCode).collect(Collectors.toSet());
                    List<TCcinfo> TCcinfos = insectPestDetectionService.getByCode(Lists.newArrayList(cccodes));
                    if (TCcinfos.size() == 0) {
                        return ResponseEntity.failed("没有该设备code！");
                    }
                    Map<String, List<TCcdata>> codeTCcdates = tCcdatas.stream().collect(Collectors.groupingBy(tCcdata -> tCcdata.getvCcCode()));
                    for (Map.Entry<String, List<TCcdata>> entry : codeTCcdates.entrySet()) {
                        TCcvalue cv = new TCcvalue();
                        String key = entry.getKey();
                        List<TCcdata> values = entry.getValue();
                        TCcinfo tCcinfo1 = TCcinfos.stream().filter(tCcinfo -> tCcinfo.getVdevcode().equals(key)).findFirst().get();
                        String orgId = tCcinfo1.getOrgId();
                        String vcfcode = tCcinfo1.getVcfcode();
                        values.forEach(v -> {
                            v.setId(uuidUtils.getCodeId(orgId, "t_ccdata"));
                            v.setOrgId(orgId);
                            v.setDataSource(dataSource2);
                            TWarningThreshold threshold = warningThresholdService.getByCfCodeAndwName(vcfcode, 0, "6973", "6989");
                            if (threshold != null) {
                                BigDecimal threshold1 = threshold.getThreshold();
                                BigDecimal bigDecimal = new BigDecimal(v.getiValue().toString());
                                if (bigDecimal.compareTo(threshold1) == 1) {
                                    String tid = uuidUtils.getCodeId(orgId, "t_warning_threshold_history");
                                    String desc = v.getiTdh()+"通道测虫(" + bigDecimal + ")只高于阈值(" + threshold1.intValue() + ")";
                                    TWarningThresholdHistory tt = warningMessage.saveWThreshold(tid, vcfcode, threshold, bigDecimal, threshold1, v.getvUpdateTime(), desc, dataSource2, "1", "0");
                                    tWarningThresholdHistorieList.add(tt);
                                }
                            }
                        });
                        
                        cv.setId(uuidUtils.getCodeId(orgId, "t_ccvalue"));
                        cv.setOrgId(orgId);
                        cv.setDataSource(dataSource2);
                        cv.setvCcCode(key);
                        cv.setvCfCode(vcfcode);
                        cv.setzZdCode(tCcinfo1.getSitecode());
                        cv.setvMax(values.stream().mapToInt(TCcdata::getiValue).max().getAsInt());
                        cv.setvMin(values.stream().mapToInt(TCcdata::getiValue).min().getAsInt());
                        BigDecimal avg = new BigDecimal(values.stream().mapToInt(TCcdata::getiValue).average().getAsDouble());
                        cv.setvAvg(avg);
                        Date date = values.stream().map(TCcdata::getvUpdateTime).distinct().collect(Collectors.toList()).get(0);
                        cv.setvUpdateTime(date);

                        Map<String,Object> map = new HashMap<String, Object>();
                        map.put("orgId", orgId);
                        map.put("vcfcode", vcfcode);
                        map.put("updateTime", date);
                        List<Map<String,Object>> jcdList = insectPestDetectionService.getJcd(map);
                        String jcd = ObjectUtils.toString(jcdList.get(0).get("jcd"));
                        cv.setHcjcdh(jcd);
                        
                        tCcvalues.add(cv);
                    }
                    if (tCcdatas.size() > 0) {
                        insectPestDetectionService.insertBatch(tCcdatas);
                    }
                    if (tCcvalues.size() > 0) {
                        tCcvalueMapper.insertBatch(tCcvalues);
                    }
                    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();
    }
}
