package com.zt.plat.module.erp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zt.plat.module.erp.api.dto.ErpSubmitReqDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.erp.enums.ErrorCodeConstants.*;
import static dm.jdbc.util.DriverUtil.log;

@Configuration
public class ErpConfig {

    @Value("${erp.address:}")
    private String erpAddress;

    @Value("${erp.sapsys:}")
    private String sapsys;

    @Value("${erp.srcsys:JYGK}")
    private String srcsys;

    @Value("${erp.secret-key:}")
    private String secretKey;

    /**
     * 调用ERP接口获取erp数据
     */
    public Map<String, Object> fetchDataFromERP(String funcnr, Map<String, Object> req) {
        try {
            // 构建完整URL
            String url = "http://" + erpAddress + "/api/rfc/get";
            // 构建请求参数
            JSONObject requestBody = new JSONObject();
            requestBody.put("sapsys", sapsys);
            requestBody.put("funcnr", funcnr); // 获取枚举值
            if (req != null) {
                requestBody.put("req", req);
            }

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建HTTP请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody.toJSONString(), headers);

            // 发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

            // 解析响应结果
            String responseBody = response.getBody();
            if (responseBody.isEmpty()) {
                throw exception(ERP_NOT_EXISTS);
            }

            Map<String, Object> resMap = new HashMap<>();
            JSONObject jsonResponse = JSON.parseObject(responseBody);
            if (jsonResponse == null) {
                throw exception(ERP_NOT_JSON_EXISTS);
            }
            // 正确获取E_DATA数组
            JSONObject dataObject = jsonResponse.getJSONObject("data");
            //判断 result里的succeed是否为true
            boolean succeed = jsonResponse.getBoolean("succeed");
            if (succeed && "S".equals(dataObject.getString("E_FLAG"))) {
                String flag = "S";
                JSONArray E_RESP = dataObject.containsKey("E_DATA") ? dataObject.getJSONArray("E_DATA") : null;
                String E_MSG = dataObject.containsKey("E_MSG") ? dataObject.getString("E_MSG") : null;
                resMap.put("E_RESP", E_RESP);
                resMap.put("resStr", E_MSG);
                resMap.put("flag", flag);
                return resMap;
            } else {
                String E_MSG = dataObject.containsKey("E_MSG") ? dataObject.getString("E_MSG") :  null;
                String flag = "E";
                resMap.put("E_RESP", null);
                resMap.put("resStr", E_MSG);
                resMap.put("flag", flag);
                return resMap;
            }
        } catch (Exception e) {
            log.error("调用ERP RFC接口失败: {}", e);
            throw exception(ERP_ERROR_EXISTS, e);
        }
    }

    /**
     * 调用ERP接口更新erp数据
     */
    public Map<String, String> pushDataToErp(ErpSubmitReqDTO reqDTO) {
        try {
            // 构建完整URL
            String url = "http://" + erpAddress + "/api/rfc/post";
            // 构建请求参数
            JSONObject requestBody = new JSONObject();
            String uuid = UUID.randomUUID().toString();
            requestBody.put("uuid", uuid);
            requestBody.put("sapsys", sapsys);
            requestBody.put("srcsys", srcsys);
            requestBody.put("funcnr", reqDTO.getFuncnr());
            requestBody.put("bskey", reqDTO.getBskey());
            requestBody.put("usrid", reqDTO.getUsrid());
            requestBody.put("usrnm", reqDTO.getUsrnm());
            if (StringUtils.isBlank(reqDTO.getSign())) {
                requestBody.put("sign", DigestUtil.md5Hex(uuid + srcsys + secretKey, StandardCharsets.UTF_8));
            } else {
                requestBody.put("sign", reqDTO.getSign());
            }
            if (reqDTO.getReq() != null) {
                requestBody.put("req", reqDTO.getReq());
            }
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            // 创建HTTP请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody.toJSONString(), headers);

            // 发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

            // 解析响应结果
            String responseBody = response.getBody();
            if (responseBody.isEmpty()) {
                throw exception(ERP_NOT_EXISTS);
            }

            JSONObject jsonResponse = JSON.parseObject(responseBody);
            if (jsonResponse == null) {
                throw exception(ERP_NOT_JSON_EXISTS);
            }

            Map<String, String> resMap = new HashMap<>();
            boolean succeed = jsonResponse.getBoolean("succeed");
            JSONObject data =  jsonResponse.getJSONObject("data");
            String msg = jsonResponse.getString("msg");
            if (data == null) {
                resMap.put("E_RESP", null);
                resMap.put("resStr", msg);
                resMap.put("flag", "E");
                log.error("SAP接口返回值为空," + jsonResponse.getString("msg"));
                //throw exception(ERP_NOT_EXISTS);
            } else if (succeed && "S".equals(data.getString("E_FLAG"))) {
                String flag = "S";
                String E_RESP = data.containsKey("E_RESP") ? data.getString("E_RESP") : null;
                String E_MSG = data.containsKey("ET_MSG") ? data.getString("ET_MSG") : null;
                if (StrUtil.isBlank(E_MSG)) {
                    E_MSG = jsonResponse.getString("msg");
                }
                resMap.put("E_RESP", E_RESP);
                resMap.put("resStr", E_MSG);
                resMap.put("flag", flag);
            } else if (!succeed && "E".equals(data.getString("E_FLAG"))) {
                String flag = "E";
                String E_RESP = data.containsKey("E_RESP") ? data.getString("E_RESP") : null;
                String E_MSG = data.containsKey("ET_MSG") ? data.getString("ET_MSG") : null;
                if (StrUtil.isBlank(E_MSG)) {
                    E_MSG = jsonResponse.getString("msg");
                }
                resMap.put("E_RESP", E_RESP);
                resMap.put("resStr", E_MSG);
                resMap.put("flag", flag);
            }
            return resMap;
        } catch (Exception e) {
            log.error("调用ERP RFC接口失败: {}", e);
            throw exception(ERP_ERROR_EXISTS);
        }
    }


}
