#include "event.h"
#include "ant.h"
#include "area.h"
#include "card.h"
#include "common_tool.h"
struct ya_event
{
private:
    uint64_t m_ev_id;
public:
    ya_event(uint64_t e_id):m_cur_time(std::chrono::system_clock::now())
    {
        m_ev_id = e_id;
        m_obj_id = "";
        m_map_id = 0;
        m_area_id = 0;
        x = 0;
        y = 0;
        m_limit_value = 0;
        m_cur_value = 0;
        m_desc = "";
        m_landmarkid = 0;
        m_landmarkdirect = 0;
        m_landmarkdist = 0;

        m_status=ES_START;
        m_is_display=true;
		m_is_sent=false;
    }
    ~ya_event(){}
public:
    ///告警状态，开始、结束
    EVENT_STATUS m_status;

    ///告警类型
    EVENT_TYPE m_ev_type;
    ///告警对象类型
    OBJECT_TYPE m_obj_type;
    /// 告警对象编号，与告警对象类型对应，如告警对象类型为分站，此字段为分站编号
    std::string m_obj_id;
    ///当前时间，为告警事件的触发时间，如果状态为开始，则表示开始时间，否则为结束时间
    std::chrono::system_clock::time_point m_cur_time;

    ///告警所在地图
    int m_map_id;
    ///告警所在区域
    int m_area_id;
    ///位置
    double x;
    ///位置
    double y;
    ///告警阈值
    double m_limit_value;
    ///当前值
    double m_cur_value;
    ///描述
    std::string m_desc;

    /// 地标信息
    int m_landmarkid;
    /// 与地标的距离
    double m_landmarkdist;
    /// 所处地标的方向
    int m_landmarkdirect;
	//是否显示
    bool m_is_display;
	//是否已经发送 ture bu发送， false推送. 推送完置为true
	bool m_is_sent;

    bool is_end()
    {
        return ES_END == m_status;
    }
};

struct Event
{
	OBJECT_TYPE m_oid;
	Event(OBJECT_TYPE oid)
		:m_oid(oid)
	{}
	void handle_alarm_event(EVENT_TYPE et,uint64_t id,double limit_value,double cur_value,bool f);
	virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f)=0;
	std::shared_ptr<ya_event> create_event(uint64_t obj_id,EVENT_TYPE ev_type);
	virtual ~Event(){}
};
struct mine_event:Event
{
	mine_event(OBJECT_TYPE oid)
		:Event(oid)
	{}
	virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};
struct area_event:Event
{
	area_event(OBJECT_TYPE oid)
		:Event(oid)
	{}
	virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};
struct device_reader_event:Event
{
	device_reader_event(OBJECT_TYPE oid)
		:Event(oid)
	{}
	virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};
struct card_event:Event
{
	card_event(OBJECT_TYPE oid)
		:Event(oid)
	{}
	virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};

event_tool * event_tool::instance()
{
	static event_tool et;
	return &et;
}
void event_tool::make_event_object()
{
	m_map[OT_MINE] = std::make_shared<mine_event>();
	m_map[OT_AREA] = std::make_shared<area_event>();
	m_map[OT_DEVICE_READER] = std::make_shared<device_reader_event>();
	m_map[OT_CARD] = std::make_shared<card_event>();
}
void event_tool::handle_event(OBJECT_TYPE ot,EVENT_TYPE et,uint64_t id,double limit_value,double cur_value,bool f)
{
	m_map[ot]->handle_alarm_evnet(et,id,limit_value,cur_value,f);
}

std::shared_ptr<ya_event> Event::create_event(uint64_t obj_id,EVENT_TYPE ev_type);
{
    auto ev_ptr = std::make_shared<ya_event>(tool_time::now_to_us());
    ev_ptr->m_ev_type = ev_type;
	ev_ptr->m_obj_type=m_oid;
    return ev_ptr;
}

