package cn.com.victorysoft.business.indicator.service;

import cn.com.victorysoft.business.indicator.entity.PumpRealtime;
import cn.com.victorysoft.business.util.DateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 水井实时数据服务
 */
@Slf4j
@Service
public class PumpRealtimeService {

    @Value("${realtime.remote.url}")
    private String realtimeRemoteUrl;
    @Value("${realtime.remote.username}")
    private String realtimeRemoteUsername;
    @Value("${realtime.remote.password}")
    private String realtimeRemotePassword;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 注水泵数据
     */
    @Transactional
    public List<PumpRealtime> getData(String pumpId, Date startTime, Date endTime) {
        List<PumpRealtime> list = new ArrayList<>();
        // 获取当前排量
        String url = realtimeRemoteUrl + "getDqBeng.json";
        ResponseEntity<String> result = null;
        boolean success = false;
        try{
            result = restTemplate.postForEntity(url, buildDevicePostBody(pumpId), String.class);
            success = result.getStatusCodeValue() == 200;
        }catch (Exception e) {
            log.error("注水泵当前数据获取异常", e);
        }
        if (result == null || !success) return list;
        log.info("注水泵实时数据接口返回结果：{}", result);
        JSONArray data = JSONArray.fromObject(result.getBody());
        if (data == null || data.size() == 0) return list;

        JSONObject jsonObject = data.getJSONObject(0);
        // 排量h
        Double volumeHour = getDouble(jsonObject, "LLJ_SSLL");
        if (volumeHour == null) {
            return list;
        }
        url = realtimeRemoteUrl + "getSsBeng.json";
        result = null;
        success = false;
        try{
            result = restTemplate.postForEntity(url, buildDeviceListBody(pumpId, startTime, endTime), String.class);
            success = result.getStatusCodeValue() == 200;
        }catch (Exception e) {
            log.error("注水泵实时数据获取异常", e);
        }
        if (result == null || !success) return list;
        log.info("注水泵实时数据接口返回结果：{}", result);
        data = JSONArray.fromObject(result.getBody());
        for (int i = 0; i < data.size(); i++) {
            jsonObject = data.getJSONObject(i);
            PumpRealtime bean = new PumpRealtime();
            bean.setSbbm(getString(jsonObject, "SBBM"));
            bean.setCjsj(getDate(jsonObject, "CJSJ"));
            bean.setCkyl(getDouble(jsonObject, "CKYL"));
            bean.setJkyl(getDouble(jsonObject, "JKYL"));
            bean.setSsll(volumeHour);
            if (bean.getCkyl() != null && bean.getJkyl() != null && bean.getSsll() != null) {
                double yxgl = (1000 * bean.getSsll() * (bean.getCkyl() - bean.getJkyl()) * 100) / 3600 * 102;
                BigDecimal bg = new BigDecimal(yxgl);
                yxgl = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                bean.setYxgl(yxgl);
            }
            list.add(bean);
        }
        return list;
    }

    private JSONObject buildDevicePostBody(String deviceCode) {
        JSONObject jsonParam = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("username", realtimeRemoteUsername);
        head.put("password", realtimeRemotePassword);
        head.put("sbbm.s", deviceCode);
        jsonParam.put("head", head);
        jsonParam.put("body", new ArrayList<>(0));
        return jsonParam;
    }

    @SneakyThrows
    private JSONObject buildDeviceListBody(String pumpId, Date startTime, Date endTime) {
        JSONObject jsonParam = new JSONObject();
        JSONObject head = new JSONObject();
        head.put("username", realtimeRemoteUsername);
        head.put("password", realtimeRemotePassword);
        head.put("startDate.t", DateUtils.formatTime(startTime));
        head.put("endDate.t", DateUtils.formatTime(endTime));
        head.put("sbbm.s", pumpId);
        jsonParam.put("head", head);
        jsonParam.put("body", new ArrayList<>(0));
        return jsonParam;
    }
    
    private String getString(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            return jsonObject.getString( key);
        }
        return null;
    }
    private Double getDouble(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            return jsonObject.getDouble(key);
        }
        return null;
    }
    private Date getDate(JSONObject jsonObject, String key) {
        if (jsonObject.containsKey(key)) {
            try {
                String dateStr = getString(jsonObject, key);
                if (dateStr != null) {
                    return DateUtils.parseDate(dateStr, "yyyy-MM-dd HH:mm:ss");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
