#include "event.h"

#include<string>

#include "ant.h"
#include "area.h"
#include "card.h"
#include "common_tool.h"
#include "websocket/constdef.h"
#include "db/db_api/CDBSingletonDefine.h"
#include"tool_time.h"
#include"ant.h"
#include"db/db_tool.h"


uint64_t ya_event::get_list_id()
{
    uint64_t car_id = tool_other::type_id_to_u64(tool_other::id64_to_type(m_obj_id), tool_other::id64_to_id(m_obj_id));
    return  event_list::to_list_id(m_ev_type, m_obj_type,car_id);
}


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,const std::string &desc="");
    virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f)=0;
    std::shared_ptr<ya_event> create_event(std::string obj_id,EVENT_TYPE ev_type);
    virtual ~Event(){}
};
struct mine_event:Event
{
    mine_event()
        :Event(OT_MINE)
    {}
    virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};
struct area_event:Event
{
    area_event()
        :Event(OT_AREA)
    {}
    virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};
struct device_reader_event:Event
{
    device_reader_event()
        :Event(OT_DEVICE_READER)
    {}
    virtual std::shared_ptr<ya_event> on_message(EVENT_TYPE et,uint64_t id,bool f);
};
struct card_event:Event
{
    card_event()
        :Event(OT_CARD)
    {}
    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,const std::string &desc/*=""*/)
{
    m_map[ot]->handle_alarm_event(et,id,limit_value,cur_value,f,desc);
}

std::shared_ptr<ya_event> Event::create_event(std::string 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;
    ev_ptr->m_obj_id = obj_id;
    return ev_ptr;
}

void Event::handle_alarm_event(EVENT_TYPE et,uint64_t id,double limit_value,double cur_value,bool f,const std::string &desc/*=""*/)
{
    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
        {
            uint64_t _id=id;
            log_info("Create_Event:desc[%s],id:%d,et:%d",desc.c_str(),id,et);
            if(et == ET_READER_LOCATION_REVERSAL&&!desc.empty())
            {
                std::string cardid = desc.substr(0,desc.find_first_of('&'));
                _id = tool_other::card_id_to_u64(cardid);
            }
            ev_ptr=on_message(et,_id,f);
            ev_ptr->m_cur_value=cur_value;
            ev_ptr->m_limit_value=limit_value;
            ev_ptr->m_desc=desc;
            //保存告警信息
            event_list::instance()->add(eid,ev_ptr);
        }
    }
    else
    {
        if(event_ptr && !event_ptr->is_end())
        {
            //取消告警
            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_desc=desc;
            event_ptr->m_is_sent=false;
            ev_ptr=event_ptr;
        }
    }
    if(ev_ptr)
    {
        event_list::save_event(ev_ptr);
    }
}


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)
    {
        auto area_ptr = area_list::instance()->get(id);
        if(!area_ptr)
        {
            log_error("create_event .can not find area ..%d",id);
            return event_ptr;
        }
        event_ptr=create_event(std::to_string(id), et);
        event_ptr->m_area_id = id;
        event_ptr->m_map_id = area_ptr->mapid();
    }
    return event_ptr;
}

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_error("create_event .can not find area ..%d",id);
            return event_ptr;
        }
        event_ptr=create_event(std::to_string(id), et);
        event_ptr->m_area_id = id;
        event_ptr->m_map_id = area_ptr->mapid();
    }
    return event_ptr;
}

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 = sit_list::instance()->get(id);
        if(!site_ptr)
        {
            log_info("create_event.can not find site :%d",id);
            return event_ptr;
        }
        event_ptr=create_event(std::to_string(id),et);
        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;
}

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(card_id,et);
        event_ptr->x = card_ptr->x;
        event_ptr->y = card_ptr->y;
        event_ptr->m_is_display = card_ptr->m_display;

        auto area_info_map = card_ptr->get_area_tool()->m_area_info;
        if(!area_info_map.empty())
        {
            auto lm = area_info_map.begin()->second;
            event_ptr->m_area_id = std::get<0>(lm);
            event_ptr->m_map_id = card_ptr->get_area_tool()->m_mapid;
            event_ptr->m_landmarkid = std::get<1>(lm);
            event_ptr->m_landmarkdist = std::get<3>(lm);
            event_ptr->m_landmarkdirect = std::get<2>(lm);
        }
    }
    return event_ptr;
}

