/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/10/27
 */
package org.ts.ddcs.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ts.ddcs.common.util.BytesUtil;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/***
 * Date:2022/10/27
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
public class TestController {


    public static byte[] hexStr2Bytes(String hexString) {
        hexString = hexString.toLowerCase();
        int remainder = hexString.length() % 2;
        if (remainder > 0) {
            hexString = "0" + hexString;
        }
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {
            //因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
            //将hex 转换成byte   "&" 操作为了防止负数的自动扩展
            // hex转换成byte 其实只占用了4位，然后把高位进行右移四位
            // 然后“|”操作  低四位 就能得到 两个 16进制数转换成一个byte.
            //
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i = begin; i < begin + count; i++) {
            bs[i - begin] = src[i];
        }
        return bs;
    }

    public static int bytes2Int(byte[] bytes, int off, int len) {
        int v = 0;
        int pos = off + len - 1;
        if (pos >= 0) {
            v |= (bytes[pos] & 0xFF);
        }
        pos--;
        if (pos >= 0) {
            v |= ((bytes[pos] << 8) & 0xFF00);
        }
        pos--;
        if (pos >= 0) {
            v |= ((bytes[pos] << 16) & 0xFF0000);
        }
        pos--;
        if (pos >= 0) {
            v |= ((bytes[pos] << 24) & 0xFF000000);
        }
        return v;
    }

    public static String leftFill(String src, int len, char fillChar) {


        String result = src;
        for (int i = src.length(); i < len; i++) {
            result = String.valueOf(fillChar) + result;
        }

        return result;
    }

    public static String byte2HexMpCdStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < 3; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
        }
        int mpcd = bytes2Int(subBytes(b, 3, 2), 0, 2) % 10000;

        sb.append(leftFill(mpcd + "", 4, '0'));
        return sb.toString().toUpperCase().trim();
    }


    @GetMapping("collect/test/fun")
    public String getFun() {
        byte[] buff = hexStr2Bytes("1522005A02");
        String str = byte2HexMpCdStr(buff);
        return str;
    }

    @GetMapping("collect/test/fun1")
    public String getFun1() {
        String rtuCode = "1522005A02";
        String rtutail = rtuCode.substring(rtuCode.length() - 4, rtuCode.length());
        byte[] rtubuff = BytesUtil.hexStr2Bytes(rtutail);
        int rtuvalue = BytesUtil.bytes2short(rtubuff);
        if (rtuvalue >= 0 && rtuvalue <= 9999) {
            rtutail = String.format("%04d", rtuvalue);
            rtuCode = rtuCode.substring(0, 6) + rtutail;

        }

        return rtuCode;
    }

    @GetMapping(value = "collect/test")
    public String toTest() {
        try {
            // 1.定义服务器的地址、端口号、数据
            InetAddress address = InetAddress.getByName("localhost");
            // 2.定义服务器端口
            int port = 8002;

            // 3.创建发送端对象：发送端自带默认端口号
            DatagramSocket socket = new DatagramSocket(2222);

            // 4.客户端启动成功，输出提示信息
            System.out.println("****客户端启动成功****");
            String msg ="7E7E01005128290300002F20080230522230271439160396987E7E01005128290300002F0008023052221027144016034F497E7E01005128290300002F0008023052221027144116038F187E7E01005128290300002F0008023052221027144216038FE87E7E01005128290300002F0008023052221027144316034FB97E7E01005128290300002F0008023052221027144416038E087E7E01005128290300002F0008023052221027144516034E597E7E01005128290300002F0008023052221027144616034EA97E7E01005128290300002F0008023052221027144716038EF8";
            byte[] buffer= BytesUtil.hexStr2Bytes(msg);

            DatagramPacket packets = new DatagramPacket(buffer, buffer.length, address, port);
            // 5.4 发送数据出去
            socket.send(packets);

            while (true) {
                byte[] buf = new byte[1024 * 64];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                // 6.2 接收服务器响应的数据
                socket.receive(packet);
                // 6.3 取出数据
                int len = packet.getLength();
                if (len >0) {
                    String rs = new String(buf, 0, len);
                    System.out.println("收到了ip为：" + packet.getAddress() + " 端口号为：" + packet.getPort() + "的消息：" + rs);
                    break;
                }
            }
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "ok";
    }
}
