package me.zhengjie.modules.quartz.task;

import java.io.*;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dm.device.service.DmDeviceService;
import me.zhengjie.modules.dm.device.service.dto.DmDeviceDto;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
public class SocketTask {
    private final DmDeviceService dmDeviceService;
    public static Socket socket;

    public void socket() {
        try {
            log.info("启动客户端");
            socket = new Socket("10.208.128.17", 12606);
            log.info("客户端连接服务器成功");
            List<DmDeviceDto> dmDeviceDtos = dmDeviceService.queryAll();
            List<String> cardIpList = new ArrayList<>();
            for(DmDeviceDto dmDeviceDto : dmDeviceDtos){
                cardIpList.add(dmDeviceDto.getCardIp());
            }
            JSONObject sendJSON = new JSONObject();
            sendJSON.put("Action",103);
            sendJSON.put("printerid",cardIpList);

            DecimalFormat decimalFormat = new DecimalFormat("00000000");
            String numFormat = decimalFormat.format(JSONObject.toJSONString(sendJSON).length());
            String sendString = "#print#"+numFormat+"#"+JSONObject.toJSONString(sendJSON);
            log.info("客户端发送字符串:"+sendString);
            sendTcpMessage(sendString);
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            InputStream inputStream = socket.getInputStream();
            byte[] buffer = new byte[5000];
            int len = -1;
            String data = "";
            while ((len = inputStream.read(buffer)) != -1) {
                data = new String(buffer, 0, len);
            }
            data = data.substring(data.lastIndexOf("#")+1);
            log.info("收到服务器的数据:" + data);
            JSONObject dataJSON = JSONObject.parseObject(data);
            Integer code = dataJSON.getInteger("code");
            if(code == 0){
                JSONArray items = dataJSON.getJSONArray("items");
                for(int i = 0; i<items.size();i++){
                    JSONObject item = items.getJSONObject(i);
                    String status = item.getString("status");
                    if(StringUtils.isEmpty(status)){
                        status = "00";
                    } else if(StringUtils.equals(status,"14") || StringUtils.equals(status,"19")) {
                        status = "01";
                    } else {
                        status = "02";
                    }
                    String cardIp = item.getString("printerid");
                    log.info("cardIp:"+cardIp);
                    dmDeviceService.updateStatus(cardIp,status);
                }
            } else {
                log.info("状态码不正确");
            }
            log.info("客户端连接服务器断开");
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("客户端连接服务器失败");
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            socket = null;
        }
    }

    public static void sendTcpMessage(final String msg) {
        if (socket != null && socket.isConnected()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        socket.getOutputStream().write(msg.getBytes());
                        socket.getOutputStream().flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            socket.shutdownOutput();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

}
