package com.cisdi.data.XRFRIGHT.impl;

import com.alibaba.fastjson.JSON;
import com.cisdi.data.common.exception.BusinessException;
import com.cisdi.data.sdk.consts.ServiceName;
import com.cisdi.data.sdk.gateway.message.SocketMessage;
import com.cisdi.data.sdk.gateway.netty.IoSession;
import com.cisdi.data.sdk.gateway.netty.impl.AbstractIoSession;
import com.cisdi.data.sdk.service.PassthroughService;
import com.cisdi.data.sdk.service.SendService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cuianbing
 * @version 1.0
 * @description: TODO
 * @date 2021/7/7 18:53
 */
@Slf4j
public class XRFRightIoSession extends AbstractIoSession implements IoSession {

    private XRFRightSessionFactory factory = null;

    private String deviceId = null;
    /**
     * 如果有值，代表所有会话都使用这一个设备id，且允许多会话共享此一个设备id，不T除旧会话
     */
    private String onlyOneDeviceId;

    private String gwPrefixCache = null;

    private ByteBuf allBuf = ByteBufAllocator.DEFAULT.buffer();


    public XRFRightIoSession(XRFRightSessionFactory factory, String onlyOneDeviceId) {
        super();
        this.factory = factory;
        this.onlyOneDeviceId = onlyOneDeviceId;
    }

    @Override
    public String[] getDeviceIds() {
        String cpDeviceId = deviceId;
        String[] result = new String[cpDeviceId == null ? 0 : 1];
        if (cpDeviceId != null) {
            result[0] = cpDeviceId;
        }
        return result;
    }

    @Override
    public void onRead(Object message) {
        try {

            Map<String, Object> resultMap = new HashMap<>();
            Integer readerIndex = null;
            /**
             * message head
             */
            ByteBuf inBuf = (ByteBuf) message;
            if (inBuf != null) {
                allBuf.writeBytes(inBuf);
            }else {
                log.info("电文格式为空");
            }
        }catch (Exception e){
            log.error("电文格式错误！");
            throw new BusinessException("电文格式错误！");
        }

    }

    @Override
    public void onOpen() {
        super.onOpen();
        log.info("建立连接，channel:{}", getChannel());
    }

    @Override
    public void onClose() {
        log.info("onClose");
        if (allBuf != null && allBuf.readableBytes() > 0){
            Map<String, String> message = decode(allBuf);
            Map<String, Object> sendMessage =new HashMap<>();
            sendMessage.put("data",message);
            if (serviceProvider != null && socketGateway != null) {
                SendService service = (SendService) serviceProvider.getByName(ServiceName.Send);
                SocketMessage socketMessage = socketGateway.buildSocketMessage();
                socketMessage.setDeviceId(onlyOneDeviceId);
                socketMessage.setData(JSON.toJSONString(sendMessage).getBytes(Charset.forName("UTF-8")));
                socketMessage.setMsgKey("default");
                service.sendMessage(socketMessage);
                if (socketGateway.getInstanceVo().getLogOpen()) {
                    log.info("类似为:{}:发送消息内容{}", sendMessage.get("data"), sendMessage.toString());
                }
            }
        }
        super.onClose();
        factory = null;
    }


    private void passThrough(ByteBuf passthroughBuf) {
        try {
            if (serviceProvider != null && socketGateway != null) {
                PassthroughService service = (PassthroughService) serviceProvider.getByName(ServiceName.Passthrough);
                service.transfer(passthroughBuf, socketGateway.getInstanceVo().getPassthroughAddress());
            }
        } catch (Exception e) {
            log.error("荧光光谱仪协议透传失败：" + e.getLocalizedMessage(), e);
        }
    }

    public String gwPrefix() {
        if (gwPrefixCache != null) {
            return gwPrefixCache;
        }

        gwPrefixCache = "";
        if (socketGateway != null && socketGateway.getInstanceVo() != null) {
            gwPrefixCache = "网关Id:" + socketGateway.getInstanceVo().getRunId() + "连接:" + getChannel() + " ";
        } else {
            gwPrefixCache = "连接:" + getChannel() + " ";
        }

        return gwPrefixCache;
    }


    public void close() {
        if (getChannel() != null) {
            try {
                getChannel().close().sync();
            } catch (InterruptedException e) {
                log.warn(e.getLocalizedMessage(), e);
            }
        }
    }


    public  Map<String,String> decode(ByteBuf byteBuf){
        Map<String,String> data = new HashMap();
        String msg = byteBuf.toString(Charset.forName("GB2312"));
        String[] strLines = msg.split("\n\r");
        for (String strLine : strLines){
            char startChat = strLine.charAt(0);
            if (startChat == '2'){
                // 27 石灰石   2021071600113-010720210717150951
                // 27 硅锰合金 071600096       1120210717155618
                String[] word = strLine.split("\\s+");
                data.put("编码",word[0]);
                data.put("code",word[1]);
                if (word[2].length() > 16){
                    data.put("name",word[2].substring(0,16));
                    data.put("dateTime",word[2].substring(18,30));
                }else {
                    data.put("name",word[2]);
                    data.put("dateTime",word[3].substring(2,14));
                }


            }else if (startChat == '3'){
                String[] word = strLine.substring(1).split("\\s+");
                for (int i = 0; i < word.length -1 ;i = i+2){
                    data.put(word[i],word[i+1]);
                }
            }
        }

        allBuf.clear();
        log.debug("解析的数据为：{}",data);
        return data;
    }



}