void Event::handle_alarm_event(EVENT_TYPE et,uint64_t id,double limit_value,double cur_value,bool f)
{
	std::shared_ptr<ya_event> ev_ptr = nullptr;
	uint64_t eid = event_list::to_list_id(et,m_oid,id);
	auto event_ptr = event_list::instance()->get(eid);
	if(f)
	{
		if(event_ptr)
		{
			//已经存在告警
			event_ptr->m_cur_value = cur_value;
			event_ptr->m_is_sent=false;
		}
		else
		{
			ev_ptr=on_message(et,id,f);
			ev_ptr->m_cur_value=cur_value;
			ev_ptr->m_limit_value=limit_value;
			//保存告警信息
			event_list::instance()->add(eid,ev_ptr);
		}
	}
	else
	{
		if(event_ptr)		
		{
			//取消告警
			event_ptr->m_cur_time = std::chrono::system_clock::now();
			event_ptr->m_status = ES_END;
			event_ptr->m_cur_value = cur_value;
			event_ptr->m_is_sent=false;
			ev_ptr=event_ptr;
		}
	}
	if(ev_ptr)
	{
        char sql[LENGTH_SQL] = {0};
        std::string _time = tool_time::to_str_ex(ev_ptr->m_cur_time);
        sprintf(sql,
                "INSERT IGNORE INTO his_event_data(event_id, stat, event_type_id, obj_type_id, obj_id, \
                map_id, area_id, limit_value, cur_value, x, y, cur_time, description, \
                landmark_id, landmark_dist,direction_mapper_id )\
                VALUES(%ld, %d, %d, %d, %s, %d, %d, %.2f, %.2f, %f, %f, '%s', '%s', %d, %10.3f, %d);",
        ev_ptr->get_id(), ev_ptr->m_status, ev_ptr->m_ev_type, ev_ptr->m_obj_type, ev_ptr->m_obj_id.c_str(),
                ev_ptr->m_map_id, ev_ptr->m_area_id, ev_ptr->m_limit_value, ev_ptr->m_cur_value, ev_ptr->x, ev_ptr->y,
                _time.c_str(), ev_ptr->m_desc.c_str(),
                ev_ptr->m_landmarkid, ev_ptr->m_landmarkdist, ev_ptr->m_landmarkdirect);

        db_tool::PushAsync(sql);
	}
}


virtual std::shared_ptr<ya_event> mine_event::on_message(EVENT_TYPE et,uint64_t id,bool f)
{
	std::shared_ptr<ya_event> event_ptr=nullptr;
	if(f)	
	{
		event_ptr=create_event(id,et);
	}
	return event_ptr;
}
virtual std::shared_ptr<ya_event> area_event::on_message(EVENT_TYPE et,uint64_t id,bool f)
{
	std::shared_ptr<ya_event> event_ptr=nullptr;
	if(f)	
	{
		auto area_ptr = area_list::instance()->get(id);
		if(!area_ptr)
		{
			log_info("create_event .can not find area ..%d",id);
			return event_ptr;
		}
		event_ptr=create_event(id,et);
		event_ptr->m_obj_id = std::to_string(id);
		event_ptr->m_area_id = id;
		event_ptr->m_map_id = area_ptr->mapid();
	}
	return event_ptr;
}
virtual std::shared_ptr<ya_event> device_reader_event::on_message(EVENT_TYPE et,uint64_t id,bool f)
{
	std::shared_ptr<ya_event> event_ptr=nullptr;
	if(f)	
	{
		auto site_ptr = site_list::instance()->get(id);
		if(!site_ptr)
		{
			log_info("create_event.can not find site :%d",id);
			return event_ptr;
		}
		event_ptr=create_event(id,et);
		event_ptr->m_obj_id = std::to_string(id);
		event_ptr->m_area_id =  site_ptr->m_area_id;
        event_ptr->m_map_id = site_ptr->m_map_id;
        event_ptr->x = site_ptr->x;
        event_ptr->y = site_ptr->y;
	}
	return event_ptr;
}
virtual std::shared_ptr<ya_event> card_event::on_message(EVENT_TYPE et,uint64_t id,bool f)
{
	std::shared_ptr<ya_event> event_ptr=nullptr;
	if(f)	
	{
		auto card_ptr = card_list::instance()->get(id);
		std::string card_id = tool_other::get_string_cardid(id);
		if(!card_ptr)
		{
			log_info("create_event.can not find card:%s",card_id.c_str());
			return event_ptr;
		}
		event_ptr=create_event(id,et);
		event_ptr->m_obj_id = card_id;
        event_ptr->x = card_ptr->x;
        event_ptr->y = card_ptr->y;
        event_ptr->m_is_display = card_ptr->m_display;
		const auto lm = card_ptr->getLandmark();
		event_ptr->m_area_id = std::get<3>(lm);
		event_ptr->m_map_id = std::get<2>(lm);
        event_ptr->m_landmarkid = std::get<4>(lm);
        event_ptr->m_landmarkdist = std::get<6>(lm);
        event_ptr->m_landmarkdirect = std::get<5>(lm);
	}
	return event_ptr;
}

