
#include "log.h"
#include "db_api/CDBSingletonDefine.h"
#include "card_base.h"

#include "mine.h"
#include "area.h"

#include "tool_time.h"
#include "db_tool.h"
//#include "../common_tool.h"
namespace db_tool
{
    void PushAsync(const char* sql)
    {
        if(!sDBConnPool.PushAsync(sql))
        {
            log_error( "PushAsync记录到队列中失败\n");
        }
    }

	static std::string type_id_to_str(int32_t type,uint32_t id)
	{
		char sql[15] = {0};
		snprintf(sql, 15,"%03d%010d", type, id);
		return std::string(sql);
	}

    void save_attendance(const std::shared_ptr<card_location_base>& card_ptr,
                         const std::shared_ptr<area_hover>& area_hover_ptr)
    {
        char sql[LENGTH_SQL] = {0};

        std::string call("add_att_staff");
        if(card_ptr->is_vehicle())//车卡
        {
            call="add_att_vehicle";
        }

        auto mine_tool_ptr = card_ptr->get_mine_tool();

        auto start = mine_tool_ptr->m_attendance_start_time;
        auto end = mine_tool_ptr->m_attendance_start_time;
        if(!mine_tool_ptr->m_is_attendance)//考勤结束时间
        {
            end = std::chrono::system_clock::now();
        }

        std::string start_str = tool_time::to_str(start);
        std::string end_str = tool_time::to_str(end);
		auto map_area_info = card_ptr->get_area_tool()->m_area_info;
        int landmarkid,landmarkdirect=0;
        double landmarkdist=0;
		if(!map_area_info.empty())
		{
			auto lm = map_area_info.begin()->second;
			landmarkid = std::get<1>(lm);
       		landmarkdirect=std::get<2>(lm);
       		landmarkdist=std::get<3>(lm);
		}

        sprintf(sql, "CALL %s(%s, %d, '%s', '%s', %d, %d, %.3f);", call.c_str(),
               type_id_to_str(card_ptr->m_type,card_ptr->m_id).c_str(),
                card_ptr->m_id, start_str.c_str(), end_str.c_str(),
                landmarkid, landmarkdirect, landmarkdist);

        PushAsync(sql);
    }
}

