package com.xhpc.pp.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhpc.common.api.PowerPileService;
import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.HttpUtils;
import com.xhpc.common.data.down.StartChargingData;
import com.xhpc.common.enums.StationDeviceEnum;
import com.xhpc.pp.domain.XhpcDeviceMessage;
import com.xhpc.pp.logic.RateModelRequestLogic;
import com.xhpc.pp.mapper.XhpcDeviceMessageMapper;
import com.xhpc.pp.server.ChargingPileServer;
import com.xhpc.pp.utils.HexUtils;
import com.xhpc.pp.utils.security.CP56Time2a;
import com.xhpc.pp.utils.security.CRCCalculator;
import com.xhpc.pp.utils.security.CacheDataUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.quickserver.net.server.ClientHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.common.data.redis.StaticBeanUtil.seqHex;
import static com.xhpc.pp.server.ChargingPileServer.*;
import static com.xhpc.pp.utils.HexUtils.toHexInt;
import static com.xhpc.pp.utils.HexUtils.toHexIntYu;

@RestController
public class ChargingController {

    private static final Logger log = LoggerFactory.getLogger(ChargingController.class);

    @Autowired
    private PowerPileService powerPileService;

    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;

    private static final List<String> etable = Arrays.asList((new String[]{"离线", "故障"}).clone());

    @PostMapping("test/pile/charging/order")
    public R test(@Validated @RequestBody StartChargingData startChargingData) {

        R r = R.ok();
        for (int i = 0; i < startChargingData.getBalance(); i++) {
            r = powerPileService.startCharging(startChargingData);
        }
        return r;
    }

    @PostMapping("charging/balance/refresh")
    public R refreshBalance(@Validated @RequestBody StartChargingData balanceRefreshData) {

        String pileNo = balanceRefreshData.getPileNo();
        String pkey = "pile:".concat(pileNo);
        Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
        R<Object> r = checkPile(cachePile);
        if (r.getCode() == 200) {
            String svcSrv = (String) cachePile.get("svcSrv");
            JSONObject json = (JSONObject) JSON.toJSON(balanceRefreshData);
            String response = HttpUtils.post(fmt(svcSrv).concat("/native/charging/balance/refresh"), json);
            r = getRR(response);
        }
        return r;
    }

    public static R<Object> getRR(String response) {

        R<Object> r;
        JSONObject responseJson = (JSONObject) JSON.parse(response);
        if (responseJson == null) {
            r = R.fail("原生服务调用失败");
        } else {
            int code = responseJson.getInteger("code");
            log.debug(response);
            if (code != 200) {//todo rat
                r = R.fail(code, responseJson.getString("msg"));
            } else {
                r = R.ok(responseJson.get("data"), responseJson.getString("msg"));
            }
        }
        return r;
    }

    @PostMapping("charging/start")
    public R startCharging(@Validated @RequestBody StartChargingData startChargingData) {

        String pileNo = startChargingData.getPileNo();
        String pkey = "pile:".concat(pileNo);
        Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
        R<Object> r = checkPile(cachePile);
        if (r.getCode() == 200) {
            String svcSrv = (String) cachePile.get("svcSrv");
            Long stationId = (Long) cachePile.get("stationId");
            ChargingStationDto cacheStation = REDIS.getCacheObject("station:".concat(stationId.toString()));
            Long stationRateModelId = cacheStation.getRateModelId();
            Long pileRateModelId = (Long) cachePile.get("rateModelId");
            if (!stationRateModelId.equals(pileRateModelId)) {
                String resultStr = RateModelRequestLogic.translate(pileNo, stationRateModelId, "0058",
                        (String) cachePile.get("version"));
                String response = HttpUtils.post(fmt(svcSrv).concat("/native/pile/".concat(pileNo).concat("/rateModel")),
                        resultStr);
                JSONObject responseJson = (JSONObject) JSON.parse(response);
                assert responseJson != null;
                int code = responseJson.getInteger("code");
                log.error(response);
                if (code != 200) {
                    r = R.fail(code, responseJson.getString("msg"));
                } else {
                    r = R.fail(responseJson.getString("msg"));
                    REDIS.setCacheMap(pkey, cachePile);
                }
            } else {
                JSONObject json = (JSONObject) JSON.toJSON(startChargingData);
                String response = HttpUtils.post(fmt(svcSrv).concat("/native/charging/start"), json);
                r = getRR(response);
                r.setData(stationRateModelId);
            }
        }
        return r;
    }

