package com.zehong.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.zehong.system.domain.TSiteStationInfo;
import com.zehong.system.domain.http.Save;
import com.zehong.system.domain.http.WorkerCertDirectDTO;
import com.zehong.system.service.ITSiteStationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.crypto.Cipher;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Controller
public class APIController {


    private static final String RSA_ALGORITHM = "RSA";

    @Autowired
    private ITSiteStationInfoService tSiteStationInfoService;
    /**
     * 场站信息管道气企业添加
     */
    @RequestMapping("/addSave")
    public void addSave() throws Exception {
        //企业ID为一  燃气集团 生成 加密 公钥 私钥
        String publicKeyString = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnbtzv7xsBPF9rGf/+4ejdNfowbFWq8qxqrNOxrUxrklhCd173Uud4UeV4HBrNiioX2/3QMy8PhPMik3u7swcPTkcEAUhCIkIua4tJ2sEvjveUuzBqeRYVQiADjrr5wm2TXC63b5ihxPPMqdJWdHOnUfXimdqx8TEvHr7ILyV1j+kyBTlVQEpB3IyCHfoW+1orffI0BC77PQEVb9hoBuL6LSqwj8YPb+2YIatPHhSh1SjMut7KhJiOwkomJAqewaBFP/eUjR0k8qeYMGdtio3dxJiifSSl8VKpAbbfSaoLBBky//k9nxB1wdr7cXDu0evwly0C+OhQadBPVmscJMNkQIDAQAB";
        String privateKeyString = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfFl4M10ib38cayb4u4vw2/JwZtptWQ6viAm/8t82QM8i2qPYNMalmCsIpO4+7QbSVO+MjG+hfnKJt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2Rl1YVOOcFZjxO03KNHa8nxKCA35t298RUelacy+avfWFKW1alALcUoS7o7v3W4F4b4wvX+y80fAoGAfmq77mIv++krdseyu/NQkRaZYiMl35lrAcoJB9vDo/SKeEWlyswAdbPLj0j03hDQBTIdTZwKdadNAH30+FInIwyhpyu4335lAgCjuphYQS/hcYQB1Cd+fD5T7E3clNqHdSAf0Awh9UIR0s3UjE0JNE8LYQ1YBvTJpgd7McYIEIcCgYEAsKgI481TPfjrCML0bjZ+d5O8fObFcQup2CzAlXvZtQrM62/Siubwta7IRiZK6yeMbU4uWeZxNBdPIE8Dd5HBFRHiJiD8uB3gdq91YxQYmbu1i37MxueAAlGGpD6Ds5OZZ6+PZZw2SGcUMgY2Y06eqVyxfbdCWuA8sQ4oxyb8DmI=";

        RsaToClient rsa = new RsaToClient(privateKeyString, publicKeyString);

        TSiteStationInfo tSiteStationInfo=new TSiteStationInfo();
        tSiteStationInfo.setBeyondEnterpriseId("15");
        List<TSiteStationInfo> tSiteStationInfos = tSiteStationInfoService.selectTSiteStationInfoList(tSiteStationInfo);
        //        组装加密数据结构 （这里根据接口参数进行调整组装格式）

        for (int i=0;i<tSiteStationInfos.size();i++){
            Save model = new Save();
            //场站地址
            model.setAddress("无");
            //建设日期
            model.setBuildDate(tSiteStationInfos.get(i).getBuildDate());
            //施工单位
            model.setConstructionUnit(tSiteStationInfos.get(i).getBuildUnit());
            //联系人
            model.setContact("无");
            //身份证
            model.setDirectorIdcardCode("508475209510309953");
            model.setPhoneNumber("18982222222");
            //监控和数据采集系统
            model.setEqEightNum("0");
            //激光云台
            model.setEqFiveNum("0");
            //防雷及防静电接地装置
            model.setEqFourNum("0");
            //燃气浓度检测报警装置
            model.setEqOneNum("0");
            //防第三方入侵系统
            model.setEqSevenNum("0");
            //视频安防系统
            model.setEqSixNum("1");
            //消防系统
            model.setEqThreeNum("1");
            //超限报警
            model.setEqTwoNum("0");
            //燃气分类
            model.setGasType("1");
            //重大危险源级别
            model.setHazardGrade("0");
            //联系方式
            model.setHazardName("0");
            //坐标点
            model.setPoint(String.valueOf(tSiteStationInfos.get(i).getLongitude())+" "+String.valueOf(tSiteStationInfos.get(i).getLatitude()));
            //投产时间
            model.setProductionDate("2023-09-22");
            //所属区县
            model.setRegion("130203");
            //备注
            model.setRemark(tSiteStationInfos.get(i).getRemark());
            //场站规模
            model.setScale("0");
            //场站级别
            model.setStaLevel("1");
            //场站状态
            model.setStaStatus("1");
            //场站编码
            model.setStationCode("0"+i);
            //场站用途
            model.setStationDestination("无");
            //场站分类
            model.setStationKind("1000190002");
            //站点面积
            model.setStationMeasure("100");
            //场站名称
            model.setStationName("无");
            //场站类型
            model.setStationType("2");
            //储罐总容积
            model.setStorageVolume("0");

            List<Save> list = new ArrayList<>();
            list.add(model);
            WorkerCertDirectDTO workerCertDirectDTO=new WorkerCertDirectDTO();
            workerCertDirectDTO.setList(list);
            String jsonObj = JSONObject.toJSONString(list);
            //加密
            //11130200001 企业ID=1的 企业CODE 这个月header参数是对应的
            String data = "11130221019@"+jsonObj;
            System.out.println("data=" + data);

            //加密的算法有长度限制 不再采用配合其他加密算法来解决了 直接切断处理加密
            String encryptedData = rsa.encryptMaxString(data, publicKeyString);



            //1. 创建URL对象
            URL url = new URL("http://101.43.197.44:8129/enterApi/s1_controller/save");
            //2. 创建HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //3. 设置请求方法
            conn.setRequestMethod("POST");
            //4. 设置请求头
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("enterpriseCode", "11130221019");
            //5. 设置参数
            JSONObject jsonpObject = new JSONObject();
            jsonpObject.put("data", encryptedData);
            //6. 发送数据
            conn.setDoOutput(true);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jsonpObject.toString().getBytes());
            outputStream.flush();
            outputStream.close();
            //7. 获取返回值
            InputStream inputStream = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String result = stringBuilder.toString();
            System.out.println(result);

//            System.out.println("加密后的数据：" + encryptedData);
        }

    }

    /**
     * 将byte数组按照指定大小分割成多个数组
     *
     * @param bytes   要分割的byte数组
     * @param subSize 分割的块大小  单位：字节
     * @return 指定大小的byte数组
     */

    public static Object[] splitByteArr(byte[] bytes, int subSize) {
        int count = bytes.length % subSize == 0 ? bytes.length / subSize : bytes.length / subSize + 1;

        List<List<Byte>> subAryList = new ArrayList<List<Byte>>();

        for (int i = 0; i < count; i++) {
            int index = i * subSize;
            List<Byte> list = new ArrayList<Byte>();
            int j = 0;
            while (j < subSize && index < bytes.length) {
                list.add(bytes[index++]);
                j++;
            }
            subAryList.add(list);
        }

        Object[] subAry = new Object[subAryList.size()];

        for (int i = 0; i < subAryList.size(); i++) {
            List<Byte> subList = subAryList.get(i);
            byte[] subAryItem = new byte[subList.size()];
            for (int j = 0; j < subList.size(); j++) {
                subAryItem[j] = subList.get(j);
            }
            subAry[i] = subAryItem;
        }
        return subAry;
    }

    /**
     * 使用公钥加密数据
     *
     * @param data      待加密的数据
     * @param publicKey 公钥
     * @return 加密后的数据
     */
    public String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    /**
     * 对大字符串进行加密
     */
    public String encryptMaxString(String data, String publicKeyString) throws Exception {
        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
        Object[] objects = splitByteArr(bytes, 245);
        String codeAll = "";
        //依次加密
        for (int i = 0; i < objects.length; i++) {
            byte[] temp = (byte[]) objects[i];
//            String encryptedData = encrypt(new String(temp, "UTF-8"), publicKeyString);
            String encryptedData = encrypt2(temp, publicKeyString);
            codeAll += "@@" + encryptedData;
        }
        return codeAll;
    }

    public  String encrypt2(byte[] data, String publicKeyString) throws Exception {
        PublicKey publicKey = generateRSAPublicKey(publicKeyString);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(data);
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    /**
     * 对小字符串进行加密 小于245字节的字符串
     *
     * @param data
     */
    public String encrypt(String data, String publicKeyString) throws Exception {
        PublicKey publicKey = generateRSAPublicKey(publicKeyString);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }
    /**
     * 公钥字符串 转换为公钥
     *
     * @param publicKeyString
     */
    public PublicKey generateRSAPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }
}
