#include"module_geofault.h"

#include<memory>
#include<string>

#include"area_business.h"
#include"event.h"
#include"db_api/CDBSingletonDefine.h"
#include"ya_setting.h"
#include"common_tool.h"
#include"log.h"

struct over_speed_data:business_data
{
    over_speed_data()
    {
        m_near_geofault_count=0;
        m_far_geofault_count=0;
    }

    int m_near_geofault_count;
    int m_far_geofault_count;
};

void module_geofault::module_geofault::on_enter(std::shared_ptr<card_location_base> card_ptr, int index)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }
    area_hover_ptr->m_data[index] = std::make_shared<over_speed_data>();

    double dist=0;
    if(_is_near(area_hover_ptr->m_area, card_ptr->x, card_ptr->y, dist))
    {
        auto ptr = static_cast<over_speed_data*>(area_hover_ptr->m_data[index].get());
        ptr->m_near_geofault_count++;
    }
}

void module_geofault::on_hover(std::shared_ptr<card_location_base> card_ptr, int index)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }
    auto ptr = static_cast<over_speed_data*>(area_hover_ptr->m_data[index].get());

    double dist=0;
    if(_is_near(area_hover_ptr->m_area, card_ptr->x, card_ptr->y, dist))
    {
        ptr->m_near_geofault_count++;
    }
    else
    {
        ptr->m_far_geofault_count++;
    }

    //确定告警
    if(_geofault_count_limit <= ptr->m_near_geofault_count)
    {
        ptr->m_near_geofault_count=_geofault_count_limit;

        auto ev_ptr = event_list::instance()->get_event_card(card_ptr->m_id, card_ptr->m_type, ET_VEHICLE_NEAR_GEOFAULT);
        if(!ev_ptr)//从没有告警状态转化为告警状态
        {
            ptr->m_far_geofault_count=0;
        }

        uint64_t id = tool_other::type_id_to_u64(card_ptr->m_type, card_ptr->m_id);
        event_tool::instance()->handle_event(OT_CARD, ET_VEHICLE_NEAR_GEOFAULT, id, CYaSetting::m_sys_setting.geofault_warn_dis, dist, true);
    }

    //确定正常
    if(_geofault_count_limit <= ptr->m_far_geofault_count)
    {
        ptr->m_far_geofault_count=_geofault_count_limit;

        auto ev_ptr = event_list::instance()->get_event_card(card_ptr->m_id, card_ptr->m_type, ET_VEHICLE_NEAR_GEOFAULT);
        if(ev_ptr && !ev_ptr->is_end())
        {
            ptr->m_near_geofault_count=0;

            uint64_t id = tool_other::type_id_to_u64(card_ptr->m_type, card_ptr->m_id);
            event_tool::instance()->handle_event(OT_CARD, ET_VEHICLE_NEAR_GEOFAULT, id, CYaSetting::m_sys_setting.geofault_warn_dis, dist, false);
        }
    }
}

void module_geofault::on_leave(std::shared_ptr<card_location_base> card_ptr, int index)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }

    uint64_t id = tool_other::type_id_to_u64(card_ptr->m_type, card_ptr->m_id);
    event_tool::instance()->handle_event(OT_CARD, ET_VEHICLE_NEAR_GEOFAULT, id, CYaSetting::m_sys_setting.geofault_warn_dis, 1000, false);

    area_hover_ptr->m_data[index] = std::make_shared<over_speed_data>();
}


void module_geofault::module_geofault::init_geofault_from_db()
{
    const char *sql = "select area_id, pt_data from   dat_geofault g, dat_work_face w \
            where g.workface_id=w.work_face_id;";
    std::string Error;
    YADB::CDBResultSet DBRes;
    sDBConnPool.Query(sql,DBRes,Error);
    if(!Error.empty())
    {
        log_error("init_geofault_from_db Error,%s",Error.c_str());
        return;
    }

    uint64_t nCount = DBRes.GetRecordCount( Error );
    if (static_cast<int64_t>(nCount) < 0)
    {
        log_error("错误，init_geofault_from_db. The record count=%ld\n", nCount );
        return;
    }

    log_info( "init_geofault_from_db. The record count=%ld\n", nCount );

    _area_geofault_map.clear();
    while ( DBRes.GetNextRecod(Error) )
    {
        int area_id  = 0;
        DBRes.GetField( "area_id",area_id, Error );

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

        std::vector<point> points;
        std::vector<std::string> strs = split(pt_data,';');
        for (const auto & s:strs)
        {
            std::vector<std::string> xy = split(s, ',');
            if (xy.size()!=2)
            {
                continue;
            }

            point pt;
            pt.x = std::atof(xy[0].c_str());
            pt.y = std::atof(xy[1].c_str());

            points.push_back(pt);
        }

        _area_geofault_map.insert({area_id,points});
    }

    for(const auto &p : _area_geofault_map)
    {
        auto kk = p.second;
        std_debug("init_geofault_from_db:area_id:%d--points: %s",p.first, points2str(kk).c_str());
        log_info("init_geofault_from_db:area_id:%d--points: %s",p.first, points2str(kk).c_str());
    }
}

bool module_geofault::_is_near(std::shared_ptr<area>& area_ptr, double x, double y, double& out_dist)
{
    auto serch = _area_geofault_map.find(area_ptr->m_id);
    if(serch == _area_geofault_map.end())
    {
        return false;
    }

    point pt(x, y);
    double min=0;
    out_dist=1000000;
    for(auto& p : serch->second)
    {
        min = pt.dist(p) * area_ptr->m_scale;
        if(min < out_dist)
        {
            out_dist = min;
        }
        if(min < CYaSetting::m_sys_setting.geofault_warn_dis)
        {
            return true;
        }
    }

    return false;
}

