#include"module_attendance_person.h"

#include <chrono>
//#include <vector>

#include "websocket/wsClientMgr.h"
#include"mine.h"
#include "module_meta_date_changed.h"

#include "module_mine.h"
#include "common_tool.h"
#include "module_area.h"
#include"log.h"
#include "mine_module/MineCardManager.h"
#include"db/db_tool.h"


/**
 * @brief 进入分站覆盖区域处理，考勤
 * @param card_ptr
 * @param site_ptr
 */
void module_attendance_person::enter_site(std::shared_ptr<card_location_base> card_ptr, std::shared_ptr<site> site_ptr)
{
    // 从井下切换到井上为考勤结束
    // 从井下切换到井上为考勤结束
    if(site_ptr->is_up_site())
    {
        up_mine(card_ptr, site_ptr);
        //检查井下是否超员--是否需要取消
        CMineCardManager::instance()->OnPersonUp(card_ptr);
    }
    else// 从井上切换到井下为考勤开始
    {
        auto mine_tool_ptr = card_ptr->get_mine_tool();
        if(!mine_tool_ptr->is_attendance())
        {
            //考勤开始
            mine_tool_ptr->m_stat_attendance=AS_ATTENDANCE;

            mine_tool_ptr->m_attendance_start_time=std::chrono::system_clock::now();

            //作为一条开始考勤记录保存到数据库
            db_tool::save_attendance(card_ptr);

            log_info("人卡考勤开始：卡id=%d，卡type=%d，分站id=%d,分站reader_type_id=%d,stat_attendance=%d",
                     card_ptr->m_id, card_ptr->m_type,
                     site_ptr->m_id,site_ptr->m_reader_type_id,mine_tool_ptr->m_stat_attendance);
        }

        //检查井下是否超员
        CMineCardManager::instance()->OnPersonDown(card_ptr);
    }
}

  /**
   * @brief 离开现有分站处理，记录现有分站的进出时间和地点
   * @param card_ptr
   * @param site_ptr
   */
  void module_attendance_person::leave_site(std::shared_ptr<card_location_base> card_ptr, std::shared_ptr<site> site_ptr)
  {

  }

///升井或收到web的删除卡命令  site_ptr==nullptr表示收到web的删除卡命令
/// 保存考勤记录，发升井json，清理卡
void module_attendance_person::up_mine(std::shared_ptr<card_location_base> card_ptr, std::shared_ptr<site> site_ptr)
{
    auto mine_tool_ptr = card_ptr->get_mine_tool();
    if(!mine_tool_ptr->is_attendance())
    {
        return;
    }

    //考勤结束
    mine_tool_ptr->m_stat_attendance=AS_NOT_ATTENDANCE;

    //作为一条结束考勤记录保存到数据库
    db_tool::save_attendance(card_ptr);

    rapidjson::Document doc(rapidjson::kObjectType);
    rapidjson::Value datas(rapidjson::kArrayType);
    rapidjson::Document::AllocatorType& allocator=doc.GetAllocator();

    _to_json_card_up_one(card_ptr, datas, allocator);
    module_meta_date_changed::clear_card(card_ptr);

    //升井json发给web
    if(datas.Size() > 0)
    {
        doc.AddMember(JSON_ROOT_KEY_CMD,JSON_CMD_VALUE_UP_MINE, allocator);
        //doc.AddMember(JSON_ROOT_KEY_VERSION,INTERFACE_VERSION, allocator);
        doc.AddMember(JSON_ROOT_KEY_DATA, datas, allocator);

        swsClientMgr.send(JSON_CMD_VALUE_PUSH, tool_json::doc_to_json(doc));
    }

    if(site_ptr)
    {
        log_info("人卡考勤结束：卡id=%d，卡type=%d，分站id=%d,分站reader_type_id=%d,stat_attendance=%d",
                 card_ptr->m_id, card_ptr->m_type,
                 site_ptr->m_id,site_ptr->m_reader_type_id,mine_tool_ptr->m_stat_attendance);
    }
    else
    {
        log_info("收到web的删除卡命令,人卡考勤结束：卡id=%d，卡type=%d， stat_attendance=%d",
                 card_ptr->m_id, card_ptr->m_type, mine_tool_ptr->m_stat_attendance);
    }
}

/**
 * @brief 手工升井函数
 */