    public static R<Object> checkPile(Map<String, Object> cachePile) {

        if (cachePile == null || cachePile.get("status") == null) {
            return R.fail("充电桩未注册");
        }
        String status = cachePile.get("status").toString();
        if (etable.contains(status)) {
            return R.fail("充电桩无法响应,状态:".concat(status));
        }
        return R.ok();
    }

    public static R<Object> checkPileConfig(Map<String, Object> cachePile) {

        if (cachePile == null || cachePile.get("status") == null) {
            return R.fail("充电桩未注册");
        }
        String status = cachePile.get("status").toString();
        if (etable.contains(status)) {
            return R.fail("充电桩无法响应,状态:".concat(status));
        }
        //充电中不能下发

        return R.ok();
    }



    @PutMapping("charging/stop/{orderNo}/{pileNo}/{connectorId}/{version}")
    public R stopCharging(@PathVariable("orderNo") String orderNo, @PathVariable("pileNo") String pileNo,
                          @PathVariable("connectorId") String connectorId,
                          @PathVariable("version") String version) {

        String pkey = "pile:".concat(pileNo);
        Map<String, String> cachePile = REDIS.getCacheMap(pkey);
        R<Object> r = R.ok();
        if (cachePile.isEmpty()) {
            r = R.fail("充电桩未注册");
        }
//        String status = cachePile.get("status");
//        if (!REGISTERED.equals(status)) {
//            r = R.fail("充电桩离线");
//        }
        String gunkey = "gun:".concat(connectorId);
        final Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
//        if (cacheGun.get("orderkey") == null || !cacheGun.get("orderkey").toString().endsWith(orderNo) || !orderNo.contains
//        (pileNo)) {
//            r = R.fail("错误的订单号");
//        } 算了容易坑
        String gunStatus = REDIS.getCacheMapValue(gunkey, "status");
        if (("空闲".equals(gunStatus) || "离线".equals(gunStatus) || "故障".equals(gunStatus))) {
            log.error("端口不在充电中, status[{}]", gunStatus);
        }
        if (r.getCode() == 200) {
            String svcSrv = cachePile.get("svcSrv");
            String response = HttpUtils.get(fmt(svcSrv)
                    .concat("/native/charging/stop/")
                    .concat(pileNo).concat("/")
                    .concat(connectorId).concat("/")
                    .concat(version));
            r = getRR(response);
        }
//        } else {
//            r = R.fail("端口不在充电中");
//        }
        return r;
    }

    public static String fmt(String svcSrv) {

        String[] split = svcSrv.split("#");
        return "http://".concat(split[0]).concat(":").concat(split[1]);
    }

    @PostMapping("native/charging/balance/refresh")
    public R nativeRefreshBalance(@Validated @RequestBody StartChargingData refreshBalanceData) {

        String pileNo = refreshBalanceData.getPileNo();
        String gunkey = "gun:".concat(pileNo).concat(refreshBalanceData.getGunId());
        if (CacheDataUtils.hori(gunkey)) return R.fail("余额下发失败");
        String skey = gunkey.concat(".seqhex");
        String seq = seqHex(skey);
        String refreshBalanceMsg = "6818".concat(seq).concat("0042").concat(pileNo).concat(refreshBalanceData.getGunId())
                .concat(refreshBalanceData.getPhysicCardNo())
                .concat(HexUtils.toHexInt(refreshBalanceData.getBalance()));
        refreshBalanceMsg = refreshBalanceMsg.concat(CRCCalculator.calcCrc(refreshBalanceMsg));
        ClientHandler handler = getHandler(pileNo);
        R<Object> r;
        if (handler != null && handler.isOpen()) { //todo 余额下发重试机制
            if (!handler.isOpen()) {
                log.error("[{}]({}) connection lost", handler.getName(), pileNo);
                removeHandler(pileNo);
                r = R.fail("网络连接断开,无法刷新桩上余额");
            } else {
                try {
                    log.debug("native refresh balance >>> {}", refreshBalanceMsg);
                    handler.sendClientBinary(HexUtils.toBytes(refreshBalanceMsg));
                    r = R.ok("余额刷新指令已下发");
                } catch (IOException e) {
                    log.error("订单[{}]余额下发失败,终端离线故障:{}", refreshBalanceData.getOrderNo(), e.getMessage());
                    r = R.fail("网络故障,余额刷新失败");
                }
            }
        } else {
            log.error("订单[{}]余额下发失败,充电桩离线", refreshBalanceData.getOrderNo());
            r = R.fail("余额刷新失败");
        }
        return r;
    }

