#include <memory>
#include "common_tool.h"
#include "message.h"
#include "loc_message.h"

#include "config_file.h"
#include "card_person.h"
#include "card_car.h"

#include "db/db_card.h"
#include "db/db_api/CDBSingletonDefine.h"
#include "db/db_api/CDBResultSet.h"

#include "tool_time.h"
#include "mine.h"
#include "log.h"
#include "area.h"
#include "card.h"
#include "mine_business.h"
#include "mine_module/MineCardManager.h"

extern config_file config;
void card_list::init_staffer(int64_t id64)
{
    std::string strategy = config.get("person.strategy","PS_1");

	std::unordered_map<uint64_t,std::shared_ptr<card_location_base>> 
		map=std::move(db_card::load_person(id64,strategy));

	if(map.empty())
	{
		log_error("增加或修改失败，数据库中找不到: card_id=%013lld", id64);
		return ;
	}

	if(-1 == id64)
	{
		log_info( "init_staffer. The record count=%d\n", map.size() );
		card_list::instance()->add(map);
	}
	else
	{
		auto db_person=map.begin()->second;
		auto card_ptr = card_list::instance()->get(id64);
		if(card_ptr)
		{
			person* tmp_ptr= static_cast<person*>(card_ptr.get());
			tmp_ptr->m_display = static_cast<uint16_t>(db_person->m_display);
			tmp_ptr->m_deptid = db_person->m_deptid;
			//group_id
			//occ_id
			tmp_ptr->m_level_id = db_person->m_level_id;
			//worktype_id
		}
		else
		{
			card_list::instance()->add(id64, db_person);
		}

		log_info("基础数据 增加或修改人卡成功：卡id:%ld, dept_id:%d,need_display:%d,occupation_level_id:%d",
				id64,db_person->m_deptid,db_person->m_display,db_person->m_level_id);
	}
}


void card_list::init_vehicle(int64_t id64)
{
	std::unordered_map<uint64_t,std::shared_ptr<card_location_base>> 
		map=std::move(db_card::load_car(id64));

	if(map.empty())
	{
		log_error("增加或修改失败，数据库中找不到: card_id=%013lld", id64);
		return ;
	}

	if(-1 == id64)
	{
		log_info( "init_vehicle. The record count=%d\n", map.size() );
		card_list::instance()->add(map);
	}
	else
	{
		car* db_car= static_cast<car*>(map.begin()->second.get());
		auto card_ptr = card_list::instance()->get(id64);
		if(card_ptr)
		{
			car* tmp_ptr= static_cast<car*>(card_ptr.get());
			tmp_ptr->m_display = static_cast<uint16_t>(db_car->m_display);
			tmp_ptr->m_deptid = db_car->m_deptid;
			tmp_ptr->m_vehicle_category_id = db_car->m_vehicle_category_id;
			tmp_ptr->m_vehicle_type_id = db_car->m_vehicle_type_id;
			tmp_ptr->m_level_id = db_car->m_level_id;
		}
		else
		{
			card_list::instance()->add(id64, map.begin()->second);
		}

		log_info("基础数据 增加或修改车卡成功：卡id:%ld, dept_id:%d,need_display:%d,categoryid:%d",
				id64,db_car->m_deptid,db_car->m_display,db_car->m_vehicle_category_id);
	}
}

void card_list::init_card_from_db()
{
    init_staffer(-1);
    init_vehicle(-1);
}

void card_list::load_his_card_postion_from_db()
{
    load_his_card_postion_vehicle();
    load_his_card_postion_staff();

    for(auto&iter: m_map)
    {
        auto card_ptr = iter.second;
        auto mine_tool_ptr = card_ptr->get_mine_tool();
        if(mine_tool_ptr->is_attendance())
        {
            auto str = tool_time::to_str_ex( tool_time::to_ms(mine_tool_ptr->m_attendance_start_time));
            log_info("加载考勤,考勤开始时间： %s, 卡id=%d，卡type=%d", str.c_str(), card_ptr->m_id, card_ptr->m_type);

            //还在考勤中表示，还在井下(初始化话数据)
            if(card_ptr->is_person())
            {
                CMineCardManager::instance()->OnPersonDown(card_ptr,true);
            }
            if(card_ptr->is_vehicle())
            {
                CMineCardManager::instance()->OnVehicleDown(card_ptr,true);
            }
        }
    }
    //初始化后检查是否超员
    CMineCardManager::instance()->OnPersonOvercrowdingWarning();
    CMineCardManager::instance()->OnVehicleOvercrowdingWarning();

    auto area_map = area_list::instance()->m_map;
    for(auto&iter: area_map)
    {
        auto area_ptr = iter.second;
        if(area_ptr->m_person_count)
        {
            log_info("加载区域人数： 区域id=%d，区域人数=%d",area_ptr->m_id, area_ptr->m_person_count.load());
        }

        if(area_ptr->m_vehicle_count)
        {
            log_info("加载区域车数： 区域id=%d，区域车数=%d",area_ptr->m_id, area_ptr->m_vehicle_count.load());
        }
    }
}

