#ifndef YA_EVENT_H
#define YA_EVENT_H

/**
 * @brief 告警事件类型
 * @author 戴月腾
 * @date 2018-09-24
 */

#include<map>
#include<chrono>
#include<memory>
#include"write-copy.h"
#include"log.h"
#include "db_api/CDBSingletonDefine.h"
#include"card.h"
#include"common_tool.h"
#include "tool_time.h"
#include "db_tool.h"
#include <area.h>
#include "ant.h"

/**
 * @brief 事件状态
 */
enum EVENT_STATUS
{
    ///事件开始
    ES_START = 0,
    ///呼救已处理状态
    ES_DEAL_HELP = 1,
    ///事件结束
    ES_END = 100
};

enum EVENT_TYPE{ // 事件类型
    ET_UNKNOWN = 0,
	ET_OVER_COUNT_PERSON = 1, // 井下人员超员pit_module/CPicardmanager
	ET_OVER_COUNT_VEHICLE = 2,    // 井下车辆超员pit_module/CPicardmanager

    ET_AREA_OVER_COUNT_PERSON = 3,	// 区域人员超员
    ET_AREA_OVER_COUNT_VEHICLE = 4,	// 区域车辆超员
	ET_READER_ERROR = 6,
    ET_CARD_LOW_POWER_SERIOUS = 12, // 电量极低

    ET_CARD_OVER_TIME_PERSON = 13, // 人员井下超时pit_module/CPicardmanager
	ET_CARD_OVER_TIME_VEHICLE = 14, // 车辆井下超时pit_module/CPicardmanager

    ET_CARD_AREA_OVER_TIME_PERSON = 15, // 人员区域超时
    ET_CARD_AREA_OVER_TIME_VEHICLE = 16, // 车辆区域超时
    ET_CARD_AREA_LIMIT_PERSON = 17, // 人员进入限制区域
    ET_CARD_AREA_LIMIT_VEHICLE = 18, // 车辆进入限制区域
    ET_CARD_AREA_FORBIDDEN_PERSON = 19,  // 人员进入禁止区域
    ET_CARD_AREA_FORBIDDEN_VEHICLE = 20, // 车辆进入禁止区域
    ET_CARD_OVER_SPEED = 21, // 车辆超速
    ET_CARD_HELP = 24, // 人员呼救

    CARD_EVENT_COUNT_MAX,
};

/**
 * @brief 对象类型
 */
enum OBJECT_TYPE
{
    ///矿井
    OT_MINE = 1,
    ///区域
    OT_AREA = 2,
    ///分站
    OT_DEVICE_READER = 4,
    ///标识卡，包括人员、车辆、自组网等
    OT_CARD = 9,
};

/**
 * @brief 告警事件
 */
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;
    }
    ~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;

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

    ///作为事件map列表的id，方便查找；(obj_type<<32| obj_id)
    uint64_t get_list_id();

    uint64_t get_id(){return m_ev_id;}
};
typedef std::shared_ptr<ya_event> event_ptr;
typedef std::map<uint64_t, std::shared_ptr<ya_event>> event_map;
typedef std::shared_ptr<event_map> event_map_ptr;


struct event_list:single_base<event_list,uint64_t,std::shared_ptr<ya_event>>
{
public:
    ///作为事件map列表的id，方便查找；(ev_type<<48 | obj_type<<40 |  obj_id_type<<32 | obj_id)
    static uint64_t to_list_id(EVENT_TYPE ev_type, OBJECT_TYPE obj_type, int obj_id_type, uint32_t obj_id)
    {
        return (static_cast<uint64_t>(ev_type)<<48)|(static_cast<uint64_t>(obj_type)<<40)
                |(static_cast<uint64_t>(obj_id_type)<<32)|static_cast<uint64_t>(obj_id);
    }
    ///创建井下警告
    static event_ptr create_event_mine(int objid, EVENT_TYPE ev_type)
    {
        return create_event(OT_MINE, objid, 0, ev_type);
    } 
    ///创建区域警告
    static event_ptr create_event_area(int area_id, EVENT_TYPE ev_type)
    {
        return create_event(OT_AREA, area_id, 0, ev_type);
    }

    static event_ptr create_event_reader(int reader_id, EVENT_TYPE ev_type)
    {
        return create_event(OT_DEVICE_READER, reader_id, 0, ev_type);
    }
    ///创建与卡有关的警告，需要卡类型
    static event_ptr create_event_card(uint32_t card_id, int32_t card_type, EVENT_TYPE ev_type)
    {
        return create_event(OT_CARD, static_cast<int32_t>(card_id), card_type, ev_type);
    }

    static void copy_event(const std::shared_ptr<card_location_base> card_ptr, event_ptr ev_ptr)
    {
        ev_ptr->x = card_ptr->x;
        ev_ptr->y = card_ptr->y;
        ev_ptr->m_cur_time = std::chrono::system_clock::now();
        ev_ptr->m_is_display = card_ptr->m_display;

        auto hover = card_ptr->get_area_hover();
        if(nullptr!=hover)
        {
            ev_ptr->m_area_id =  hover->m_area->id();
            ev_ptr->m_map_id = hover->m_area->mapid();

            ev_ptr->m_landmarkid = hover->landmark_dir;
            ev_ptr->m_landmarkdist = hover->landmark_dis;
            ev_ptr->m_landmarkdirect = hover->landmark_dir;
        }
    }

    static void copy_event(const std::shared_ptr<area> area_ptr, event_ptr ev_ptr)
    {
        ev_ptr->m_cur_time = std::chrono::system_clock::now();
        ev_ptr->m_is_display = true;

        ev_ptr->m_area_id =  area_ptr->id();
        ev_ptr->m_map_id = area_ptr->mapid();
    }
    static void copy_event(const std::shared_ptr<site> site_ptr, event_ptr ev_ptr)
    {
        ev_ptr->m_cur_time = std::chrono::system_clock::now();
        ev_ptr->m_is_display = true;

        ev_ptr->m_area_id =  site_ptr->m_area_id;
        ev_ptr->m_map_id = site_ptr->m_map_id;
        ev_ptr->x = site_ptr->x;
        ev_ptr->y = site_ptr->y;
    }


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

    std::shared_ptr<ya_event> get_event_area(int32_t area_id, EVENT_TYPE ev_type)
    {
        return base::get(to_list_id(ev_type, OT_AREA, 0, static_cast<uint32_t>(area_id)));
    }

    std::shared_ptr<ya_event> get_event_reader(int32_t reader_id, EVENT_TYPE ev_type)
    {
        return base::get(to_list_id(ev_type,OT_DEVICE_READER, 0, static_cast<uint32_t>(reader_id)));
    }
    void load_his_data_from_db();

    static void save_event(const event_ptr 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);
    }

    ~event_list(){}

    static std::string ev_to_json(std::shared_ptr<ya_event> ev_ptr)
    {
        std::vector<std::shared_ptr<ya_event>> evs;
        evs.push_back(ev_ptr);
        return evs_to_json(evs);
    }

    static std::string 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();
    }

private:
    static void 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);
    }

private:
    static event_ptr create_event(OBJECT_TYPE obj_type, int obj_id, int type, 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 = obj_type;
        ev_ptr->m_obj_id = tool_other::type_id_to_str(type, obj_id);

        return ev_ptr;
    }
};

#endif // YA_EVENT_H