    @PostMapping("native/charging/start")
    public R nativeStartCharging(@Validated @RequestBody StartChargingData startChargingData) {

        String pileNo = startChargingData.getPileNo();
        ClientHandler handler = ChargingPileServer.getHandler(pileNo);
        if (handler == null) {
            return R.fail("充电桩没有连接到上次注册的服务器,请稍后再试一次");
        } else if (!handler.isOpen()) {
            log.error("[{}]({}) connection lost", handler.getName(), pileNo);
            removeHandler(pileNo);
            return R.fail("充电桩连接已断开,请稍后再试一次");
        }
        try {
            String pileKey = "pile:".concat(pileNo);
            if (CacheDataUtils.hori(pileKey)) return R.fail("充电桩正在忙碌,请重试");
            String gunkey = "gun:".concat(pileNo).concat(startChargingData.getGunId());
            Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
            String gunstatus = (String) cacheGun.get("status");
            if (!"空闲".equals(gunstatus)) {

                return R.fail("端口不在空闲或正常状态,稍后再试");
            }
            if (CacheDataUtils.hori(gunkey)) return R.fail("请检查枪号是否正确,稍后再试");
            String orderkey = "order:".concat(startChargingData.getOrderNo());
//            String oldOrderKey = (String) cacheGun.get("orderkey");
//            if (oldOrderKey!=null && !oldOrderKey.equals(orderkey)) {
//                return R.fail("端口正在充电");
//            } //todo delete oldOrderKey val?
            String skey = gunkey.concat(".seqhex");
            String seq = seqHex(skey);
            byte[] msg = translateStart(startChargingData, seq);
            handler.sendClientBinary(msg);
            Integer balance = startChargingData.getBalance();
            Map<String, Object> cacheOrder = REDIS.getCacheMap(orderkey);
            String pkey = "pile:".concat(pileNo);
            Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
            Long pileRateModelId = (Long) cachePile.get("rateModelId");
            cacheOrder.put("rateModelId", pileRateModelId);
            cacheOrder.put("pileNo", pileNo);
            cacheOrder.put("initBalance", balance * 100);
            cacheOrder.put("logicCardNo", startChargingData.getLogicCardNo());
            cacheOrder.put("physicCardNo", startChargingData.getPhysicCardNo());
            cacheOrder.put("startType", "02");
            cacheOrder.put("gunId", startChargingData.getGunId());
            cacheOrder.put("tel", startChargingData.getTel());
            cacheOrder.put("stopSoc", startChargingData.getSoc());
            cacheOrder.put("startTime",
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(Instant.now()));
            REDIS.setCacheMap(orderkey, cacheOrder);
            return R.ok("充电指令已下发");
        } catch (IOException e) {
            log.error("send message failed. " + e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @GetMapping("native/charging/stop/{pileNo}/{connectorId}/{version}")
    public R stopCharging(@PathVariable("pileNo") String pileNo, @PathVariable("connectorId") String connectorId,
                          @PathVariable("version") String version) {

        ClientHandler handler = ChargingPileServer.getHandler(pileNo);
        if (handler == null) {
            return R.fail("充电桩没有连接到上次注册的服务器,请稍后再试一次");
        }
        try {
            String pileKey = "pile:".concat(pileNo);
            if (CacheDataUtils.hori(pileKey)) return R.fail("充电桩正在忙碌,请重试");
            if (connectorId.length() == 2) { //兼容16位和2位的id
                connectorId = pileNo.concat(connectorId);
            }
            String gunkey = "gun:".concat(connectorId);
            String skey = gunkey.concat(".seqhex");
            String seq = seqHex(skey);
            byte[] msg = translateStop(connectorId, seq);
            if (!handler.isOpen()) {
                log.error("send message failed. [{}]({}) connection lost", handler.getName(), pileNo);
                removeHandler(pileNo);
                return R.ok("充电桩已离线");
            } else {
                handler.sendClientBinary(msg);
                return R.ok("停止充电指令已下发");
            }
        } catch (IOException e) {
            log.error("send message failed. " + e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    public void stopInvalidOrder(String orderNo) {

        String pileNo = orderNo.substring(0, 14);
        ClientHandler handler = ChargingPileServer.getHandler(pileNo);
        if (handler != null && handler.isOpen()) {
            try {
                String connectorId = orderNo.substring(0, 16);
                String gunkey = "gun:".concat(connectorId);
                String skey = gunkey.concat(".seqhex");
                String seq = seqHex(skey);
                byte[] msg = translateStop(connectorId, seq);
                if (!handler.isOpen()) {
                    log.error("stop invalid order failed. [{}]({}) connection lost", handler.getName(), pileNo);
                    removeHandler(pileNo);
                } else {
                    String orderkey = REDIS.getCacheMapValue(gunkey, "orderkey");
//                    Integer sts = REDIS.getCacheMapValue(orderkey, "sts");
                    if (orderkey != null && orderNo.equals(orderkey.substring(6))) {// && (sts == null)) {
                        handler.sendClientBinary(msg);
                        log.error("invalid orderNo [{}], stop msg sent to pile |{}|", orderNo, HexUtils.toHex(msg));
//                        REDIS.setCacheMapValue(orderkey, "sts", 1);
                    }
                }
            } catch (IOException e) {
                try {
                    handler.closeConnection();
                } catch (Exception e1) {
                    log.error("invalid conn [{}]", handler.getName());
                }
            }
        } else if (handler != null) {
            handler.closeConnection();
        }
    }

    private byte[] translateStart(StartChargingData startChargingData, String seq) {

        byte[] data = new byte[0];
        data = ArrayUtils.addAll(data, HexUtils.toBytes("6830".concat(seq).concat("0034")));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(startChargingData.getOrderNo()));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(startChargingData.getPileNo()));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(startChargingData.getGunId()));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(String.format("%016X", Long.parseLong(startChargingData.getLogicCardNo(), 16))));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(String.format("%016X", Long.parseLong(startChargingData.getPhysicCardNo(), 16))));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(toHexInt(startChargingData.getBalance())));
        String msg = HexUtils.toHex(data);
        msg = msg.concat(CRCCalculator.calcCrc(msg));
        log.debug("start charging order[{}], send msg >>>> |{}|", startChargingData.getOrderNo(), msg);

        // 写入设备日志表数据
        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(startChargingData.getPileNo());
        deviceMessage.setRemark("平台下发开机指令");
        deviceMessage.setStatus(0);
        deviceMessage.setContent(msg);
        deviceMessageMapper.insertByDomain(deviceMessage);
        return HexUtils.toBytes(msg);
    }

