#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"

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());
            person* db_person_ptr= static_cast<person*>(db_person.get());

            tmp_ptr->m_cid = db_person_ptr->m_cid;
            tmp_ptr->m_type = db_person_ptr->m_type;
            tmp_ptr->m_deptid = db_person_ptr->m_deptid;
            //group_id
            //occ_id
            tmp_ptr->m_level_id = db_person_ptr->m_level_id;
            tmp_ptr->m_display = db_person_ptr->m_display;
            tmp_ptr->m_workLine = db_person_ptr->m_workLine;
            tmp_ptr->m_stafferName = db_person_ptr->m_stafferName;
            tmp_ptr->m_deptName = db_person_ptr->m_deptName;
            tmp_ptr->m_worktype_id = db_person_ptr->m_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();
}

void card_list::load_his_card_postion_vehicle()
{
    const char *sql = "select l.card_id,l.site_id, l.cur_time, l.x, l.y, l.z, l.area_info, l.state, \
            att.start_time, att.end_time \
            from rt_location l, rt_att_vehicle att, dat_card c, dat_vehicle_extend v \
            where l.card_id = c.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 );
            uint64_t c_id = tool_other::card_id_to_u64(card_id);
            auto card_ptr = card_list::instance()->get(c_id);

            if(!card_ptr)
            {
                log_error("全局卡列表中找不到卡，%s",card_id.c_str());
                continue;
            }

            int site_id = -1;
            DBRes.GetField( "site_id",site_id, Error );

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

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

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

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

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

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

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

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

            std::string cur_time  = "";
            DBRes.GetField( "cur_time",cur_time, Error );
            
            card_ptr->m_time = tool_time::to_time(cur_time)*1000;
            card_ptr->set(x,y,z);

            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_is_attendance = true;
                log_info("vehicle加载考勤,考勤开始时间： %s, 卡id=%s", start_time.c_str(), card_id.c_str());
            }

            auto area_tool=card_ptr->get_area_tool();
            auto sit_ptr=sit_list::instance()->get(site_id);
            if(sit_ptr)
            {
                auto area_hover_ptr = std::make_shared<area_hover>(sit_ptr->get_area(),*card_ptr);
                area_tool->m_hover_list.push_back(area_hover_ptr);
                area_tool->set(sit_ptr);
            }

            //解析area_info
            const char * split = "|";
            char *p = strtok(const_cast<char *>(strAreaInfo.c_str()), split);
            while (p != NULL)
            {
                int area_id = 0;
                uint64_t enter_time = 0; 
                sscanf(p, "%d,%lu", &area_id, &enter_time);
                p = strtok(NULL, split);
                if (area_id < 0)
                    continue;

                auto area = area_list::instance()->get(area_id);
                if(area == nullptr)
                {
                    log_error("load_vehicle...area_list 找不到区域：区域id=%d", area_id);
                    continue;
                }
                log_info("load_vehicle_area:%s,%d,%lu",card_id.c_str(),area_id,enter_time);
                //要放到最后
                auto area_hover_ptr = std::make_shared<area_hover>();
                area_hover_ptr->m_area = area;
                area_hover_ptr->m_enter_time = enter_time;
                area_tool->m_hover_list.push_back(area_hover_ptr);
                area->on_load_his(area_hover_ptr, card_ptr);
            }
        }
    }
}

void card_list::load_his_card_postion_staff()
{
    const char *sql = "select l.card_id,l.site_id, l.cur_time, l.x, l.y, l.z, l.area_info, l.state, \
            att.start_time, att.end_time \
            from rt_location l, rt_att_staff att, dat_card c, dat_staff_extend s \
            where l.card_id = c.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 );
            uint64_t c_id = tool_other::card_id_to_u64(card_id);
            auto card_ptr = card_list::instance()->get(c_id);

            if(!card_ptr)
            {
                log_error("全局卡列表中找不到卡，%s", card_id.c_str());
                continue;
            }

            int site_id = -1;
            DBRes.GetField( "site_id",site_id, Error );

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

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

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

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

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

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

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

            std::string cur_time  = "";
            DBRes.GetField( "cur_time",cur_time, Error );
            
            card_ptr->set(x,y,z);
            card_ptr->m_time = tool_time::to_time(cur_time)*1000;

            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_is_attendance = true;
                log_info("person加载考勤,考勤开始时间： %s, 卡id=%s", start_time.c_str(), card_id.c_str());
            }

            auto area_tool=card_ptr->get_area_tool();
            auto sit_ptr=sit_list::instance()->get(site_id);
            if(sit_ptr)
            {
                auto area_hover_ptr = std::make_shared<area_hover>(sit_ptr->get_area(),*card_ptr);
                area_tool->m_hover_list.push_back(area_hover_ptr);
                area_tool->set(sit_ptr);
            }

            //解析area_info
            const char * split = "|";
            char *p = strtok(const_cast<char *>(strAreaInfo.c_str()), split);
            while (p != NULL)
            {
                int area_id = 0;
                uint64_t enter_time = 0; 
                sscanf(p, "%d,%lu", &area_id, &enter_time);
                p = strtok(NULL, split);
                if (area_id < 0)
                    continue;

                auto area = area_list::instance()->get(area_id);
                if(area == nullptr)
                {
                    log_error("area_list 找不到区域：区域id=%d", area_id);
                    continue;
                }
                log_info("load_person_area:%s,%d,%lu",card_id.c_str(),area_id,enter_time);

                //要放到最后
                auto area_hover_ptr = std::make_shared<area_hover>();
                area_hover_ptr->m_area = area;
                area_hover_ptr->m_enter_time = enter_time;
                area_tool->m_hover_list.push_back(area_hover_ptr);
                area->on_load_his(area_hover_ptr, card_ptr);
            }
        }
    }
}

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)
{
	c->get_card();
	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>();

