//
// Created by huli on 2020/7/2.
//

#include "system_executor.h"

// std::ofstream g_debug_file; // 用于测试滤波功能

System_executor::System_executor()
{

}

System_executor::~System_executor()
{
	system_executor_uninit();
}

//初始化
Error_manager System_executor::system_executor_init(int threads_size, int terminal_id)
{
	m_thread_pool.thread_pool_init(threads_size);
	m_system_executor_status = SYSTEM_EXECUTOR_READY;
	m_terminal_id = terminal_id;
	PathCreator pc;
	pc.Mkdir("./log/");
	return Error_code::SUCCESS;
}

//反初始化
Error_manager System_executor::system_executor_uninit()
{
    // if(g_debug_file.is_open())
    //     g_debug_file.close();

	m_thread_pool.thread_pool_uninit();
	m_system_executor_status = SYSTEM_EXECUTOR_UNKNOW;
	return Error_code::SUCCESS;
}

//检查消息是否有效, 主要检查消息类型和接受者, 判断这条消息是不是给我的.
Error_manager System_executor::check_msg(Communication_message* p_msg)
{
	if ( p_msg == nullptr )
	{
		return Error_manager(Error_code::POINTER_IS_NULL, Error_level::MINOR_ERROR,
							 "  POINTER IS NULL ");
	}

	//检查消息类型
	switch ( p_msg->get_message_type() )
	{
		case Communication_message::Message_type::eGround_detect_request_msg:
		{
			//检查接受人
			if ( p_msg->get_receiver() == Communication_message::Communicator::eGround_measurer)
			{
				message::Ground_detect_request_msg t_ground_detect_request_msg;
				//针对消息类型, 对消息进行二次解析
				if (t_ground_detect_request_msg.ParseFromString(p_msg->get_message_buf()))
				{
					// //检查终端id
					// 普爱不检查终端id
					// 楚天检查终端id
					// if ( t_ground_detect_request_msg.terminal_id() == m_terminal_id )
					// {
						return Error_code::SUCCESS;
					// }
				}
			}
			break;
		}
		default :
			;
			break;
	}


	//无效的消息,
	return Error_manager(Error_code::INVALID_MESSAGE, Error_level::NEGLIGIBLE_ERROR,
						 " INVALID_MESSAGE error ");
}

//检查执行者的状态, 判断能否处理这条消息,
Error_manager System_executor::check_executer(Communication_message* p_msg)
{
	return Error_code::SUCCESS;
}


//处理消息的执行函数
Error_manager System_executor::execute_msg(Communication_message* p_msg)
{
	if ( p_msg == nullptr )
	{
		return Error_manager(Error_code::POINTER_IS_NULL, Error_level::MINOR_ERROR,
							 "  POINTER IS NULL ");
	}

	// std::cout << " huli test ::333333333333333333333333333333:: " << " p_msg->get_message_type() = " << p_msg->get_message_type() << std::endl;
	switch ( p_msg->get_message_type() )
	{
		case Communication_message::eGround_detect_request_msg:
		{
			message::Ground_detect_request_msg t_ground_detect_request_msg;
			//针对消息类型, 对消息进行二次解析
			if (t_ground_detect_request_msg.ParseFromString(p_msg->get_message_buf()) && t_ground_detect_request_msg.id_struct().has_terminal_id())
			{

				//往线程池添加执行任务, 之后会唤醒一个线程去执行他.
				m_thread_pool.enqueue(&System_executor::execute_for_measure, this,
									  t_ground_detect_request_msg.command_key(), t_ground_detect_request_msg.id_struct().terminal_id(),
									  p_msg->get_receive_time());
			}
			else
			{
				return Error_manager(Error_code::SYSTEM_EXECUTOR_PARSE_ERROR, Error_level::MINOR_ERROR,
									 " message::Measure_request_msg  ParseFromString error ");
			}
			break;
		}
		default:
		{

		}
	}


	return Error_code::SUCCESS;
}

