package com.huimv.environ.eco.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.environ.eco.entity.EcoDeviceFlow;
import com.huimv.environ.eco.entity.dto.EcoDeviceDto;
import com.huimv.environ.eco.entity.dto.LastFlowDto;
import com.huimv.environ.eco.mapper.EcoDeviceFlowMapper;
import com.huimv.environ.eco.service.EcoDeviceFlowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.environ.env.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zn
 * @since 2022-11-09
 */
@Slf4j
@Service
public class EcoDeviceFlowServiceImpl extends ServiceImpl<EcoDeviceFlowMapper, EcoDeviceFlow> implements EcoDeviceFlowService {
    @Autowired
    private EcoDeviceFlowMapper ecoDeviceFlowMapper;
    @Value("${dry.search.before.minute}")
    private String BEFORE_MINUTE;
    @Value("${dry.search.after.minute}")
    private String AFTER_MINUTE;
    @Value("${url.threshold.service}")
    private String URL_THRESHOLD_SERVICE;
    //最后一条记录的查询范围（分钟）
    @Value("${dry.last.minute}")
    private String LAST_MINUTE;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Result getLastFlow(Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        //栋舍id
        String pigpenId = paramsMap.get("pigpenId");
        if(StringUtils.isNotBlank(pigpenId)){
            //查询栋舍下单元
            return new Result(ResultCode.SUCCESS, ecoDeviceFlowMapper.getLastFlowByPigpenId(pigpenId,farmId));
        }else{
            return new Result(ResultCode.SUCCESS, ecoDeviceFlowMapper.getLastFlow(farmId));
        }
    }

//    public Result getLastFlow(Map<String, String> paramsMap) {
//        String farmId = paramsMap.get("farmId");
//        return new Result(ResultCode.SUCCESS, ecoDeviceFlowMapper.getLastFlow(farmId));
//    }

