<?php


namespace App\Services;


use App\Exceptions\ErrorException;
use App\Exceptions\PanicException;
use App\MaterialBox;
use App\StationTaskMaterialBox;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Http;
use Ramsey\Collection\Collection;

class ForeignHaiRoboticsService
{
    /**
     * @param string $modeName '输送线入立架'|'立架出至输送线'|'移动立架内位置'|'缓存架入立架'|'立架出至缓存架'
     * @param string $fromLocation
     * @param string $toLocation
     * @param Collection $taskMaterialBoxes
     * @param string $groupId
     * @param int $priority
     * @param int $isSequenced
     */
    private function makeJson_move(
        Collection $taskMaterialBoxes,
        string $modeName,
        string $fromLocation='',
        string $toLocation='',
        $groupId=''
        , $priority=10
        , $isSequenced=1
    ){
        $timestampSuffix = microtime(true);
        $taskMode=(function()use($modeName){
            switch ($modeName){
                case '输送线入立架': return 1;
                case '立架出至输送线': return 2;
                case '移动立架内位置': return 3;
                case '缓存架入立架':
                case '立架出至缓存架': return 6;
                default: throw new \Exception('发至海柔的移料箱请求，模式不存在');
            }
        })();
        $bins=$taskMaterialBoxes->map(function (StationTaskMaterialBox $taskMaterialBox)use($timestampSuffix){
            return [
                "taskCode"  =>"{$taskMaterialBox['id']}_{$taskMaterialBox['material_box_id']}_{$timestampSuffix}",
                "binCode"   => $taskMaterialBox['materialBox']['code'],
                "fromLocCode" => $fromLocation??'',
                "toLocCode" => $toLocation??'',
            ];
        });
        $groupId .= $timestampSuffix;
        return [
            "taskMode"  =>$taskMode,
            "bins"=>$bins,
            "groupCode"=>$groupId,
            "priority"=>$priority,
            "sequenceFlag"=>$isSequenced,
        ];
    }

    public function fetchGroupToProcessor($toLocation, Collection $taskMaterialBoxes, $groupIdPrefix=''): bool
    {
        $dataToPost=$this->makeJson_move(
            $taskMaterialBoxes,
            '立架出至输送线',
            '',
            $toLocation,
            $groupIdPrefix
        );
        $response = Http::post(config('api.haiq.storage.moveBin'),$dataToPost);
        $errMsg=(function()use($response){
            if($response->ok())return '';
            $errMsg = '错误: ';
            if (!$response){
                return $errMsg.'没有返回内容，检查连接或目标服务器';
            }
            switch (((string)$response["code"])[0]){
                case 5: $errMsg.='目标服务器代码错误，请联系对方';break;
                case 4: $errMsg.='权限不足以请求资源，请检查对方服务器规范';break;
                default: $errMsg.='出现未知请求错误';break;
            }
            $responseDetails=' code:'.$response["code"]
                .' header:'.$response->body()
                .' response:'.json_encode($response->headers());
            return $errMsg.$responseDetails;
        })();

        LogService::log(__METHOD__,__FUNCTION__,
            $errMsg??''
            .'请求：'.json_encode($dataToPost)
            .'调用堆栈：'.json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),0,3))
        );
        return $isSuccess=!$errMsg;
    }

    public function moveBin(){

    }

    public function markBinProcessed(){

    }
    public function taskUpdate(
        $groupCode,
        $taskCode,
        $updateEventType,   //0：task_begin(取货)1：task_end（放货）
        $status,            //0：任务成功1：任务失败
        $binCode,
        $robotId,
        $description
    ):bool{
        if($status==1){
            return $this->excepted();
        }
        switch ($updateEventType){
            case 0:
            case 1:
        }
        $this->markHasGet();

    }
    public function markHasPut(
        $groupCode,
        $taskCode,
        $updateEventType,   //0：task_begin(取货)1：task_end（放货）
        $status,            //0：任务成功1：任务失败
        $binCode,
        $robotId,
        $description
    ):bool{


    }
    public function markHasGet(
        $groupCode,
        $taskCode,
        $updateEventType,   //0：task_begin(取货)1：task_end（放货）
        $status,            //0：任务成功1：任务失败
        $binCode,
        $robotId,
        $description
    ):bool{


    }


    public function excepted():bool{

    }

}
