#pragma once

#include <thread>
#include <Eigen/Core>
#include <Eigen/Geometry>

#include "tool/error_code.hpp"
#include "ceres_detect/detect_wheel_ceres.h"
#include "proto/enum_type.pb.h"
#include "proto/detect_message.pb.h"
#include "thread/thread_condition.h"
#include "vzense/device_tof3d.h"

#include "detect/ceres_detect/car_pose_detector.h"
#include "detect/ceres_detect/wheel_detector.h"
#include "detect/ceres_detect/detect_wheel_ceres.h"
#include "detect/data_buf_lable.hpp"
#include "communication/transitData.h"
#include "proto/def.grpc.pb.h"

class DetectManager {
public:
    struct DetectResult {
        WheelCeresDetector::WheelDetectResult wheel[DeviceAzimuth::DEVICE_AZIMUTH_MAX];
        Car_pose_detector::CarDetectResult car;

        void reset() {
            for (int i = 0; i < DeviceAzimuth::DEVICE_AZIMUTH_MAX; i++) {
                wheel[i].reset();
            }
            car.reset();
        }

        std::string info() {
            std::string str = car.info();
            for (int i = 0; i < DeviceAzimuth::DEVICE_AZIMUTH_MAX; i++) {
                str += wheel[i].info();
            }
            return str;
        }
    };

    struct RecordImages {
        std::string name_1;         // 图片名, 表示图片被保存时的时间;
        std::string name_2;
        std::string name_3;
        std::string name_4;
        cv::Mat img_1;              // 四和一图片, 第一张是第一次识别到一个识别结果情况下的图片
        cv::Mat img_2;              // 四和一图片, 第二张是第一次识别到二个识别结果情况下的图片
        cv::Mat img_3;              // 四和一图片, 第三张是第一次识别到三个识别结果情况下的图片
        cv::Mat img_4;              // 四和一图片, 第四张是第一次识别到四个识别结果情况下的图片
    };

public:
    static DetectManager *iter() {
        static DetectManager *instance = nullptr;
        if (instance == nullptr) {
            instance = new DetectManager();
        }
        return instance;
    }

    ~DetectManager() = default;

    Error_manager Init(const google::protobuf::RepeatedPtrField<tof3dVzenseEtc> &tof_devices);

    Error_manager Release();

    Error_manager Stop();

    Error_manager Continue();

    MeasureStatu getMeasureResult(DetectResult &result);

    Error_manager carMoveStatus();
protected:
    Error_manager updateTrans(const DeviceAzimuth &azimuth, const CoordinateTransformation3D &trans);

    void run();

    void stop();

    // 车轮点云优化
    Error_manager WheelCloudOptimize(std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> &vct_wheel_cloud, DetectResult &result);

private:
    std::thread *m_thread;
    Thread_condition m_condit;

    TimedLockData<bool> move_statu;
    TimedLockData<MeasureStatu> detect_statu;
    TimedLockData<Eigen::Matrix4f> rotation_matrix4[DeviceAzimuth::DEVICE_AZIMUTH_MAX];
    TimedLockData<DetectResult> m_detect_result_time_lock_data;
};


