#include "threadSendTCP.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <qtcpsocket.h>
#include <PLCDevice.h>
#pragma comment(lib, "ws2_32.lib")

extern PLCDevice* m_PLCTCPDevice;
extern PLCDevice* m_PLCDevice;
void threadSendTCP::init(SyncQueue<_TCPSendInfo>* p_TCP_Info_queue, std::string ip_, int port_) {
    ip = QString::fromStdString(ip_);
    port = port_;
    qDebug() << "tcp ip:" << ip << "| tcp port:" << port;
    Local_TCP_Info_queue = p_TCP_Info_queue;

#ifdef __TCPServer
    tcpServer = new QTcpServer(this);
	tcpServer->listen(QHostAddress::Any, port);// Equivalent to QHostAddress("127.0.0.1").
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
	connect(mySocket, SIGNAL(connected()), this, SLOT(onClientConnected()));
	connect(mySocket, SIGNAL(disconnected()), this, SLOT(onClientDisconnected()));
#endif

}
void threadSendTCP::start_work()
{
    //start(HighestPriority);///
    start();
 
}

void threadSendTCP::stop()
{
#ifdef __TCPServer
	if (tcpServer->isListening())
		tcpServer->close();
	if(tcpServer) delete tcpServer;
#endif
#ifdef __TCPClient
    mySocket->deleteLater();
    if (mySocket) delete mySocket;
#endif
    isLoop = false;
    // wait();

}

#ifdef __TCPClient
bool threadSendTCP::connectTCP() {
    mySocket = new QTcpSocket();
    // 取消已有的连接
    mySocket->abort();
    // 连接服务器
    mySocket->connectToHost(ip, port);
    if (!mySocket->waitForConnected(100)) {
       qDebug() << "connect failed!";
       return false;
    }
    qDebug() << "connect successfully!";
    
    return true;
}
#endif

void threadSendTCP::run()
{
    
#ifdef __TCPClient
    if (!connectTCP())
    {
        qDebug() << "TCP connect error!";
    }
#endif
    while (isLoop) {
        _TCPSendInfo TCPSendInfo;
        Local_TCP_Info_queue->take(TCPSendInfo);
        num++;
        sendData(&TCPSendInfo, num);
#ifdef __TCPServer
        if (ClientStatus == QAbstractSocket::ConnectedState)
        {
            sendData(&TCPSendInfo, num);
        }
#endif
#ifdef __TCPClient
        sendData(&TCPSendInfo, num);
#endif
      //mySocket->write("Hello! here is tcp client!\n");
      //mySocket->flush();
      
    }
}


void threadSendTCP::sendData(_TCPSendInfo* TCPSendInfo, int Num) {

    std::string fileName = TCPSendInfo->pics_name;
    QDateTime ts_start = QDateTime::currentDateTime();
#if defined(__TCPServer) || defined(__TCPClient)
    mySocket->write(fileName.c_str());
    char temp = num % 10;
    mySocket->write((char*)&temp, sizeof(char));
    mySocket->write("\n");
    mySocket->flush();
#endif

#if defined(__ModebusServer) || defined(__ModebusClient)
    std::vector<int> asciiVals = stringToAscii(fileName);
    //mySocket->write(fileName.c_str());
    /*int temp = num % 2;
    if (temp == 1)
    {
        m_PLCDevice->write_bit_2_plc(10006, 1);

    }
    else
    {
        m_PLCDevice->write_bit_2_plc(10006, 0);
    }*/

    //mySocket->write((char*)&temp,sizeof(char));
    //mySocket->write("\n");
    //mySocket->flush();
    // 
    //遍历发送
    int val_[32] = {};
    uint8_t high[17] = {};
    uint8_t low[17] = {};
    uint16_t val[17] = {};
    int h = 0;
    int l = 0;
    for (int i = 0; i < asciiVals.size(); i++)
    {
        if (i % 2 == 0)
        {
            high[h] = asciiVals[i];
            h++;
        }
        else
        {
            low[l] = asciiVals[i];
            l++;
        }
    }

#endif

#ifdef __ModebusServer
    //m_PLCTCPDevice->write_2_plc(40000, 70, (uint16_t*)&val_);//小盒
    m_PLCTCPDevice->write_2_plc(40070, 70, (uint16_t*)&val_);//条盒
#endif

#ifdef __ModebusClient

    for (int i = 0; i < sizeof(val) / sizeof(short); i++)
    {
        val[i] = (static_cast<uint16_t>(high[i]) << 8) | low[i];//组合高低字节
        m_PLCTCPDevice->mapping->tab_registers[i] = val[i];
    }
    //uint16_t data, data_;
    //data = m_PLCTCPDevice->mapping->tab_registers[15];
    //data_ = m_PLCTCPDevice->mapping->tab_registers[16];
    //QDateTime ts_end = QDateTime::currentDateTime();
    //{
    //    char buffer[1024];
    //    auto buf = ts_end.toString().toStdString();
    //    sprintf(buffer, "time: %s, data: %x,%d\n", buf.c_str(), data, data_);
    //    std::cout << buffer << std::endl;
    //}
#endif
    /*QDateTime ts_end = QDateTime::currentDateTime();
    int time_process = ts_start.msecsTo(ts_end);
    qDebug() << "end-now_ts=" << time_process;*/
}
//字符串转ASCII
std::vector<int> threadSendTCP::stringToAscii(const std::string& str)
{
    std::vector<int> asciiValues;
    for (char c : str) {
        asciiValues.push_back(static_cast<int>(c));
    }
    return asciiValues;
}

#ifdef __TCPServer
void threadSendTCP::onNewConnection()
{
    mySocket = tcpServer->nextPendingConnection(); //创建socket
	qDebug() << "NewConnectionConnected";
	ClientStatus = QAbstractSocket::ConnectedState;
    
}

void threadSendTCP::onClientConnected()
{
    
    qDebug() << "ClientConnected";
}

void threadSendTCP::onClientDisconnected()
{
    ClientStatus = QAbstractSocket::UnconnectedState;
    qDebug() << "ClientDisconnected";
	mySocket->deleteLater();
}
#endif