
#include <thread>
#include <mutex>
#include <atomic>
#include <iostream>
#include <memory>
#include <string.h>
#include <math.h>

#include <log.h>
#include <znet.h>
#include <zstream.h>
#include <sys/time.h>
#include "worker.h"
#include "tdoa_sync.h"
#include "net-service.h"
#include "ant.h"
#include "card.h"
#include "mine_business.h"
net_service::net_service()
{
	m_loc_worker=worker::instance();
	m_sync_worker=tdoa_sync::instance();
}

net_service::~net_service()
{
	if(m_loc_worker)
		m_loc_worker->stop();
}

void net_service::on_timer()
{
	visit_site_status vss;
	sit_list::instance()->accept(vss);
	mine_business::inst()->run_business();
}
void net_service::on_message(std::shared_ptr<client> clt,const char*data,size_t len)
{
	logn_bin(1,"",data,len);//输出二进制日志

	zistream is(data,len-2);
	uint16_t cmd;
	is>>skip(2)>>cmd;
	switch(cmd)
	{
		case 0x843b://tof
			{
				uint32_t site_id;
				is>>site_id>>skip(12);
                auto site_ptr = sit_list::instance()->get(static_cast<int32_t>(site_id));
                if(!site_ptr)
                {
                    log_error("在全局分站列表中找不到分站：分站id=%d", site_id);
                    break;
                }
                site_ptr->set_client(clt);

				struct timeval tv;
				gettimeofday(&tv,NULL);
				uint64_t t = tv.tv_sec*1000 + tv.tv_usec/1000;
				int index=0;
				while(!is.eof())
				{
					uint64_t tstamp = t -1000 + 50 + index* 45;
					index++;
					task*t=task::alloc<message_locinfo>();
					message_locinfo&m=t->body<message_locinfo>();
					m.load(is,cmd==0x863b);
					m.m_time_stamp=tstamp;
					m.m_site_id=site_id;

					t->m_cmd_code=cmd;
					t->m_hash_id=m.m_card_id;
					m_loc_worker->request(t);
					if(m.m_card_type==5)
						mine_business::inst()->make_reverse_condition(m.m_card_type,m.m_card_id,m.m_ant_id,m.m_card_ct,m.m_tof,m.m_site_id);
				}
			}
			break;
		case 0x863b://tdoa
			{
				uint32_t site_id;
				is>>site_id>>skip(12);
				while(!is.eof())
				{
					task*t=task::alloc<message_locinfo>();
					message_locinfo&m=t->body<message_locinfo>();
					m.load(is,cmd==0x863b);
					m.m_site_id=site_id;
					t->m_cmd_code=cmd;
					t->m_hash_id=m.m_card_id;
					m_sync_worker->translate(m);
					m_loc_worker->request(t);
				}
			}
			break;
		case 0xa78d://time sync
			{
				message_tdoasync m;
				m.load(is);
				m_sync_worker->on_message(m);
			}
			//site_message::on_sync(this,t.m_param1);
			break;
		case 0x853b://tof his
		case 0x873b://tdoa his
			break;
		case 0x804c://ctrl site message
			break;
	}
}


