package com.zbf.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zbf.common.core.domain.AjaxResult;
import com.zbf.system.domain.TBaseGoods;
import com.zbf.system.mapper.TBaseGoodsMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;


@Component("DataPushingTask")
public class DataPushing {


    @Autowired
    private TBaseGoodsMapper mapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 数据推送
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult DataPush() {
        final String url = "http://172.18.29.101/wms/api/RestJsonService/syncMatBasicInfos";
        ObjectMapper objectMapper = new ObjectMapper();

        /*Object times = redisTemplate.opsForValue().get("times");*/
        if (1 == 2) {

        } else {
            // 构建新的请求体
            Map<String, Object> taskData = new HashMap<>();
            taskData.put("reqCode", generateRandomHexString(14)); // 示例请求编号

            LambdaQueryWrapper<TBaseGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.isNotNull(TBaseGoods::getGoodsId);
            queryWrapper.isNotNull(TBaseGoods::getGoodsName);
            List<TBaseGoods> tBaseGoods = mapper.selectList(queryWrapper);
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (TBaseGoods good : tBaseGoods) {
                Map<String, Object> dataItem = new HashMap<>();
                dataItem.put("operType", "A");
                dataItem.put("matCode", good.getGoodsId());
                dataItem.put("ownerCode", "8000");
                dataItem.put("matText", good.getGoodsName());
                dataItem.put("matUnit", "EA");
                dataList.add(dataItem);
            }
            taskData.put("data", dataList);

            String requestBody = "";
            try {
                requestBody = objectMapper.writeValueAsString(taskData);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return AjaxResult.error("JSON processing failed");
            }

            try (CloseableHttpClient httpClient = createHttpClient()) {


                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
                httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); // 确保使用UTF-8编码
                HttpResponse response = httpClient.execute(httpPost);

                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                JsonNode rootNode = objectMapper.readTree(responseString);

                boolean isSuccess = rootNode.path("success").asBoolean(); // 获取success的值

                if (isSuccess) {
                    // 成功的处理逻辑
                    return AjaxResult.success("数据推送成功");
                } else {
                    // 失败的处理逻辑
                    String errorCode = rootNode.path("code").asText();
                    String message = rootNode.path("message").asText();
                    AjaxResult.error("操作失败，错误码：" + errorCode + ", 错误信息：" + message);
                }
                // 创建日期格式化对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // 获取当前日期时间的字符串表示
                String dateString = sdf.format(new Date());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("Failed to send POST request");
            }
        }
        return AjaxResult.warn("123");
    }

    // Helper method to generate random hex string
    private String generateRandomHexString(int len) {
        String hexChars = "0123456789abcdef";
        StringBuilder sb = new StringBuilder(len);
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < len; i++) {
            int index = random.nextInt(hexChars.length());
            sb.append(hexChars.charAt(index));
        }
        return sb.toString();
    }


    private SSLContext createTrustAllSslContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }


                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        return sslContext;
    }


    private CloseableHttpClient createHttpClient() throws Exception {
        return HttpClients.custom()
                .setSslcontext(createTrustAllSslContext())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    }
}
