package com.xxxxtech.srac.modules.relay;

import com.xxxxtech.srac.commom.Constants;
import com.xxxxtech.srac.utils.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

/**
 * FileName：OperationUtils <br>
 * CreateTime： 2019-08-14 17:58 <br>
 * Description：<br>
 * 继电器操作集合，包括开/关门和开/关灯。
 *
 * @author Dawson <br>
 * @version v0.1  <br>
 * @since JDK 1.8
 */

@Deprecated
// 不建议使用，请使用ModbusUtil
public class OperationUtils {

    public static final int ORDER_TYPE_OPEN_DOOR = 0;
    public static final int ORDER_TYPE_OPEN_LIGHT = 1;

    /**
     * 灯光控制，当前使用
     *
     * @param ip          继电器组IP地址
     * @param relayNo     继电器编号
     * @param time        结束时间
     * @param isOpenRelay ture - 开继电器灯，false - 关继电器灯  （开灯控 = 开继电器灯，开门 = 关继电器灯）
     */
    public void lightingControl(String ip, int relayNo, int time, boolean isOpenRelay, int type) {
        Socket lightClient = new Socket();
        String message = "";
        if(lightClient.isConnected()){
            try {
                lightClient.close();
            } catch (IOException e) {
                return;
            }
        }
        while (true) {
            try {
                //  准备开灯
                System.out.println("正在连接......" + ip);
                lightClient.connect(new InetSocketAddress(ip, 10000), 4000);
                OutputStream sendMsg = lightClient.getOutputStream();
                InputStream getMsg = lightClient.getInputStream();
                //  不能大于32
                if (isOpenRelay) {
                    message = Constants.open_instruction[relayNo];
                } else {
                    message = Constants.close_instruction[relayNo];
                }
                byte[] bytes = StringUtils.hexStrToBinaryStr(message);
                sendMsg.write(bytes);
                sendMsg.flush();
                String gmsg = StringUtils.bytesToHex(getMsg).toUpperCase();
                System.out.println(" >> " + gmsg);
                sendMsg.close();
                lightClient.close();
                System.out.println("关闭连接");

                Thread.sleep(4 * 1000);
                switchLight(ip, relayNo, true);
                // 开门后N秒后自动关门，isOpen 为继电器灯状态，继电器灯为开（isOpen = true）时, 为关门，相反则开门
//                if (time > 0 && !isOpenRelay && type == ORDER_TYPE_OPEN_DOOR) {
//                    redisUtils.set(ip + "_" + relayNo, ip, time);
//                    redisUtils.set(Integer.toString(relayNo), ip + "_" + relayNo);
//                }
                break;
            } catch (Exception e2) {
                e2.printStackTrace();
                if (lightClient != null) {
                    try {
                        if (lightClient.isConnected()) {
                            lightClient.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //TODO: 这里应该要提醒店家没有打开继电器
                break;
            } finally {
                if (lightClient != null) {
                    try {
                        if (lightClient.isConnected()) {
                            lightClient.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
        }
    }


    public static void checkStatus(String ip, String doorNo, String time, boolean isOpenRelay) {
        Socket lightClient;
        String message = "FE010000002029DD";
        while (true) {
            try {
                System.out.println("正在连接......" + ip);
                lightClient = new Socket(ip, 10000);
                System.out.println(">>>>> 灯控连接成功: " + lightClient);
                OutputStream sendMsg = lightClient.getOutputStream();
                InputStream getMsg = lightClient.getInputStream();
                //  不能大于32
                System.out.println(" 发送指令: " + message);
                byte[] bytes = StringUtils.hexStrToBinaryStr(message);
                sendMsg.write(bytes);
                sendMsg.flush();
                sendMsg.close();
                lightClient.close();
                System.out.println("关闭连接");
                break;
            } catch (UnknownHostException | ConnectException es) {
                es.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }

    public void switchLight(String ip, int id, boolean isOpen) {
        Socket lightClient = new Socket();
        String message = "";
        if(lightClient.isConnected()){
            try {
                lightClient.close();
            } catch (IOException e) {
                return;
            }
        }
        while (true) {
            try {
                //  准备开灯
                System.out.println("正在连接......" + ip);
                lightClient.connect(new InetSocketAddress(ip, 10000), 4000);
                OutputStream sendMsg = lightClient.getOutputStream();
                InputStream getMsg = lightClient.getInputStream();
                //  不能大于32
                if (isOpen) {
                    message = Constants.open_instruction[id];
                } else {
                    message = Constants.close_instruction[id];
                }
                byte[] bytes = StringUtils.hexStrToBinaryStr(message);
                sendMsg.write(bytes);
                sendMsg.flush();
                String gmsg = StringUtils.bytesToHex(getMsg).toUpperCase();
                sendMsg.close();
                lightClient.close();
                System.out.println("关闭连接");


                break;
            } catch (Exception e2) {
//                e2.printStackTrace();
                if (lightClient != null) {
                    try {
                        if (lightClient.isConnected()) {
                            lightClient.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //TODO: 这里应该要提醒店家没有打开继电器
                break;
            } finally {
                if (lightClient != null) {
                    try {
                        if (lightClient.isConnected()) {
                            lightClient.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
        }
    }

    // 继电器状态，如果是true，不发送关门指令
    private boolean relayStatus = false;

    /**
     * 监听服务器
     * @param ip
     */
    public void listenServer(String ip, List<Integer> doorList) {
        Socket lightClient = new Socket();
        String message = "";
        while (true) {
            try {
                //  准备开灯
//                System.out.println("正在连接......" + ip);
                lightClient.connect(new InetSocketAddress(ip, 10000), 2000);
                lightClient.close();
//                System.out.println("关闭连接");

                if (!relayStatus && doorList != null) {
                    for (Integer doorNo: doorList) {
                        this.switchLight(ip, doorNo, true);
                    }
                    relayStatus = true;
                }

                Thread.sleep(1 * 1000);
                this.listenServer(ip, doorList);
                break;
            } catch (Exception e2) {
                relayStatus = false;
//                e2.printStackTrace();
//                System.out.println(" >>>>>>>>>>>>>>>>>> " + lightClient);
                try {
                    Thread.sleep(1 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                listenServer(ip, doorList);
                break;
            } finally {
                if (lightClient != null) {
                    try {
                        if (lightClient.isConnected()) {
                            lightClient.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
        }
    }

    public static void main(String[] args) {
        OperationUtils operationUtils = new OperationUtils();
        operationUtils.switchLight("192.168.1.45", 0, true);
//        List<Integer> doorList = new ArrayList<>();
//        doorList.add(0);
//        doorList.add(1);
////

//        new Thread(()->operationUtils.listenServer("192.168.1.103", doorList)).start();
//        new Thread(()->operationUtils.listenServer("192.168.1.102", doorList)).start();
//        operationUtils.listenServer("192.168.1.103", doorList);
//        OperationUtils operationUtils1 = new OperationUtils();
//        operationUtils1.listenServer("192.168.1.102", doorList);


    }
}