//检查状态
Error_manager System_executor::check_status()
{
	if ( m_system_executor_status == SYSTEM_EXECUTOR_READY )
	{
		if ( m_thread_pool.thread_is_full_load() == false )
		{
			return Error_code::SUCCESS;
		}
		else
		{
			return Error_manager(Error_code::SYSTEM_EXECUTOR_STATUS_BUSY, Error_level::NEGLIGIBLE_ERROR,
								 " System_executor::check_status error ");
		}
	}
	else
	{
		return Error_manager(Error_code::SYSTEM_EXECUTOR_STATUS_ERROR, Error_level::MINOR_ERROR,
							 " System_executor::check_status error ");
	}
}

bool System_executor::update_measure_info(measure_info &msg, Common_data::Car_wheel_information &measure_info, bool empty) {
    msg.set_cx(measure_info.uniform_car_x);
    msg.set_cy(measure_info.uniform_car_y);
    msg.set_theta(measure_info.car_angle);
    msg.set_length(measure_info.car_length);
    msg.set_width(measure_info.car_wheel_width);
    msg.set_height(0.0f);
    msg.set_wheelbase(measure_info.car_wheel_base);
    msg.set_front_theta(measure_info.car_front_theta);
    msg.set_border_statu(measure_info.range_status);
    msg.set_motion_statu(measure_info.motion_statu);
    msg.set_move_distance(measure_info.forward_dis);

    if (!measure_info.correctness)
    {
        if (empty) {
            msg.set_ground_status(MeasureStatu::Measure_Empty_Clouds);
        } else {
            msg.set_ground_status(MeasureStatu::Measure_Failture);
        }
    } else if (measure_info.range_status == int(Range_status::Range_correct))
    {
        msg.set_ground_status(MeasureStatu::Measure_OK);
    }
    else
    {
        msg.set_ground_status(MeasureStatu::Measure_Border);
    }

    return true;
}

