#include "ytj.h"

#include "app/app.h"
#include "common/snowflake/snowflake.h"
#include "common/spdlog/logging.h"
#include "common/utils/biz_lock.h"
#include "mqtt/mqtt_cli.h"

namespace zsy
{
    Ytj::Ytj(YtjConfig config)
        : config(std::move(config))
    {
        if (const auto mqttCli = MQTTCli::get(config.mqtt_sn()))
        {
            if (config.has_barrier_config())
            {
                barrier = std::make_shared<YtjBarrier>(config.dev_sn(), config.barrier_config().io(), mqttCli);
            }
            if (config.has_vidicon_config())
            {
                vidicon = std::make_shared<YtjVidicon>(config.dev_sn(), config.vidicon_config().timeout(), config.vidicon_config().enable_recognize(), mqttCli);
                connect(vidicon.get(), &YtjVidicon::recognizeComplete, this, &Ytj::onRecognizeComplete);
            }
        }
    }

    std::string Ytj::sn() const
    {
        return config.sn();
    }

    std::string Ytj::name() const
    {
        return config.name();
    }

    void Ytj::open(const std::string &id)
    {
        if (barrier)
        {
            barrier->gpioOut(id.empty() ? Snowflake::genIdStr() : id, 2);
        } else
        {
            LOGGER_ERROR("未配置道闸");
        }
    }

    std::string Ytj::photograph()
    {
        if (vidicon)
        {
            return vidicon->photograph();
        } else
        {
            LOGGER_ERROR("未配置摄像机");
            return "";
        }
    }

    void Ytj::onRecognizeComplete(bool success, std::string id, std::string licensePlate, std::string image)
    {
        if (!success)
        {
            LOGGER_ERROR("解析车牌识别结果失败");
            return;
        }
        if (const auto mqttCli = MQTTCli::get(config.mqtt_sn()))
        {
            mqttCli->publish("wbs/discover_truck", JSON::toJsonStr(RecognizeData{
                                 .id = id,
                                 .sn = App::sn(),
                                 .stationSn = App::stationSn(),
                                 .front = config.front(),
                                 .groupSn = config.group_sn(),
                                 .barrierSn = config.dev_sn(),
                                 .licensePlate = licensePlate,
                                 .image = image,
                             }));
        }
    }
} // zsy