#include "recognize_processor.h"
#include "application.h"
#include "common/date_util.h"
#include "common/logging.h"
#include "common/sys_util.h"
#include "common/snowflake.h"

namespace zsy
{
    void RecognizeProcessor::process(std::shared_ptr<RecognizeData> data)
    {
        const std::string &sn = data->sn;
        const std::string &license = data->license;
        try
        {
            std::jthread t;
            if (data->isFront)
            {
                t = std::jthread([sn]
                {
                    Application::deviceHolder->getSoundColumn(sn)->play("欢迎光临");
                });
                t.detach();
            }

            // 上报 1
            auto reportPassResult = Application::reportSvr->reportPass(license, sn);
            if (!(reportPassResult.code == 0 && (reportPassResult.data.type == 1 || reportPassResult.data.type == 2)))
            {
                LOGGER_INFO("不进行后续处理");
                return;
            }
            addition_process(reportPassResult.data.orderNo, data);
        } catch (std::exception &e)
        {
            LOGGER_ERROR("车牌识别结果处理失败: {}", e.what());
        } catch (...)
        {
            LOGGER_ERROR("未知异常，车牌识别结果处理失败");
        }
    }

    void RecognizeProcessor::addition_process(const std::string &orderNo, std::shared_ptr<RecognizeData> data)
    {
        const std::string &sn = data->sn;
        const std::string &license = data->license;
        std::shared_ptr<std::istream> frontImageFile = data->imageFile;
        // 上报结果 type 不为 0，播放语音 2 并读地磅，拍车斗并上传
        std::jthread t([sn]
        {
            Application::deviceHolder->getSoundColumn(sn)->play("正在称重，请稍后");
        });
        auto bodyImageFile = Application::deviceHolder->getVidicon(sn)->photograph();

        const auto weight = Application::deviceHolder->getPlatformScale(sn)->reading();

        std::string date = DateUtil::format(Ymd);

        auto photoId = Snowflake::genIdStr();

        auto [carFrontUrlSucc,carFrontUrl] = Application::oss->upload(date + "/" + "front_" + photoId + ".jpg", frontImageFile);

        auto [carBodyUrlSucc,carBodyUrl] = Application::oss->upload(date + "/" + "body_" + photoId + ".jpg", bodyImageFile);

        // 上报 2
        Application::reportSvr->report(license, sn, weight, carFrontUrl, carBodyUrl, orderNo);
    }
} // zsy