// ***************************** rabbitmq *********************************
Error_manager System_executor::encapsulate_send_mq_status()
{
	Error_manager t_error;
	//创建一条状态消息
	message::Ground_status_msg t_ground_status_msg;
	t_ground_status_msg.mutable_base_info()->set_msg_type(message::Message_type::eGround_status_msg);
	t_ground_status_msg.mutable_base_info()->set_timeout_ms(5000);
	t_ground_status_msg.mutable_base_info()->set_sender(message::Communicator::eGround_measurer);
	t_ground_status_msg.mutable_base_info()->set_receiver(message::Communicator::eEmpty);

	t_ground_status_msg.mutable_id_struct()->set_terminal_id(m_terminal_id);

	// 以多线雷达为主
	Velodyne_manager::Velodyne_manager_status t_velodyne_manager_status = Velodyne_manager::get_instance_references().get_status();
	t_ground_status_msg.set_wanji_manager_status((message::Wanji_manager_status)t_velodyne_manager_status);

	// vlp16 lidar
	std::map<int, Velodyne_lidar_device *> t_velodyne_lidar_device_map = Velodyne_manager::get_instance_references().get_velodyne_lidar_device_map();
	std::map<int, Velodyne_lidar_device::Velodyne_lidar_device_status> t_velodyne_lidar_status_map;
	for (auto &iter : t_velodyne_lidar_device_map)
	{
		t_velodyne_lidar_status_map.emplace(std::pair<int, Velodyne_lidar_device::Velodyne_lidar_device_status>(iter.second->get_lidar_id(), iter.second->get_status()));
		DLOG(INFO) << "lidar " << iter.second->get_lidar_id() << " statu: " << iter.second->get_status();
	}

	// vlp16 region
	std::map<int, Ground_region *> t_ground_region_map = Velodyne_manager::get_instance_references().get_ground_region_map();
	for (auto iter = t_ground_region_map.begin(); iter != t_ground_region_map.end(); ++iter)
	{
		// 以t_ground_status_msg为模板创建各区域心跳消息
		message::Ground_status_msg t_multi_status_msg;
		t_multi_status_msg.CopyFrom(t_ground_status_msg);
		t_multi_status_msg.mutable_id_struct()->set_terminal_id(iter->second->get_terminal_id());
		t_multi_status_msg.set_region_worker_status((message::Region_worker_status)(iter->second->get_status()));
		// 查找多线区域内对应多线激光雷达
		velodyne::Region t_param = iter->second->get_param();
		for (size_t j = 0; j < t_param.lidar_exts_size(); j++)
		{
			auto t_status_iter = t_velodyne_lidar_status_map.find(t_param.lidar_exts(j).lidar_id());
			if (t_status_iter == t_velodyne_lidar_status_map.end())
			{
				LOG(WARNING) << "vlp16 lidar status " << t_param.lidar_exts(j).lidar_id() << " cannot be found, param error";
			}
			else
			{
				t_multi_status_msg.add_wanji_lidar_device_status((message::Wanji_lidar_device_status)t_status_iter->second);
			}
		}


		// 获取区域点云填入信息
        measure_buffer measure_result;
		pcl::PointCloud<pcl::PointXYZ>::Ptr t_region_cloud(new pcl::PointCloud<pcl::PointXYZ>);
		iter->second->get_region_cloud(t_region_cloud, Ground_region::Region_cloud_type::filtered);

        //velodyne雷达的自动定位信息
        measure_info t_plc_forward_measure_info_msg, t_plc_reverse_measure_info_msg, t_plc_terminal_measure_info_msg;
        std::vector<Common_data::Car_wheel_information> t_car_wheel_information;
        // plc正向
        iter->second->get_last_wheel_information(t_car_wheel_information, std::chrono::system_clock::now());

		if (!t_car_wheel_information.empty()) {
        	update_measure_info(t_plc_forward_measure_info_msg, t_car_wheel_information[0], t_region_cloud->empty());
			update_measure_info(t_plc_reverse_measure_info_msg, t_car_wheel_information[1], t_region_cloud->empty());
			update_measure_info(t_plc_terminal_measure_info_msg, t_car_wheel_information[2], t_region_cloud->empty());
		} else {
			Common_data::Car_wheel_information t_cwi;
			update_measure_info(t_plc_forward_measure_info_msg, t_cwi, t_region_cloud->empty());
			update_measure_info(t_plc_reverse_measure_info_msg, t_cwi, t_region_cloud->empty());
			update_measure_info(t_plc_terminal_measure_info_msg, t_cwi, t_region_cloud->empty());
		}

        for (auto &statu : t_multi_status_msg.wanji_lidar_device_status()) {
            if (statu != message::Wanji_lidar_device_status::WANJI_LIDAR_DEVICE_READY) {
                t_plc_forward_measure_info_msg.set_ground_status(MeasureStatu::Lidar_Disconnect);
                t_plc_reverse_measure_info_msg.set_ground_status(MeasureStatu::Lidar_Disconnect);
                t_plc_terminal_measure_info_msg.set_ground_status(MeasureStatu::Lidar_Disconnect);
                break;
            }
        }

        measure_result.mutable_measure_info_to_plc_forward()->CopyFrom(t_plc_forward_measure_info_msg);
        measure_result.mutable_measure_info_to_plc_reverse()->CopyFrom(t_plc_reverse_measure_info_msg);
        measure_result.mutable_measure_info_to_terminal()->CopyFrom(t_plc_terminal_measure_info_msg);
		std::string t_msg = measure_result.DebugString();
		System_communication_mq::get_instance_references().encapsulate_status_msg(t_msg, t_multi_status_msg.id_struct().terminal_id());
	}

	return Error_code::SUCCESS;
}

// ***************************** nanomsg *********************************
//定时发送状态信息
Error_manager System_executor::encapsulate_send_status()
{
	return Error_code::FAILED;
}

