package com.jpsoft.uniview.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jpsoft.uniview.dto.PersonVerification;
import com.jpsoft.uniview.dto.PersonVerificationResponseInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class PersonVerificationHandler extends SimpleChannelInboundHandler<PersonVerification> {
    private  final String X_FRAME_OPTIONS = "X-Frame-Options";
    private  final String SAMEORIGIN = "SAMEORIGIN";
    private  final String JSON_PLAIN = "application/json";
    private  final String CONTENT_LENGTH = "Content-Length";
    private  final String CONTENT_TYPE = "Content-Type";
    private  final String CONNECTION = "Connection";

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersonVerification personVerification) throws Exception {
        try {
            JSONObject jsonObject = personVerification.getJsonObject();
            JSONObject faceJson = new JSONObject(jsonObject.getStr("FaceInfoList").substring(1,jsonObject.getStr("FaceInfoList").length()-1));

            Long timestamp = faceJson.getLong("Timestamp");

            if (timestamp.toString().length()<13){
                double timestampDouble = timestamp *  Math.pow(10, 13 - timestamp.toString().length());
                timestamp =new Double(timestampDouble).longValue() ;
            }

            //设备序列号
            String deviceNo = jsonObject.getStr("DeviceCode");

            Date date = new Date(timestamp);

            // 记录上传响应后，必须返回否则会经过保活间隔设置时间后重发
            // 此时如果是临时顶替，则不返回，等正式服务器启动后再返回
            //sendVerficationResponse(ctx, jsonObject);

            JSONObject libMatInfoListJson = jsonObject.getJSONArray("LibMatInfoList").getJSONObject(0);
            long matchPersonID = libMatInfoListJson.getLong("MatchPersonID");

            //匹配人员信息
            JSONObject matchPersonInfo = new JSONObject();
            if (StringUtils.isNotBlank(libMatInfoListJson.getStr("MatchPersonInfo"))){
                matchPersonInfo = libMatInfoListJson.getJSONObject("MatchPersonInfo");
            }

            String personName = matchPersonInfo.getStr("PersonName");

            //remoteControl(ctx,deviceNo, matchPersonID, personName, date);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    private void sendVerficationResponse(ChannelHandlerContext ctx, JSONObject jsonObject) throws UnsupportedEncodingException {
        log.warn("===人员记录回包处理 start===");
        PersonVerificationResponseInfo responseInfo = new PersonVerificationResponseInfo();

        responseInfo.getResponse().setResponseURL("/LAPI/V1.0/PACS/Controller/Event/Notifications");
        responseInfo.getResponse().setStatusCode(0);
        responseInfo.getResponse().setStatusString("Succeed");

        //即记录推送中的"ID"（长连接V1）或"Seq"（长连接 V2）
        if (jsonObject.containsKey("ID")) {
            responseInfo.getResponse().getData().setRecordID(jsonObject.getInt("ID"));
        } else {
            responseInfo.getResponse().getData().setRecordID(jsonObject.getInt("Seq"));
        }

        responseInfo.getResponse().getData().setTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));

        String json = JSONUtil.toJsonStr(responseInfo);

        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(json.getBytes("UTF-8")));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(CONTENT_TYPE, JSON_PLAIN);
        response.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
        response.headers().set(X_FRAME_OPTIONS, SAMEORIGIN);

        ctx.channel().writeAndFlush(response);

        log.warn("===人员记录回包结束 end===");
    }

    /**
     * 远程开门需要关闭记录上传响应，否则会不停重发(因为没有正确返回ID或Seq)
     * @param ctx
     * @param deviceNo
     * @param matchPersonID
     */
    private void remoteControl(ChannelHandlerContext ctx,String deviceNo, Long matchPersonID,String matchPersonName, Date recordTime) {
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");

            System.out.println(sdf1.format(recordTime));

            HashMap<String, Object> map = new HashMap<>();
            List<Map> showInfoListMap = new ArrayList<>();
            Map<String, Object> showInfoMap1 = new HashMap<>();
            Map<String, Object> showInfoMap2 = new HashMap<>();

            int resultCode = 1; //0:不开门， 1:开门
            String resultMsg = "允许通行";

            map.put("ResultCode", resultCode);
            map.put("ResultMsg", resultMsg);
            map.put("PassTime", sdf1.format(recordTime));
            map.put("ShowInfoNum", 2);

            showInfoMap1.put("Key", "姓名:");
            showInfoMap1.put("Value", matchPersonName);
            showInfoListMap.add(showInfoMap1);

            showInfoMap2.put("Key", "状态:");
            showInfoMap2.put("Value", resultMsg);
            showInfoListMap.add(showInfoMap2);

            map.put("ShowInfoList", showInfoListMap);

            JSONObject jsonObject = new JSONObject(map);
            String msg = jsonObject.toString();

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

            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,"/LAPI/V1.0/PACS/Controller/GUIShowInfo",byteBuf);

            //必须设置content_length,否则返回报错
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
            ctx.channel().writeAndFlush(request);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }
}
