<?php

/**
 * DBLogicRedisScript.php
 * 文件描述
 * Created On 2022/1/11
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Framework\DB\DBLogic;

use Framework\DB\DBCondition;
use Framework\DB\DBLogicBase;
use Library\DB\IRedis;
use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;

class DBLogicRedisScript extends DBLogicBase
{
    protected DBCondition $condition;

    protected int $keyNum;

    protected string $sha;

    protected array $scriptParam;

    protected array $result;

    public function checkParam(DBCondition $param): bool
    {
        $this->condition = $param;
        $this->scriptParam = $this->condition->param;
        return true;
    }

    public function execute(IRedis $redis): bool
    {
        $result = "";
        if (!$redis->evalSha($result, $this->sha, $this->scriptParam, $this->keyNum)) {
            $this->condition->exe_error = $redis->getLastError();
            LogMark::getInstance()->markError(
                ErrorDefine::REDIS_COMMAND_RUN_FAIL,
                "redis script run fail",
                array("sha" => $this->sha,
                    "redisError" => $this->condition->exe_error,
                    "param" => json_encode($this->scriptParam))
            );
            return false;
        }
        $this->result = json_decode($result, true);
        if ($this->result['error'] != "success") {
            if(!empty($this->result['result'])) {
                return true;
            }
            $this->condition->exe_error = $this->result['error'];
            LogMark::getInstance()->markError(
                ErrorDefine::REDIS_COMMAND_RUN_FAIL,
                "redis script run fail",
                array("sha" => $this->sha,
                    "redisError" => $this->condition->exe_error,
                    "param" => json_encode($this->scriptParam))
            );
            return false;
        }
        return true;
    }

    public function dealResult(&$des): bool
    {
        $des = $this->result['result'];
        return true;
    }
}