//判断是否为待机，如果已经准备好，则可以执行任务。
bool System_executor::is_ready()
{
	if (m_system_executor_status == SYSTEM_EXECUTOR_READY && m_thread_pool.thread_is_full_load() == false)
	{
		return true;
	}
	else
	{
		return false;
	}
}

	System_executor::System_executor_status System_executor::get_system_executor_status()
	{
		return m_system_executor_status;
	}

	int System_executor::get_terminal_id()
	{
		return m_terminal_id;
	}

	//雷达感测定位 的处理函数
	//input::command_id, 消息指令id, 由主控制系统生成的唯一码
	//input::command_id, 终端id, 对应具体的某个车位
	//return::void, 没有返回, 执行结果直接生成一条答复消息, 然后通过通信返回
	void System_executor::execute_for_measure(std::string command_info, int terminal_id, std::chrono::system_clock::time_point receive_time)
	{
		Error_manager t_error;
		Error_manager t_result;
		LOG(INFO) << " System_executor::execute_for_measure run " << this;

		//第1步, 按照时间生成中间文件的保存路径
		time_t nowTime;
		nowTime = time(NULL);
		struct tm *sysTime = localtime(&nowTime);
		char t_save_path[256] = {0};
		sprintf(t_save_path, "../data/%04d%02d%02d_%02d%02d%02d",
				sysTime->tm_year + 1900, sysTime->tm_mon + 1, sysTime->tm_mday, sysTime->tm_hour, sysTime->tm_min, sysTime->tm_sec);

		//第2步, 创建万集管理模块的任务单, 并发送到 wanji_manager
		// Wanji_manager_task  t_wanji_manager_task ;
		// Common_data::Car_wheel_information	t_car_information_by_wanji;
		// t_wanji_manager_task.task_init(TASK_CREATED,"",NULL,std::chrono::milliseconds(3000),
		// 							   terminal_id, receive_time);
		// t_error = Task_command_manager::get_instance_references().execute_task(&t_wanji_manager_task);
		// 或者创建velodyne管理模块任务单，并发送到velodyne_manager
		Velodyne_manager_task t_velodyne_manager_task;
		Common_data::Car_wheel_information t_car_information_by_velodyne;
		t_velodyne_manager_task.task_init(TASK_CREATED, "", NULL, std::chrono::milliseconds(3000),
										  terminal_id, receive_time);
		t_error = Task_command_manager::get_instance_references().execute_task(&t_velodyne_manager_task);

		//第3步, 等待任务单完成
		if (t_error != Error_code::SUCCESS)
		{
			LOG(INFO) << " Velodyne_manager/Velodyne_manager  execute_task   error " << this;
		}
		else
		{
			// //判断任务是否结束, 阻塞 等待, 直到任务完成或者超时
			// while ( t_wanji_manager_task.is_task_end() == false)
			// {
			// 	if ( t_wanji_manager_task.is_over_time() )
			// 	{
			// 		//超时处理。取消任务。
			// 		Wanji_manager::get_instance_pointer()->cancel_task(&t_wanji_manager_task);
			// 		t_error.error_manager_reset(Error_code::WJ_MANAGER_TASK_OVER_TIME, Error_level::MINOR_ERROR,
			// 									" t_wanjestaui_manager_task is_over_time ");
			// 		t_wanji_manager_task.set_task_error_manager(t_error);
			// 	}
			// 	else
			// 	{
			// 		//继续等待
			// 		std::this_thread::sleep_for(std::chrono::microseconds(1));
			// 		std::this_thread::yield();
			// 	}
			// }

			// //提取任务单 的错误码
			// t_error = t_wanji_manager_task.get_task_error_manager();
			// if ( t_error == Error_code::SUCCESS )
			// {
			// 	t_car_information_by_wanji = t_wanji_manager_task.get_car_wheel_information();
			// }
			// else
			// {
			//     LOG(INFO) << " wanji_manager_task error :::::::"  << t_wanji_manager_task.get_task_error_manager().to_string() << this;
			// }
			// ------------------- 切换为velodyne ------------------
			//判断任务是否结束, 阻塞 等待, 直到任务完成或者超时
			while (t_velodyne_manager_task.is_task_end() == false)
			{
				if (t_velodyne_manager_task.is_over_time())
				{
					//超时处理。取消任务。
					Velodyne_manager::get_instance_pointer()->cancel_task(&t_velodyne_manager_task);
					t_error.error_manager_reset(Error_code::VELODYNE_MANAGER_TASK_OVER_TIME, Error_level::MINOR_ERROR,
												" t_velodyne_manager_task is_over_time ");
					t_velodyne_manager_task.set_task_error_manager(t_error);
				}
				else
				{
					//继续等待
					std::this_thread::sleep_for(std::chrono::microseconds(1));
					std::this_thread::yield();
				}
			}

			//提取任务单 的错误码
			t_error = t_velodyne_manager_task.get_task_error_manager();
			if (t_error == Error_code::SUCCESS)
			{
				t_car_information_by_velodyne = t_velodyne_manager_task.get_car_wheel_information();
			}
			else
			{
				LOG(INFO) << " velodyne_manager_task error :::::::" << t_velodyne_manager_task.get_task_error_manager().to_string() << this;
			}
		}
		t_result.compare_and_cover_error(t_error);

		//measure 测量模块的最终结果
		Common_data::Car_measure_information t_car_information_result;

		//第4步, 生成反馈消息
		// if(t_car_information_by_wanji.correctness == true )
		// {
		// 	t_car_information_result.center_x = t_car_information_by_wanji.center_x;
		// 	t_car_information_result.center_y = t_car_information_by_wanji.center_y;

		// 	t_car_information_result.car_angle = t_car_information_by_wanji.car_angle;
		// 	t_car_information_result.wheel_base = t_car_information_by_wanji.wheel_base;

		// 	t_car_information_result.wheel_width = t_car_information_by_wanji.wheel_width;
		// 	t_car_information_result.correctness = true;
		// }else{
		// 	t_result.set_error_level_down(NEGLIGIBLE_ERROR);
		// }
		// ------------------- 切换为velodyne ------------------
		if (t_car_information_by_velodyne.correctness == true)
		{
			t_car_information_result.car_center_x = t_car_information_by_velodyne.car_center_x;
			t_car_information_result.car_center_y = t_car_information_by_velodyne.car_center_y;

			t_car_information_result.car_angle = t_car_information_by_velodyne.car_angle;
			t_car_information_result.car_wheel_base = t_car_information_by_velodyne.car_wheel_base;

			t_car_information_result.car_wheel_width = t_car_information_by_velodyne.car_wheel_width;
			t_car_information_result.correctness = true;
		}
		else
		{
			t_result.set_error_level_down(NEGLIGIBLE_ERROR);
		}

		//第七步, 创建一条答复消息
		message::Ground_detect_response_msg t_ground_detect_response_msg;
		t_ground_detect_response_msg.mutable_base_info()->set_msg_type(message::Message_type::eGround_detect_response_msg);
		t_ground_detect_response_msg.mutable_base_info()->set_timeout_ms(5000);
		t_ground_detect_response_msg.mutable_base_info()->set_sender(message::Communicator::eGround_measurer);
		t_ground_detect_response_msg.mutable_base_info()->set_receiver(message::Communicator::eMain);

		t_ground_detect_response_msg.set_command_key(command_info);
		t_ground_detect_response_msg.mutable_id_struct()->set_terminal_id(terminal_id);
		t_ground_detect_response_msg.mutable_error_manager()->set_error_code(t_result.get_error_code());
		t_ground_detect_response_msg.mutable_error_manager()->set_error_level((message::Error_level)t_result.get_error_level());
		t_ground_detect_response_msg.mutable_error_manager()->set_error_description(t_result.get_error_description());

		t_ground_detect_response_msg.mutable_locate_information()->set_locate_x(t_car_information_result.car_center_x);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_y(t_car_information_result.car_center_y);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_angle(t_car_information_result.car_angle);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_length(t_car_information_result.car_length);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_width(t_car_information_result.car_width);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_height(t_car_information_result.car_height);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_wheel_base(t_car_information_result.car_wheel_base);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_wheel_width(t_car_information_result.car_wheel_width);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_front_theta(t_car_information_result.car_front_theta);
		t_ground_detect_response_msg.mutable_locate_information()->set_locate_correct(t_car_information_result.correctness);

		std::string t_msg = t_ground_detect_response_msg.SerializeAsString();
		System_communication::get_instance_references().encapsulate_msg(t_msg);

		std::cout << "huli t_measure_response_msg = " << t_ground_detect_response_msg.DebugString() << std::endl;

		return;
	}
