package com.jpsoft.shinestar.modules.uniview.request;

import com.alibaba.fastjson.JSONObject;
import com.jpsoft.shinestar.modules.uniview.exception.OfflineException;
import com.jpsoft.shinestar.modules.uniview.utils.LapiSessionUtil;
import com.jpsoft.shinestar.modules.uniview.channel.LapiChannel;
import com.jpsoft.shinestar.modules.sys.entity.SysLog;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class LapiRequest {
    @Autowired
    private SysLogService sysLogService;

    public JSONObject sendJson(String deviceNo, String uri,HttpMethod httpMethod,JSONObject requestBody) throws Exception{
        LapiChannel lapiChannel = LapiSessionUtil.get(deviceNo);

        if (lapiChannel==null){
            throw new OfflineException("设备已离线!");
        }
        else if(lapiChannel.getChannel()!=null && !lapiChannel.getChannel().isOpen()){
            throw new OfflineException("设备未联网!");
        }

        String msg = "";

        if (requestBody!=null) {
            msg = requestBody.toJSONString();
        }

        ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes("UTF-8"));

        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod,uri,byteBuf);

        //必须设置content_length,否则返回报错
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());

        lapiChannel.getChannel().writeAndFlush(request).sync();

        SysLog sysLog = new SysLog();
        sysLog.setPointcut(deviceNo);
        sysLog.setUrl(uri);

        String shortUri = uri;

        if (uri.indexOf("?")>0)
        {
            shortUri = uri.substring(0,uri.lastIndexOf("?"));
        }

        BlockingQueue<String> queue = lapiChannel.getReceivePacketQueue(shortUri);

        String body = "";

        if(queue!=null) {
            body = queue.poll(10, TimeUnit.SECONDS);
        }
        else{
            sysLog.setRemark("设备" + deviceNo + "uri对应队列不存在!");
        }

        if (StringUtils.isNotEmpty(msg) && msg.length()>255) {
            sysLog.setData(msg.substring(0,255));
        }
        else{
            sysLog.setData(msg);
        }

        if (StringUtils.isNotEmpty(body)){
            if (body.length()>255){
                sysLog.setRemark(body.substring(0,255));
            }
            else{
                sysLog.setRemark(body);
            }
        }

        SocketAddress remoteAddress = lapiChannel.getChannel().remoteAddress();
        sysLog.setRemoteIp(remoteAddress.toString());
        sysLog.setCreateTime(new Date());
//        sysLogService.insert(sysLog);

        if (StringUtils.isNotEmpty(body)){
            JSONObject jsonObject = JSONObject.parseObject(body);

            return jsonObject;
        }
        else{
            throw new OfflineException("设备不在线");
            //    return null;
        }
    }

    public JSONObject send(String deviceNo, String uri,HttpMethod httpMethod,HashMap map) throws Exception{
        LapiChannel lapiChannel = LapiSessionUtil.get(deviceNo);

        if (lapiChannel==null){
            throw new OfflineException("设备已离线!");
        }
        else if(lapiChannel.getChannel()!=null && !lapiChannel.getChannel().isOpen()){
            throw new OfflineException("设备未联网!");
        }

        String msg = "";

        if (map!=null) {
            msg = new JSONObject(map).toJSONString();
        }

        ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes("UTF-8"));

        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod,uri,byteBuf);

        //必须设置content_length,否则返回报错
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());

        lapiChannel.getChannel().writeAndFlush(request).sync();

        SysLog sysLog = new SysLog();
        sysLog.setPointcut(deviceNo);
        sysLog.setUrl(uri);

        String shortUri = uri;

        if (uri.indexOf("?")>0)
        {
            shortUri = uri.substring(0,uri.lastIndexOf("?"));
        }

        BlockingQueue<String> queue = lapiChannel.getReceivePacketQueue(shortUri);

        String body = "";

        if(queue!=null) {
            body = queue.poll(10, TimeUnit.SECONDS);
        }
        else{
            sysLog.setRemark("设备" + deviceNo + "uri对应队列不存在!");
        }

        if (StringUtils.isNotEmpty(msg) && msg.length()>255) {
            sysLog.setData(msg.substring(0,255));
        }
        else{
            sysLog.setData(msg);
        }

        if (StringUtils.isNotEmpty(body)){
            if (body.length()>255){
                sysLog.setRemark(body.substring(0,255));
            }
            else{
                sysLog.setRemark(body);
            }
        }

        SocketAddress remoteAddress = lapiChannel.getChannel().remoteAddress();
        sysLog.setRemoteIp(remoteAddress.toString());
        sysLog.setCreateTime(new Date());
//        sysLogService.insert(sysLog);

        if (StringUtils.isNotEmpty(body)){
            JSONObject jsonObject = JSONObject.parseObject(body);

            return jsonObject;
        }
        else{
            throw new OfflineException("设备响应超时!");
            //    return null;
        }
    }
}
