package com.sw.mes.yb.mcs.utils;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.log4j.Log4j2;


/**
 * @Author: GaoXinJian
 * @Date: 2022-01-12 15:12
 */

@Component(value = "requestUtilsMcs")
@Log4j2
@RefreshScope
public class RequestUtils {
    @Value("${spring.mcsServiceUrl}")
    private String mcsServiceUrl;
    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    RestTemplate restTemplate;

    public ResultDto postForMcs(RequestDto<T> requestDto) {

        log.info("3333");
        ResponseEntity<String> result = null;
        ResultDto resultDto = new ResultDto();

        if (!active.equals("prod")){
            log.info("非生产环境，不请求mcs");
            resultDto.setMessage("非生产环境，不请求mcs");
            resultDto.setStatus(200);
            return  resultDto;
        }
        Integer count = 0;
        while (true) {

            UUID uuid=UUID.randomUUID();
            log.info("【postForMcs】【"+uuid+":】"+mcsServiceUrl + requestDto.getServiceUrl()+"【requestDto:】"+ JSONObject.toJSONString(requestDto));
            // 请求部分
            try {
                result = restTemplate.postForEntity(mcsServiceUrl + requestDto.getServiceUrl(), requestDto.getData(), String.class);
                log.info("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));

                if (result.getStatusCodeValue() == 200) {
                    //请求成功

                    if (StringUtils.isBlank(result.getBody())) {
                        resultDto.setMessage("请求成功，返回信息为空");
                        resultDto.setStatus(result.getStatusCodeValue());
                        count++;
                        if (count > 2) {
                            break;
                        }
                        continue;
                    }

                    // 返回结果，解析部分
                    try {
                        resultDto = JSON.parseObject(result.getBody(), ResultDto.class);
                        break;
                    } catch (Exception e) {
                        resultDto.setMessage("请求成功，解析返回结果发生错误，返回信息：[" + result.getBody() + "]" + "，错误信息：" + e.getMessage());
                        resultDto.setStatus(500);
                    }
                    break;
                } else {
                    //请求失败
                    resultDto.setMessage("请求失败");
                    resultDto.setStatus(result.getStatusCodeValue());
                }

            } catch (Exception e) {
                // 发生异常，存储异常信息
                resultDto.setMessage("请求发生错误：" + e.getMessage());
                resultDto.setStatus(500);
                count++;
               log.error("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));
               e.printStackTrace();
                if (count > 2) {
                    break;
                }
                continue;
            }
        }

        return resultDto;
    }



    /**
     * mcs返回的status为字符串，mes重新处理并解析
     * @param requestDto
     * @return
     */
    public ResultDto postForMcsNew(RequestDto<T> requestDto) {
        log.info("3333");
        ResponseEntity<String> result = null;
        ResultDto resultDto = new ResultDto();

        if (!active.equals("prod")){
            log.info("非生产环境，不请求mcs");
            resultDto.setMessage("非生产环境，不请求mcs");
            resultDto.setStatus(200);

            return  resultDto;
        }
        Integer count = 0;
        while (true) {

            UUID uuid=UUID.randomUUID();
            log.info("【postForMcs】【"+uuid+":】"+mcsServiceUrl + requestDto.getServiceUrl()+"【requestDto:】"+ JSONObject.toJSONString(requestDto));
            // 请求部分
            try {
                result = restTemplate.postForEntity(mcsServiceUrl + requestDto.getServiceUrl(), requestDto.getData(), String.class);
                log.info("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));

                if (result.getStatusCodeValue() == 200) {
                    //请求成功
                    if (StringUtils.isBlank(result.getBody())) {
                        resultDto.setMessage("请求成功，返回信息为空");

                        resultDto.setStatus(result.getStatusCodeValue());
                        count++;
                        if (count > 2) {
                            break;
                        }
                        continue;
                    }

                    // 返回结果，解析部分
                    try {
                        String body = result.getBody();
                        JSONObject jsonObject = JSONObject.parseObject(body);
                        String status = jsonObject.getString("status").trim();
                        Integer v = 500;
                        //todo 解析 status
                        if (null != status && StringUtils.isNotEmpty(status) && ("200".equals(status) || "Success".equals(status))){
                            v = 200;
                        }
//                        resultDto = JSON.parseObject(result.getBody(), ResultDto.class,);
                        resultDto.setStatus(v);
                        resultDto.setMessage(jsonObject.getString("message"));
                        resultDto.setCode(Integer.parseInt(jsonObject.getString("code")));
                        resultDto.setData(jsonObject.getString("data"));

                        break;
                    } catch (Exception e) {
                        resultDto.setMessage("请求成功，解析返回结果发生错误，返回信息：[" + result.getBody() + "]" + "，错误信息：" + e.getMessage());
                        resultDto.setStatus(500);
                    }
                    break;
                } else {
                    //请求失败
                    resultDto.setMessage("请求失败");
                    resultDto.setStatus(result.getStatusCodeValue());
                }

            } catch (Exception e) {
                // 发生异常，存储异常信息
                resultDto.setMessage("请求发生错误：" + e.getMessage());
                resultDto.setStatus(500);
                count++;
                log.error("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));
                e.printStackTrace();
                if (count > 2) {
                    break;
                }
                continue;
            }
        }

        return resultDto;
    }




    public ResultDto postForMcsByWaterLineManage(RequestDto<T> requestDto) {

        log.info("3333");
        ResponseEntity<String> result = null;
        ResultDto resultDto = new ResultDto();

        if (!active.equals("prod")){
            log.info("非生产环境，不请求mcs");
            resultDto.setMessage("非生产环境，不请求mcs");
            resultDto.setStatus(200);
            return  resultDto;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("token","token_admin");
        headers.add("Content-Type","application/json");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(requestDto.getData()), headers);
        Integer count = 0;
        while (true) {
            UUID uuid=UUID.randomUUID();
            log.info("【postForMcs】【"+uuid+":】"+mcsServiceUrl + requestDto.getServiceUrl()+"【requestDto:】"+ JSONObject.toJSONString(requestDto.getData()));
            // 请求部分
            try {
                result = restTemplate.postForEntity(mcsServiceUrl + requestDto.getServiceUrl(), httpEntity, String.class);
                log.info("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));
                if (result.getStatusCodeValue() == 200) {
                    //请求成功
                    if (StringUtils.isBlank(result.getBody())) {
                        resultDto.setMessage("请求成功，返回信息为空");
                        resultDto.setStatus(result.getStatusCodeValue());
                        count++;
                        if (count > 2) {
                            break;
                        }
                        continue;
                    }
                    // 返回结果，解析部分
                    try {
                        resultDto = JSON.parseObject(result.getBody(), ResultDto.class);
                        break;
                    } catch (Exception e) {
                        resultDto.setMessage("请求成功，解析返回结果发生错误，返回信息：[" + result.getBody() + "]" + "，错误信息：" + e.getMessage());
                        resultDto.setStatus(500);
                    }
                    break;
                } else {
                    //请求失败
                    resultDto.setMessage("请求失败");
                    resultDto.setStatus(result.getStatusCodeValue());
                }

            } catch (Exception e) {
                // 发生异常，存储异常信息
                resultDto.setMessage("请求发生错误：" + e.getMessage());
                resultDto.setStatus(500);
                count++;
                log.error("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));

                if (count > 2) {
                    break;
                }
                continue;
            }
        }
        return resultDto;
    }


    public ResultDto canningMaterialPostForMcs(RequestDto<T> requestDto) {
        ResponseEntity<String> result = null;
        ResultDto resultDto = new ResultDto();
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Authorization", "token_admin");
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(requestDto.getData()), headers);
        Integer count = 0;
        while (true) {

            UUID uuid=UUID.randomUUID();
            log.info("【postForMcs】【"+uuid+":】"+mcsServiceUrl + requestDto.getServiceUrl()+"【requestDto:】"+ JSONObject.toJSONString(requestDto));
            // 请求部分
            try {
                result = restTemplate.postForEntity(mcsServiceUrl + requestDto.getServiceUrl(), httpEntity, String.class);
                log.info("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));

                if (result.getStatusCodeValue() == 200) {
                    //请求成功
                    if (StringUtils.isBlank(result.getBody())) {
                        resultDto.setMessage("请求成功，返回信息为空");
                        resultDto.setStatus(result.getStatusCodeValue());
                        count++;
                        if (count > 2) {
                            break;
                        }
                        continue;
                    }

                    // 返回结果，解析部分
                    try {
                        String body = result.getBody();
                        JSONObject jsonObject = JSONObject.parseObject(body);
                        String status = StringUtils.trim(jsonObject.getString("status"));
                        Integer v = 500;
                        //todo 解析 status
                        if (null != status && StringUtils.isNotEmpty(status) && ("200".equals(status) || "Success".equals(status))){
                            v = 200;
                        }
                        resultDto.setStatus(v);
                        resultDto.setMessage(jsonObject.getString("message"));
                        resultDto.setCode(Integer.parseInt(jsonObject.getString("code")));
                        resultDto.setData(jsonObject.getString("data"));
                        break;
                    } catch (Exception e) {
                        resultDto.setMessage("请求成功，解析返回结果发生错误，返回信息：[" + result.getBody() + "]" + "，错误信息：" + e.getMessage());
                        resultDto.setStatus(500);
                    }
                    break;
                } else {
                    //请求失败
                    resultDto.setMessage("请求失败");
                    resultDto.setStatus(result.getStatusCodeValue());
                }
            } catch (Exception e) {
                // 发生异常，存储异常信息
                resultDto.setMessage("请求发生错误：" + e.getMessage());
                resultDto.setStatus(500);
                count++;
                log.error("【postForMcs】【"+uuid+":】【result:】"+ JSONObject.toJSONString(result));
                e.printStackTrace();
                if (count > 2) {
                    break;
                }
                continue;
            }
        }

        return resultDto;
    }
}