void event_list::load_his_data_from_db()
{
	std::unordered_map<uint64_t, std::shared_ptr<ya_event>> map;
    const char *sql = "SELECT event_id, stat,event_type_id,obj_type_id,obj_id,map_id,area_id,\
            limit_value,cur_value,x,y, cur_time FROM his_event_data \
            WHERE event_id IN (SELECT MAX(event_id) FROM his_event_data \
                               WHERE cur_time > (CASE obj_type_id \
                                                 WHEN 1 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
                                                 WHEN 2 THEN DATE_SUB(NOW(),INTERVAL 2 DAY)\
                                                 WHEN 4 THEN DATE_SUB(NOW(),INTERVAL 1 MONTH)\
                                                 WHEN 9 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
                                                 WHEN 10 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
                                                 END) \
                               AND cur_time < NOW()\
                               GROUP BY event_type_id, obj_id) \
            AND  event_id NOT IN ( SELECT event_id FROM (SELECT * FROM his_event_data WHERE  stat=100) s);";
    std::string Error;
    YADB::CDBResultSet DBRes;
    sDBConnPool.Query(sql,DBRes,Error);
    if(!Error.empty())
        log_error("初始化事件列表 Error,%s",Error.c_str());
    uint64_t nCount = DBRes.GetRecordCount( Error );
    if (nCount > 0)
    {
        log_info( "init_vehicle_category. The record count=%ld\n", nCount );

        while ( DBRes.GetNextRecod(Error) )
        {
            long long event_id  = 0;
            DBRes.GetField( "event_id",event_id, Error );

            int event_type_id  = 0;
            DBRes.GetField( "event_type_id",event_type_id, Error );

            int obj_type_id  = 0;
            DBRes.GetField( "obj_type_id",obj_type_id, Error );

            std::string obj_id  = "";
            DBRes.GetField( "obj_id",obj_id, Error );

            int map_id  = 0;
            DBRes.GetField( "map_id",map_id, Error );

            int area_id  = 0;
            DBRes.GetField( "area_id",area_id, Error );

            double limit_value = 0;
            DBRes.GetField( "limit_value",limit_value, Error );

            double cur_value = 0;
            DBRes.GetField( "cur_value",cur_value, Error );

            double x = 0;
            DBRes.GetField( "x",x, Error );

            double y = 0;
            DBRes.GetField( "y",y, Error );

            std::string cur_time  = "";
            DBRes.GetField( "cur_time",cur_time, Error );

            int stat  = 0;
            DBRes.GetField( "stat",stat, Error );


            std::shared_ptr<ya_event> ev = std::make_shared<ya_event>(event_id);
            ev->m_status = static_cast<EVENT_STATUS>(stat);
            ev->m_ev_type = static_cast<EVENT_TYPE>(event_type_id);

            ev->m_obj_type = static_cast<OBJECT_TYPE>(obj_type_id);
            ev->m_obj_id = tool_other::to13str(obj_id);
            ev->m_cur_time = tool_time::to_time_ex(cur_time);

            ev->m_cur_value = cur_value;
            ev->m_limit_value = limit_value;

            ev->m_map_id = map_id;
            ev->m_area_id = area_id;
            ev->x = x;
            ev->y = y;

			map.insert(std::make_pair(event_id, ev));
        }

        for(auto&iter: m_map)
        {
            auto ev = iter.second;
            log_info("event list %lld,%d,%d,%d,%s,%d,%d,%f,%f,%f,%f,%s"
                     , ev->get_id(),ev->m_status,ev->m_ev_type,ev->m_obj_type,ev->m_obj_id.c_str()
                     ,ev->m_map_id,ev->m_area_id,ev->m_limit_value,ev->m_cur_value
                     ,ev->x,ev->y
                     ,tool_time::to_str_ex(ev->m_cur_time).c_str());
        }
		if(!map.empty())
		  event_list::instance()->add(map);
    }
}


template<> std::shared_ptr<event_list>
single_base<event_list, uint64_t, std::shared_ptr<ya_event>>::m_instance=std::make_shared<event_list>();