std::shared_ptr<ya_event> event_list::get_event_card(uint32_t card_id, int card_type, EVENT_TYPE ev_type)
{
    uint64_t id64 = tool_other::type_id_to_u64(card_type, card_id);
    return base::get(to_list_id(ev_type, OT_CARD, id64));
}

void event_list::save_event(std::shared_ptr<ya_event> 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);
}

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);
    }
}

std::string event_list::evs_to_json(std::vector<std::shared_ptr<ya_event>> arr)
{
    rapidjson::Document doc(rapidjson::kObjectType);
    rapidjson::Value data(rapidjson::kArrayType);
    rapidjson::Document::AllocatorType& allocator=doc.GetAllocator();

    auto it=arr.begin();
    for(;it!=arr.end();++it)
    {
        if((*it)->m_is_display)
        {
            _ev_to_node(*it, allocator, data);
        }
    }

    doc.AddMember(JSON_ROOT_KEY_CMD,JSON_CMD_VALUE_EVENT, allocator);
    doc.AddMember(JSON_ROOT_KEY_VERSION,INTERFACE_VERSION, allocator);
    doc.AddMember(JSON_ROOT_KEY_DATA,data, allocator);

    rapidjson::StringBuffer sb;
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
    doc.Accept(writer);

    return sb.GetString();
}

void event_list::_ev_to_node(std::shared_ptr<ya_event> ev_ptr,
                             rapidjson::Document::AllocatorType& allocator,
                             rapidjson::Value& out_data)
{
    rapidjson::Value ev(rapidjson::kObjectType);

    ev.AddMember(JSON_KEY_EVENT_EVENT_ID,ev_ptr->get_id(), allocator);
    ev.AddMember(JSON_KEY_EVENT_STATUS,ev_ptr->m_status, allocator);

    ev.AddMember(JSON_KEY_EVENT_TYPE_ID,ev_ptr->m_ev_type, allocator);
    ev.AddMember(JSON_KEY_EVENT_OBJ_TYPE_ID,ev_ptr->m_obj_type, allocator);

    tool_json::add_member(ev, JSON_KEY_EVENT_OBJ_ID, ev_ptr->m_obj_id, allocator);
    ev.AddMember(JSON_KEY_EVENT_MAP_ID,ev_ptr->m_map_id, allocator);
    ev.AddMember(JSON_KEY_EVENT_AREA_ID,ev_ptr->m_area_id, allocator);
    ev.AddMember(JSON_KEY_EVENT_X,ev_ptr->x, allocator);
    ev.AddMember(JSON_KEY_EVENT_Y,ev_ptr->y, allocator);

    ev.AddMember(JSON_KEY_EVENT_LIMIT_VALUE,ev_ptr->m_limit_value, allocator);
    ev.AddMember(JSON_KEY_EVENT_CUR_VALUE,ev_ptr->m_cur_value, allocator);
    ev.AddMember(JSON_KEY_EVENT_CUR_TIME,tool_time::to_ms(ev_ptr->m_cur_time), allocator);

    ev.AddMember(JSON_KEY_EVENT_LANDMARK_ID,ev_ptr->m_landmarkid, allocator);
    ev.AddMember(JSON_KEY_EVENT_LANDMARK_DIRECTION,ev_ptr->m_landmarkdirect, allocator);
    ev.AddMember(JSON_KEY_EVENT_LANDMARK_DISTANCE,ev_ptr->m_landmarkdist, allocator);

    out_data.PushBack(ev, allocator);
}

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