void card_list::load_his_card_postion_vehicle()
{
    const char *sql = "select l.card_id, l.cur_time, l.x, l.y, l.z, l.map_id, la.area_id, l.state, \
            case when l.cur_time >= date_sub(now(), interval 2 minute) then l.speed else 0 end as speed, \
            l.mileage, la.enter_time, att.start_time, \
            att.end_time, \
            l.landmark_id, l.direction_mapper_id, l.landmark_dist \
            from rt_location l, rt_location_area la, rt_att_vehicle att, dat_card c, dat_vehicle_extend v \
            where l.card_id = c.card_id and l.card_id = la.card_id and l.card_id = att.card_id and l.card_id=v.card_id \
            and c.state_id=0;";
    std::string Error;
    YADB::CDBResultSet DBRes;
    sDBConnPool.Query(sql,DBRes,Error);
    if(!Error.empty())
        log_error("load_his_card_postion_vehicle列表 Error,%s",Error.c_str());
    uint64_t nCount = DBRes.GetRecordCount( Error );
    if (nCount > 0)
    {
        log_info( "load_his_card_postion_vehicle. The record count=%ld\n", nCount );

        while ( DBRes.GetNextRecod(Error) )
        {
            std::string card_id  = "";
            DBRes.GetField( "card_id",card_id, Error );

            uint32_t id = tool_other::id64_to_id(card_id);
            int type = tool_other::id64_to_type(card_id);

            auto temp_ptr = card_list::instance()->get(tool_other::type_id_to_u64(type, id));
            if(!temp_ptr || !temp_ptr->is_vehicle())
            {
                log_error("全局卡列表中找不到卡，卡id=%d，卡type=%d", id, type);
                continue;
            }

            auto card_ptr = static_cast<car*>(temp_ptr.get());

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

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

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

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

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

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

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

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

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

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

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

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

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

            card_ptr->x = x;
            card_ptr->y = y;
            card_ptr->z = z;

            auto area = area_list::instance()->get(area_id);
            if(area == nullptr)
            {
                log_error("load_vehicle...area_list 找不到区域：区域id=%d", area_id);
                continue;
            }
            area->m_vehicle_count++;

            point pt = *card_ptr;
            card_ptr->m_area_tool->init_area(area,pt,temp_ptr);
			//m_area_hover = std::make_shared<area_hover>( area, pt,speed);
            auto area_hover_ptr = card_ptr->get_area_hover();

            auto e_t = tool_time::to_time_ex(enter_time);
            area_hover_ptr->m_enter_time = std::chrono::system_clock::to_time_t(e_t);

            //int map_id  = 0;
            //int state  = 0;
            card_ptr->m_speed = speed;

            if(end_time.empty())
            {
                auto mine_tool_ptr = card_ptr->get_mine_tool();
                mine_tool_ptr->m_attendance_start_time = tool_time::to_time_ex(start_time);
                mine_tool_ptr->m_stat_attendance = AS_ATTENDANCE;
            }

            area_hover_ptr->landmark_id = landmark_id;
            area_hover_ptr->landmark_dir = direction_mapper_id;
            area_hover_ptr->landmark_dis = landmark_dist;

            card_ptr->m_time = tool_time::now_to_ms();
        }
    }
}