    @Override
    public void save(JSONObject dataJo, Date todayTime) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        EcoDeviceFlow ecoDeviceFlow = new EcoDeviceFlow();
        ecoDeviceFlow.setDeviceCode(dataJo.getString("deviceKey"));
        ecoDeviceFlow.setDeviceName(dataJo.getString("deviceName"));
        ecoDeviceFlow.setDeviceStatus(Integer.parseInt(dataJo.getString("deviceStatus")));
        ecoDeviceFlow.setDeviceOpen(dataJo.getBoolean("deviceDisabled"));
        //温/湿度数据
        JSONArray realTimeDataJa = dataJo.getJSONArray("realTimeData");
        JSONObject id1Jo = realTimeDataJa.getJSONObject(0);
        ecoDeviceFlow.setId1Name(id1Jo.getString("dataName"));
        //
        String id1Value = id1Jo.getString("dataValue");
        if (StringUtils.isBlank(id1Value)) {
            id1Value = "0";
        }
        System.out.println(dataJo.getString("deviceKey") +"____________>");
        if ("880601000003".equals(dataJo.getString("deviceKey"))){
            ecoDeviceFlow.setId1Value((new BigDecimal(id1Value).add(new BigDecimal(40))).toString());
        }else {
            ecoDeviceFlow.setId1Value(id1Value);
        }
        ecoDeviceFlow.setId1AlarmStatus(id1Jo.getBoolean("isAlarm"));
        ecoDeviceFlow.setId1AlarmMsg(id1Jo.getString("alarmMsg"));
        JSONObject id2Jo = realTimeDataJa.getJSONObject(1);
        ecoDeviceFlow.setId2Name(id2Jo.getString("dataName"));
        String id2Value = id2Jo.getString("dataValue");
        //
        if (StringUtils.isBlank(id2Value)) {
            id2Value = "0";
        }
        ecoDeviceFlow.setId2Value(id2Value);
        ecoDeviceFlow.setId2AlarmStatus(id2Jo.getBoolean("isAlarm"));
        ecoDeviceFlow.setId2AlarmMsg(id2Jo.getString("alarmMsg"));
        ecoDeviceFlow.setAddTime(todayTime);
        ecoDeviceFlowMapper.insert(ecoDeviceFlow);
    }


    @Override
    public Result listByRoom(HttpServletRequest request, Map<String, String> paramsMap) throws ParseException {
        String farmId = paramsMap.get("farmId");
        String unitId = paramsMap.get("unitId");
        String startDate = paramsMap.get("startDate");
        String endDate = paramsMap.get("endDate");
        String type = paramsMap.get("type");

        List<EcoDeviceDto> ecoDeviceDtos = null;
        //默认显示
        if (type == null) {
            unitId = "77";
            DateUtil dateUtil = new DateUtil();
            startDate = dateUtil.getTodayDate().toString();
            ecoDeviceDtos = ecoDeviceFlowMapper.listDayDevice(farmId, unitId);
        } else {

            //自定义查询
            if ("4".equals(type)) {
                ecoDeviceDtos = ecoDeviceFlowMapper.listDevice(farmId, unitId, startDate, endDate);
            }
            //今日查询
            else if ("3".equals(type)) {
                ecoDeviceDtos= ecoDeviceFlowMapper.listDayDevice(farmId, unitId);

            }
            //本周查询
            else if ("2".equals(type)) {
                ecoDeviceDtos = ecoDeviceFlowMapper.listWeekDevice(farmId, unitId);
            }
            //本月查询
            else if ("1".equals(type)) {
                ecoDeviceDtos = ecoDeviceFlowMapper.listMonthDevice(farmId, unitId);
            }
        }
        return new Result(ResultCode.SUCCESS, ecoDeviceDtos);
    }

    @Override
    public Result listDayDetails(HttpServletRequest request, Map<String, String> paramsMap) throws ParseException {
        String farmId = paramsMap.get("farmId");
        String deviceCode = paramsMap.get("deviceCode");
        String addTime = paramsMap.get("addTime");

        //读取高温阈值数据
        JSONObject thresholdJo = getThresholdURL(Integer.parseInt(farmId));
        System.out.println("调取牧场[" + farmId + "]服务获取阈值接口：" + thresholdJo);
        String dryDuration = "0";
        if(thresholdJo.getString("dryDuration") != null){
            //一次烘干持续时间（分钟）
            dryDuration = thresholdJo.getString("dryDuration");
        }
        System.out.println("dryDuration="+dryDuration);
        System.out.println("BEFORE_MINUTE="+BEFORE_MINUTE);
        System.out.println("AFTER_MINUTE="+AFTER_MINUTE);

        DateUtil dateUtil = new DateUtil();
        Date startDateTime = dateUtil.getDateBeforeMinute(addTime, Integer.parseInt(BEFORE_MINUTE));
        Date endDateTime = dateUtil.getDateAfterMinute(addTime, Integer.parseInt(dryDuration) + Integer.parseInt(AFTER_MINUTE));
        System.out.println("farmId=" + farmId);
        System.out.println("deviceCode=" + deviceCode);
        System.out.println("addTime=" + addTime);
        System.out.println("startDateTime = " + dateUtil.formatDateTime(startDateTime));
        System.out.println("endDateTime = " + dateUtil.formatDateTime(endDateTime));
        //查询时间范围：开始时间（startTime = beforeMinute + addTime）
        //查询时间范围：结束时间（endTime = addTime + duration + afterMinute）
        QueryWrapper<EcoDeviceFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_code", deviceCode);
        queryWrapper.between("add_time", startDateTime, endDateTime);
        queryWrapper.orderByAsc("add_time");
        List<EcoDeviceFlow> ecoDeviceFlowList = ecoDeviceFlowMapper.selectList(queryWrapper);
        List resultList = new ArrayList();
        for(EcoDeviceFlow ecoDeviceFlow:ecoDeviceFlowList){
            JSONObject ecoDeviceFlowJo = new JSONObject();
            ecoDeviceFlowJo.put("value",ecoDeviceFlow.getId1Value());
            ecoDeviceFlowJo.put("time",dateUtil.formatDateTime(ecoDeviceFlow.getAddTime()));
            resultList.add(ecoDeviceFlowJo);
        }
        return new Result(ResultCode.SUCCESS,resultList);
    }

    @Override
    public Result getLastFlowByUnitId(Map<String, String> paramsMap) {
        String unitId = paramsMap.get("unitId");
        LastFlowDto lastFlowByUnitId = ecoDeviceFlowMapper.getLastFlowByUnitId(unitId);
        return new Result(ResultCode.SUCCESS,lastFlowByUnitId);
    }

    @Override
    public Result getUnitLastFlow(Map<String, String> paramsMap) {
        String deviceCode = paramsMap.get("deviceCode");
        LastFlowDto lastUnitFlow = ecoDeviceFlowMapper.getUnitLastFlow(deviceCode);
        if (ObjectUtil.isEmpty(lastUnitFlow) ){
            lastUnitFlow = new LastFlowDto();
        }
        return new Result(ResultCode.SUCCESS,lastUnitFlow);
    }

    @Override
    public EcoDeviceFlow getLastDryDeviceFlow(String dryDeviceCode, String endTime) throws ParseException {
        DateUtil dateUtil = new DateUtil();
        System.out.println(" AA endTime="+endTime);
        Integer lastMinute = Integer.parseInt(LAST_MINUTE);
        log.info("计算最后一条记录时间间隔范围 lastMinute="+lastMinute);
        Date startTime = dateUtil.getDateBeforeMinute(endTime,lastMinute);
        log.info("读取最后一条烘干记录开始时间 "+dateUtil.formatDateTime(startTime));
        log.info("读取最后一条烘干记录结束时间 "+endTime);
        //
        List<EcoDeviceFlow> ecoDeviceFlowList = ecoDeviceFlowMapper.getLastDryDeviceFlow(dryDeviceCode,startTime,endTime);
        log.info("读取符合时间区间范围内的记录数量="+ecoDeviceFlowList.size());
        if (ecoDeviceFlowList.size()==0){
            return null;
        }else{
            return ecoDeviceFlowList.get(0);
        }
    }

//    @Override
//    public Result getFlowList(Map<String, String> paramsMap) {
//        String pigpenId = paramsMap.get("pigpenId");
//        return null;
//    }

    //获取阈值
    private JSONObject getThresholdURL(Integer farmId) {
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        HashMap<String, Object> map = new HashMap<>();
        map.put("farmId", farmId);
        HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<>(map, httpHeaders);
        //读取真实数据
//        String remoteUrl = "http://192.168.1.67:8010/produce/threshold/getThresholdByFarmId";
        System.out.println("URL_THRESHOLD_SERVICE=" + URL_THRESHOLD_SERVICE);
        ResponseEntity<String> entity = restTemplate.postForEntity(URL_THRESHOLD_SERVICE, objectHttpEntity, String.class);
        JSONObject thresholdJo = JSONObject.parseObject(entity.getBody());
        System.out.println("thresholdJo>>>>>>>>>>>>>>>"+thresholdJo);
        if (thresholdJo.getInteger("code") != 10000) {
            return null;
        }
        return thresholdJo.getJSONObject("data");
    }
}
