package com.mvc.forwarmana;

import com.alibaba.fastjson.JSON;
import com.mvc.dao.TAireadMapper;
import com.mvc.entity.TAiread;
import com.mvc.entity.TAireadExample;
import com.mvc.model.TAireadModel;
import com.mvc.model.forwarding.CpszyResponseModel;
import com.mvc.model.forwarding.DicForwarderModel;
import com.mvc.model.forwarding.TForwarderRecordsModel;
import com.mvc.service.forwarding.TForwarderRecordsService;
import com.mvc.utils.DateUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 昌平水资源科
 */
@Component
public class CpszyForwarder {
    private static Logger log = LoggerFactory.getLogger(CpszyForwarder.class);

    private static final String TAG_VALUE_START = "<InsertDaydataResult>";
    private static final String TAG_VALUE_END = "</InsertDaydataResult>";

    @Resource
    private TAireadMapper aireadMapper;

    @Resource
    private TForwarderRecordsService forwarderRecordsService;

    public void insertDayData(DicForwarderModel forwarderModel, TAireadModel aireadModel) {
        //如果未识别,resultValue == null 也要上报,根据资源科的建议进行(以下特殊处理,主要为了促进上报率) 2024-06-28 guozhao
        //if (aireadModel.getResultValue() == null) return;

        TForwarderRecordsModel record = new TForwarderRecordsModel(aireadModel);
        Date yesterdayDate = null;
        BigDecimal dailyWaterConsumption = BigDecimal.ZERO;

        try {
            String time = DateUtil.formateDate(aireadModel.getSampleTime(), "HHmm");
            if (!time.equals("0000")) {//非零点不处理
                return;
            }

            TAireadModel yesterdayModel = getYesterdayAireadModel(aireadModel);
            if (yesterdayModel == null) {
                yesterdayDate = DateUtil.getOtherDateByCurrentDate(aireadModel.getSampleTime(), -1);
            } else {
                yesterdayDate = yesterdayModel.getSampleTime();
            }

            /*if (yesterdayModel == null || yesterdayModel.getResultValue() == null) {//没有昨日数据
                return;
            }*/

            if (aireadModel.getResultValue() != null && yesterdayModel != null && yesterdayModel.getResultValue() != null) {
                dailyWaterConsumption = aireadModel.getResultValue().subtract(yesterdayModel.getResultValue());

                //做基本过滤,当从0跳数到5000+时,怀疑之前没在表上,不进行推送 2024-06-27 guozhao
                if (yesterdayModel.getResultValue().compareTo(BigDecimal.ZERO) == 0
                        && dailyWaterConsumption.abs().compareTo(new BigDecimal(5000)) > 0) {
                    dailyWaterConsumption = BigDecimal.ZERO;
                    log.warn("{}：[{}]特殊处理,0直跳5000+,上报用量为0", forwarderModel.getServerName(), aireadModel.getStationCode());
                /*log.warn("{}：[{}]日用量异常不上报;value:{}", forwarderModel.getServerName(), aireadModel.getStationCode(), dailyWaterConsumption);
                return;*/
                }
            }//else --相当于无识别值上报0
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 设置请求 URL
            //HttpPost httpPost = new HttpPost("http://111.207.70.133:8009/cpdata/CPWaterService.asmx");
            HttpPost httpPost = new HttpPost(forwarderModel.getServerIp());
            CpszyResponseModel responseModel = new CpszyResponseModel(aireadModel, yesterdayDate);
            responseModel.setDay_w(dailyWaterConsumption.abs().toString());
            Map<String, List<CpszyResponseModel>> map = new HashMap<>();
            List<CpszyResponseModel> list = new ArrayList<>();
            list.add(responseModel);
            map.put("data", list);
            String json = JSON.toJSONString(map);
            ////String json = "{\"data\":[{\"mp_cd\":\"1101140117001\",\"dt\":\"2018-07-01\",\"day_w\":\"20\",\"nt\":\"\", \"dpdtype\":\"03\",\"aduncd\":\"11011401\",\"frontwtime\":\"2018-07-01 00:00:00\", \"mdtime\":\"\"}]}";
            log.warn(json);
            record.setSendMsg(json);
            record.setForwardValue(responseModel.getDay_w());

            StringBuilder sb = new StringBuilder();
            sb.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
            sb.append("<soap:Body>");
            sb.append("<InsertDaydata xmlns=\"http://tempuri.org/\">");
            sb.append("<json>");
            sb.append(json);
            sb.append("</json>");
            sb.append("</InsertDaydata>");
            sb.append("</soap:Body>");
            sb.append("</soap:Envelope>");
            // 构建 SOAP 请求体

            // 设置 HTTP 头部，指定内容类型为 SOAP
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            ////httpPost.setHeader("SOAPAction", "http://example.com/YourServiceMethod");

            // 设置请求体
            httpPost.setEntity(new StringEntity(sb.toString(), "UTF-8"));

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 打印响应内容
                    String soapResponse = EntityUtils.toString(entity);
                    String result = getResult(soapResponse);
                    if (result.equals("1")) {
                        log.warn("{}WS上传成功：[{}]{}", forwarderModel.getServerName(), aireadModel.getStationCode(), soapResponse);
                    } else {
                        log.warn("{}WS上传失败：[{}]{}", forwarderModel.getServerName(), aireadModel.getStationCode(), soapResponse);
                    }
                    record.setReplyMsg(soapResponse);
                }
            }
        } catch (IOException e) {
            log.error("{}WS上传失败：[{}]{}", forwarderModel.getServerName(), aireadModel.getStationCode(), e.getMessage());
            e.printStackTrace();
        }

        try {
            forwarderRecordsService.saveTForwarderRecords(record);
        } catch (Exception e) {
            log.error("转发记录入库失败", e);
        }
    }

    /**
     * 获取返回结果(简单解析)
     *
     * @param xmlContent xml内容
     * @return
     */
    private String getResult(String xmlContent) {
        int index0 = xmlContent.indexOf(TAG_VALUE_START);
        int index1 = xmlContent.indexOf(TAG_VALUE_END);
        if (index0 != -1 && index1 != -1) {
            return xmlContent.substring(index0 + TAG_VALUE_START.length(), index1);
        }
        return "";
    }

    /**
     * 获取昨日读数对象
     *
     * @param aireadModel
     * @return
     */
    private TAireadModel getYesterdayAireadModel(TAireadModel aireadModel) {
        TAireadExample example = new TAireadExample();
        //-2是由于,推送数据使用的是前一天数据,例如:3号推送时,使用的是2号的数据,想计算用量,前一天的值就要是1号的
        //此处仍有一个特殊情况,就是1号的值有未审核的可能? 2024-07-01 guozhao
        Date yesterdayDate = DateUtil.getOtherDateByCurrentDate(aireadModel.getSampleTime(), -2);
        example.createCriteria().andStationCodeEqualTo(aireadModel.getStationCode()).andSampleTimeEqualTo(yesterdayDate);
        List<TAiread> list = aireadMapper.selectByExample(example);
        example.setOrderByClause("ID");
        if (list.size() > 0 && list.get(list.size() - 1).getResultValue() != null) {
            TAireadModel model = new TAireadModel();
            BeanUtils.copyProperties(list.get(list.size() - 1), model);
            return model;
        }
        return null;
    }
}
