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

import cn.com.victorysoft.business.condition.entity.WaterRealtime;
import cn.com.victorysoft.business.util.DateUtils;
import cn.com.victorysoft.business.util.StringUtils;
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.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    @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<WaterRealtime> getData(String wellname, Date startTime, Date endTime) {
        List<WaterRealtime> list = new ArrayList<>();
        if (StringUtils.isEmpty(wellname)) {
            return list;
        }
        String url = realtimeRemoteUrl + "getSjSs.json";
        ResponseEntity<String> result = null;
        boolean success = false;
        try{
            result = restTemplate.postForEntity(url, buildPostWellBody(wellname, startTime, endTime), 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());
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = data.getJSONObject(i);
            WaterRealtime bean = new WaterRealtime();
            bean.setJh(getString(jsonObject, "JH"));
            bean.setCjsj(getDate(jsonObject, "CJSJ"));
            bean.setRksj(getDate(jsonObject, "RKSJ"));
            bean.setFmzt1(getDouble(jsonObject, "FMZT1"));
            bean.setGxyl(getDouble(jsonObject, "GXYL1"));
            bean.setKd1(getDouble(jsonObject, "KD1"));
            bean.setLjll1(getDouble(jsonObject, "LJLL1"));
            bean.setPzsl1(getDouble(jsonObject, "PZSL1"));
            bean.setSsll1(getDouble(jsonObject, "SSLL1"));
            bean.setZsyl1(getDouble(jsonObject, "ZSYL1"));
            list.add(bean);
        }
        return list;
    }

    @SneakyThrows
    private JSONObject buildPostWellBody(String wellname, 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("jh.s", wellname);
        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;
    }

}