void card_list::load_his_card_postion_staff()
{
    const char *sql = "select l.card_id, l.cur_time, l.x, l.y, l.z, l.map_id, la.area_id, l.state, \
            case when l.cur_time >= date_sub(now(), interval 2 minute) then l.speed else 0 end as speed, \
            l.mileage, la.enter_time, att.start_time, \
            att.end_time, \
            l.landmark_id, l.direction_mapper_id, l.landmark_dist \
            from rt_location l, rt_location_area la, rt_att_staff att, dat_card c, dat_staff_extend s \
            where l.card_id = c.card_id and l.card_id = la.card_id and l.card_id = att.card_id and l.card_id=s.card_id\
            and c.state_id=0;";
    std::string Error;
    YADB::CDBResultSet DBRes;
    sDBConnPool.Query(sql,DBRes,Error);
    if(!Error.empty())
        log_error("load_his_card_postion_staff列表 Error,%s",Error.c_str());
    uint64_t nCount = DBRes.GetRecordCount( Error );
    if (nCount > 0)
    {
        log_info( "load_his_card_postion_staff. The record count=%ld\n", nCount );

        while ( DBRes.GetNextRecod(Error) )
        {
            std::string end_time  = "";
            DBRes.GetField( "end_time",end_time, Error );
            if(!end_time.empty()) // 已升井，不再读入
            {
                continue;
            }

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

            uint32_t id = tool_other::id64_to_id(card_id);
            int type = tool_other::id64_to_type(card_id);

            auto temp_ptr = card_list::instance()->get(tool_other::type_id_to_u64(type, id));
            if(!temp_ptr || !temp_ptr->is_person())
            {
                log_error("全局卡列表中找不到卡，卡id=%d，卡type=%d", id, type);
                continue;
            }

            auto card_ptr = static_cast<car*>(temp_ptr.get());

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

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

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

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

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

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

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

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

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

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

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

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

            card_ptr->x = x;
            card_ptr->y = y;
            card_ptr->z = z;

            auto area = area_list::instance()->get(area_id);
            if(area == nullptr)
            {
                log_error("area_list 找不到区域：区域id=%d", area_id);
                continue;
            }
            area->m_person_count++;

            point pt = *card_ptr;
            card_ptr->m_area_tool->init_area(area,pt,temp_ptr);
			
//			m_area_hover = std::make_shared<area_hover>(area,pt,speed);
            auto area_hover_ptr = card_ptr->get_area_hover();

            auto e_t = tool_time::to_time_ex(enter_time);
            area_hover_ptr->m_enter_time = std::chrono::system_clock::to_time_t(e_t);
			log_info("load_staff...%d,areaid:%d,mapid:%d",id,area->id(),area->mapid());

            //int map_id  = 0;
            //int state  = 0;
            card_ptr->m_speed = speed;

            if(end_time.empty())
            {
                auto mine_tool_ptr = card_ptr->get_mine_tool();
                mine_tool_ptr->m_attendance_start_time = tool_time::to_time_ex(start_time);
                mine_tool_ptr->m_stat_attendance = AS_ATTENDANCE;
            }

            area_hover_ptr->landmark_id = landmark_id;
            area_hover_ptr->landmark_dir = direction_mapper_id;
            area_hover_ptr->landmark_dis = landmark_dist;

            card_ptr->m_time = tool_time::now_to_ms();
        }
    }
}

void card_list::on_message(zloop<task*> *loop,const message_locinfo&loc,bool is_history)
{
	uint64_t cardid = tool_other::type_id_to_u64(loc.m_card_type,loc.m_card_id);
	const auto c=card_list::instance()->get(cardid);
	if(c==nullptr)
	{
		log_warn("数据库中未定义该卡的信息，card_id=%d, card_type=%d,cardid:%lld",loc.m_card_id,loc.m_card_type,cardid);
		return;
	}
	log_info("card message:site=%d,ant=%d,card=%d,tof=%lld,rav=%02X,acc=%02X,rssi=%d,stamp=%llu",
			loc.m_site_id,loc.m_ant_id,loc.m_card_id,loc.m_tof,loc.m_rav,loc.m_acc,loc.m_rssi,loc.m_time_stamp);

	c->on_message(loop,loc,is_history);
}

bool card_list_visit::visit(std::shared_ptr<card_location_base> c)
{
//	if(c->on_timer())
//		mine_business::inst()->put(c);
	return true;	
}

template<> std::shared_ptr<card_list> 
single_base<card_list, uint64_t, std::shared_ptr<card_location_base>>::m_instance=std::make_shared<card_list>();

