package com.usky.agbox.service.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.agbox.domain.PatrolInspectionAgbox;
import com.usky.agbox.service.PatrolInspectionAgboxService;
import com.usky.agbox.service.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Component
public class patrolAgbox {

    @Value("${agBox.key}")
    private String KEY;
    @Value("${agBox.url}")
    private String URL;

    @Autowired
    private PatrolInspectionAgboxService patrolInspectionAgboxService;

    public static void sendMessage(String host, int port, String xmlData) {
        try (Socket socket = new Socket(host, port);
             OutputStream os = socket.getOutputStream();
             Writer writer = new OutputStreamWriter(os)) {
            String str = "QWCMD:";
            byte[] byteArray = str.getBytes();
            // 定义消息头的长度为4个字节
            byte[] header = new byte[20];
            ByteBuffer buffer = ByteBuffer.wrap(header);
            buffer.put(byteArray);
            // 将XML数据的长度转换为字节，并填充到消息头中
            buffer.putInt(xmlData.getBytes().length);
            // 发送消息头
            os.write(header);
            // 发送XML数据
            writer.write(xmlData);
            writer.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取推送配置信息
     * @return
     */
    public List<PatrolInspectionAgbox> getAgBox() {
        LambdaQueryWrapper<PatrolInspectionAgbox> lambdaQuery = Wrappers.lambdaQuery();
        List<PatrolInspectionAgbox> list = patrolInspectionAgboxService.list(lambdaQuery);
        return list;
    }

    /**
     * 获取事件编码信息
     * @return
     */
    public JSONObject getEventCode() {
        List<PatrolInspectionAgbox> list = this.getAgBox();
        HashMap map = new HashMap();
        map.put("key", list.get(0).getAgboxKey());
        map.put("json", "{\"jsonrpc\":\"2.0\",\"method\":\"getPatrolEventCode\"}");
        String resultString = HttpClientUtils.doPost(list.get(0).getAgboxUrl(),map);
        JSONObject resultVO = JSONObject.parseObject(resultString);
        return resultVO;
    }

    /**
     * 获取设备列表信息
     * @return
     */
    public JSONObject getDeviceList() {
        List<PatrolInspectionAgbox> list = this.getAgBox();
        HashMap map = new HashMap();
        map.put("key", list.get(0).getAgboxKey());
        map.put("json", "{\"jsonrpc\":\"2.0\",\"method\":\"getDeviceList\"}");
        String resultString = HttpClientUtils.doPost(list.get(0).getAgboxUrl(),map);
        JSONObject resultVO = JSONObject.parseObject(resultString);
        return resultVO;
    }

    /**
     * 添加事件信息
     * @return
     */
    public JSONObject addEvent(String requestBody) {
        List<PatrolInspectionAgbox> list = this.getAgBox();
        JSONObject eventVO = JSONObject.parseObject(requestBody);
        HashMap map = new HashMap();
        map.put("key", list.get(0).getAgboxKey());
        map.put("json", "{\"jsonrpc\":\"2.0\",\"method\":\"addEvent\",\"params\":{\"deviceId\":\""+eventVO.get("deviceId").toString()+"\"," +
                "\"triggerTime\":\""+eventVO.get("triggerTime").toString()+"\",\"eventCode\":"+eventVO.get("eventCode")+",\"name" +
                "\":\""+eventVO.get("name").toString()+"\",\"certifiedNo\":\""+eventVO.get("certifiedNo").toString()+"\"}}");
        String resultString = HttpClientUtils.doPost(list.get(0).getAgboxUrl(),map);
        JSONObject resultVO = JSONObject.parseObject(resultString);
        LocalDateTime now = LocalDateTime.now();
//        String host = "127.0.0.1";
        int port = 5901;
        String xmlData = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>  \n" +
                "<Agent ID=\"SGT100006088\" Type=\"SG\" Ver=\"1.2.0.0\">\n" +
                "<DVRHeart State=\"0\" TotalSpace=\"1000\" FreeSpace=\"500\">\n" +
                "System,smss.exe,csrss.exe\n" +
                "</DVRHeart>\n" +
                "<GetTicks/>\n" +
                "<OperationCmd Type=\"18\" Channel=\"2\" TriggerTime=\""+now+"\" Note=\"5rWL6K+V\" " +
                "GUID=\"7b726e15-4d45-53e7-f0e0-0abb91156fd7\">\n" +
                "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9V\n" +
                "</OperationCmd>\n" +
                "</Agent>";
        sendMessage(URL, port, xmlData);
        return resultVO;
    }

    /**
     * 更新心跳信息
     * @return
     */
    public JSONObject updateHeart(String requestBody) {
        List<PatrolInspectionAgbox> list = this.getAgBox();
        JSONObject eventVO = JSONObject.parseObject(requestBody);
        HashMap map = new HashMap();
        map.put("key", list.get(0).getAgboxKey());
        map.put("json",
                "{\"jsonrpc\":\"2.0\",\"method\":\"updateHeart\",\"params\":{\"deviceId\":\""+eventVO.get("deviceId").toString()+"\"}}");
        String resultString = HttpClientUtils.doPost(list.get(0).getAgboxUrl(),map);
        JSONObject resultVO = JSONObject.parseObject(resultString);
        return resultVO;
    }

    /**
     * 获取事件信息
     * @return
     */
    public JSONObject getEvent(String requestBody) {
        List<PatrolInspectionAgbox> list = this.getAgBox();
        JSONObject eventVO = JSONObject.parseObject(requestBody);
        HashMap map = new HashMap();
        map.put("key", list.get(0).getAgboxKey());
        map.put("json", "{\"jsonrpc\":\"2.0\",\"method\":\"getEvent\",\"params\":{\"eventId\":\""+eventVO.get("eventId").toString()+"\"}}");
        String resultString = HttpClientUtils.doPost(list.get(0).getAgboxUrl(),map);
        JSONObject resultVO = JSONObject.parseObject(resultString);
        return resultVO;
    }
}