    private byte[] translateStop(String connectorId, String seq) {

        byte[] data = new byte[0];
        data = ArrayUtils.addAll(data, HexUtils.toBytes("680C".concat(seq).concat("0036")));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(connectorId));
        String msg = HexUtils.toHex(data);
        msg = msg.concat(CRCCalculator.calcCrc(msg));
        log.debug("stop charging, send msg to terminal ({}) >>>> {}", connectorId, msg);
        // 写入设备日志表数据
        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(StrUtil.sub(connectorId, 0, -2));
        deviceMessage.setRemark("平台下发停机指令");
        deviceMessage.setStatus(0);
        deviceMessage.setContent(msg);
        deviceMessageMapper.insertByDomain(deviceMessage);
        return HexUtils.toBytes(msg);
    }

    @PostMapping("charging/capacity/start")
    public R startChargingCapacity(@Validated @RequestBody StartChargingData startChargingData) {

        String pileNo = startChargingData.getPileNo();
        String pkey = "pile:".concat(pileNo);
        //log.info("==================pkey======================"+pkey);
        Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
        R<Object> r = checkPile(cachePile);
        if (r.getCode() == 200) {
            String svcSrv = (String) cachePile.get("svcSrv");
            Long stationId = (Long) cachePile.get("stationId");
            ChargingStationDto cacheStation = REDIS.getCacheObject("station:".concat(stationId.toString()));
            Long stationRateModelId = cacheStation.getRateModelId();
            Long pileRateModelId = (Long) cachePile.get("rateModelId");
            if (!stationRateModelId.equals(pileRateModelId)) {
                String resultStr = RateModelRequestLogic.translate(pileNo, stationRateModelId, "0058",
                        (String) cachePile.get("version"));
                String response = HttpUtils.post(fmt(svcSrv).concat("/native/pile/".concat(pileNo).concat("/rateModel")),
                        resultStr);
                JSONObject responseJson = (JSONObject) JSON.parse(response);
                assert responseJson != null;
                int code = responseJson.getInteger("code");
                log.error(response);
                if (code != 200) {
                    r = R.fail(code, responseJson.getString("msg"));
                } else {
                    r = R.fail(responseJson.getString("msg"));
                    REDIS.setCacheMap(pkey, cachePile);
                }
            } else {
                JSONObject json = (JSONObject) JSON.toJSON(startChargingData);
                String response = HttpUtils.post(fmt(svcSrv).concat("/native/charging/capacity/start"), json);
                r = getRR(response);
                r.setData(stationRateModelId);
            }
        }
        return r;
    }


    @PostMapping("native/charging/capacity/start")
    public R nativeStartChargingCapacity(@Validated @RequestBody StartChargingData startChargingData) {

        String pileNo = startChargingData.getPileNo();
        ClientHandler handler = ChargingPileServer.getHandler(pileNo);
        if (handler == null) {
            return R.fail("充电桩没有连接到上次注册的服务器,请稍后再试一次");
        } else if (!handler.isOpen()) {
            log.error("[{}]({}) connection lost", handler.getName(), pileNo);
            removeHandler(pileNo);
            return R.fail("充电桩连接已断开,请稍后再试一次");
        }
        try {
            String pileKey = "pile:".concat(pileNo);
            if (CacheDataUtils.hori(pileKey)) return R.fail("充电桩正在忙碌,请重试");
            String gunkey = "gun:".concat(pileNo).concat(startChargingData.getGunId());
            Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
            String gunstatus = (String) cacheGun.get("status");
            if (!"空闲".equals(gunstatus)) {

                return R.fail("端口不在空闲或正常状态,稍后再试");
            }
            if (CacheDataUtils.hori(gunkey)) return R.fail("请检查枪号是否正确,稍后再试");
            String orderkey = "order:".concat(startChargingData.getOrderNo());
//            String oldOrderKey = (String) cacheGun.get("orderkey");
//            if (oldOrderKey!=null && !oldOrderKey.equals(orderkey)) {
//                return R.fail("端口正在充电");
//            } //todo delete oldOrderKey val?
            String skey = gunkey.concat(".seqhex");
            String seq = seqHex(skey);
            byte[] msg = translateChargingCapacityStart(startChargingData, seq);
            handler.sendClientBinary(msg);
            Integer balance = startChargingData.getBalance();
            Map<String, Object> cacheOrder = REDIS.getCacheMap(orderkey);
            String pkey = "pile:".concat(pileNo);
            Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
            Long pileRateModelId = (Long) cachePile.get("rateModelId");
            cacheOrder.put("rateModelId", pileRateModelId);
            cacheOrder.put("pileNo", pileNo);
            cacheOrder.put("initBalance", balance * 100);
            cacheOrder.put("logicCardNo", startChargingData.getLogicCardNo());
            cacheOrder.put("physicCardNo", startChargingData.getPhysicCardNo());
            cacheOrder.put("startType", "02");
            cacheOrder.put("gunId", startChargingData.getGunId());
            cacheOrder.put("tel", startChargingData.getTel());
            cacheOrder.put("stopSoc", startChargingData.getSoc());
            cacheOrder.put("startTime",
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(Instant.now()));
            REDIS.setCacheMap(orderkey, cacheOrder);
            return R.ok("充电指令已下发");
        } catch (IOException e) {
            log.error("send message failed. " + e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    private byte[] translateChargingCapacityStart(StartChargingData startChargingData, String seq) {

        byte[] data = new byte[0];
        data = ArrayUtils.addAll(data, HexUtils.toBytes("6832".concat(seq).concat("0038")));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(startChargingData.getOrderNo()));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(startChargingData.getPileNo()));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(startChargingData.getGunId()));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(String.format("%016X", Long.parseLong(startChargingData.getLogicCardNo(), 16))));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(String.format("%016X", Long.parseLong(startChargingData.getPhysicCardNo(), 16))));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(toHexInt(startChargingData.getBalance())));
        data = ArrayUtils.addAll(data, HexUtils.toBytes(toHexIntYu(startChargingData.getChargingCapacity())));

        String msg = HexUtils.toHex(data);
        msg = msg.concat(CRCCalculator.calcCrc(msg));
        log.debug("start charging capacity order[{}], send msg >>>> |{}|", startChargingData.getOrderNo(), msg);

        // 写入设备日志表数据
        XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
        deviceMessage.setType(StationDeviceEnum.PILE.getCode());
        deviceMessage.setSerialNumber(startChargingData.getPileNo());
        deviceMessage.setRemark("平台下发开机指令");
        deviceMessage.setStatus(0);
        deviceMessage.setContent(msg);
        deviceMessageMapper.insertByDomain(deviceMessage);
        return HexUtils.toBytes(msg);
    }



    public static void main(String[] args) {
//        Integer FFFF = HexUtils.reverseHexInt("0452");
//        System.out.println("51 转化成="+FFFF);

        Integer F402 = HexUtils.reverseHexInt("04010000");
        System.out.println("F402 转化成="+F402);

//        Integer D007 = HexUtils.reverseHexInt("D007");
//        System.out.println("D007 转化成="+D007);
//
//        Integer F620 = HexUtils.reverseHexInt("F620");
//        System.out.println("F620 转化成="+F620);
//
//        Integer F03 = HexUtils.reverseHexInt("03");
//        System.out.println("F03 转化成="+F03);
//
        Integer D3C0F = HexUtils.reverseHexInt("385A");
        System.out.println("3C0F 转化成="+D3C0F);
//
//        Integer f4C1D = HexUtils.reverseHexInt("4C1D");
//        System.out.println("f4C1D 转化成="+f4C1D);
//
//        Integer DC05 = HexUtils.reverseHexInt("DC05");
//        System.out.println("DC05 转化成="+DC05);
//
//        Integer A00F = HexUtils.reverseHexInt("A00F");
//        System.out.println("A00F 转化成="+A00F);
//
//        Integer FCF3 = HexUtils.reverseHexInt("FCF3");
//        System.out.println("FCF3 转化成="+FCF3);
//
//
//
//        Integer f70C0001 = HexUtils.reverseHexInt("D8B68A0400");
//        System.out.println("f70C0001 转化成="+f70C0001);
//
//        Integer f70C0002 = HexUtils.reverseHexInt("C2E00200");
//        System.out.println("f70C0002 转化成="+f70C0002);
//
//        String s = HexUtils.reverseHex("38C7280A1D0817");
//        System.out.println("s 转化成="+s);
//        String s = toHexInt(3532);
//        System.out.println("3532 转化成BIN码="+s);
//        byte[] bytes = HexUtils.toBytes("80836000150001022305301518050003");
//        System.out.println("String 转化成Byte[]="+ Arrays.toString(bytes));
//        String msg = HexUtils.toHex(bytes);
//        System.out.println("Byte 转化成String="+ msg);
//        double vs = 76011030;
//        double v = vs / 10000;
//        DecimalFormat df = new DecimalFormat("#.000");
//        System.out.println(df.format(v));

//        String s = CP56Time2a.p56toDateStr("C05D2011200318");
//
//        System.out.println("-111-变为--:" + s);
//
//        String s1 = cp56toDateStr("88903507220418");
//
//        System.out.println("-111-变为--:" + s1);

//        String ascii = HexUtils.toAscii("828dcc2624042615");
//       System.out.println("ascii :"+ascii);


    }

}