void module_attendance_person::handle_up_mine(sio::message::ptr const& data)
{
    std::vector<sio::message::ptr> card_vec;
    if(!tool_map::try_get_value(card_vec, JSON_ROOT_KEY_DATA, data) || card_vec.size() == 0)
    {
        log_error("手工升井，web发来的数据data字段为空 或者不是数组");
        return;
    }

    rapidjson::Document doc(rapidjson::kObjectType);
    rapidjson::Value datas(rapidjson::kArrayType);
    rapidjson::Document::AllocatorType& allocator=doc.GetAllocator();

    std::vector<sio::message::ptr>::const_iterator it_card = card_vec.begin();
    int type = 0;
    std::string s_card_id;
    for(; it_card != card_vec.end(); ++it_card)
    {
        if(!tool_map::try_get_value(s_card_id, JSON_KEY_CALL_CARD_CARD_ID, (*it_card))
           ||!tool_map::try_get_value(type, JSON_KEY_CALL_CARD_CARD_TYPE_ID, (*it_card)))
        {
            log_error("手工升井，web发来的数据 card_id 或 card_type格式不对");
            continue;
        }

        uint32_t id = tool_other::id64_to_id(s_card_id);
        auto card_ptr = card_list::instance()->get(tool_other::type_id_to_u64(type, id));
        if(card_ptr && card_ptr->is_person())
        {
            std_debug("手工升井，处理，卡id=%d，卡type=%d", id, type);
            log_info("手工升井，处理，卡id=%d，卡type=%d", id, type);

            auto mine_tool_ptr = card_ptr->get_mine_tool();
            if(mine_tool_ptr->is_attendance())
            {
                //考勤结束
                mine_tool_ptr->m_stat_attendance=AS_NOT_ATTENDANCE;

                //作为一条结束考勤记录保存到数据库
                db_tool::save_attendance(card_ptr);
            }

            //检查井下是否超员--是否需要取消
            CMineCardManager::instance()->OnPersonUp(card_ptr);

            auto area_hover_ptr = card_ptr->get_area_hover();
            if(area_hover_ptr && 0!=area_hover_ptr->id() && 0!=area_hover_ptr->mapid())
            {
                module_area::on_leave(card_ptr->m_id, area_hover_ptr, card_ptr->m_type);
            }

            _to_json_card_up_one(card_ptr, datas, allocator);
            module_meta_date_changed::clear_card(card_ptr);
        }
        else
        {
            log_error("手工升井，在全局列表中找不到卡，卡id=%d，卡type=%d", id, type);
        }
    }

    //升井json发给web
    if(datas.Size() > 0)
    {
        doc.AddMember(JSON_ROOT_KEY_CMD,JSON_CMD_VALUE_UP_MINE, allocator);
        //doc.AddMember(JSON_ROOT_KEY_VERSION,INTERFACE_VERSION, allocator);
        doc.AddMember(JSON_ROOT_KEY_DATA, datas, allocator);

        swsClientMgr.send(JSON_CMD_VALUE_PUSH, tool_json::doc_to_json(doc));
    }
}

///升井json
void module_attendance_person::_to_json_card_up_one(std::shared_ptr<card_location_base> card_ptr,
                                   rapidjson::Value& out_datas, rapidjson::Document::AllocatorType& allocator)
{
    auto site_area_ptr = card_ptr->get_site_area();
    if(!card_ptr->m_display || !site_area_ptr || site_area_ptr->is_invalid())
    {
        return;
    }

    auto mine_tool_ptr = card_ptr->get_mine_tool();

    rapidjson::Value data(rapidjson::kArrayType);
    //卡号
    std::string id = tool_other::type_id_to_str(card_ptr->m_type, card_ptr->m_id);
    tool_json::push_back(data, id, allocator);

    //x,y坐标
    data.PushBack(card_ptr->x, allocator);
    data.PushBack(card_ptr->y, allocator); //CFunctions::round(card->y_offset_after(),2)

    //入井时间戳
    uint64_t t = tool_time::to_ms(mine_tool_ptr->m_attendance_start_time);	//转为ms
    data.PushBack(t, allocator);

    //进入区域时间戳
    data.PushBack(0, allocator);

    //接收时间戳
    data.PushBack(0, allocator);
    //工作时长
    t = tool_time::elapse_ms(mine_tool_ptr->m_attendance_start_time);	//转为ms
    data.PushBack(t, allocator);

    //地图编号
    data.PushBack(0, allocator);
    //区域编号
    data.PushBack(0, allocator);
    //部门编号
    data.PushBack(card_ptr->m_deptid, allocator);

    //状态
    data.PushBack(0, allocator);
    //运行状态
    data.PushBack(card_ptr->m_stat, allocator);
    //业务状态
    data.PushBack(0, allocator);
    //速度
    data.PushBack(card_ptr->m_speed, allocator);


    out_datas.PushBack(data, allocator);
}




