<?php
namespace Gm\Controller;
use Framework\Log\LogMark;
use Game\Protobuf\GMBanPlayer;
use Game\Protobuf\GMOutPlayer;
use Game\Protobuf\GMProhibitionPlayer;
use Game\Protobuf\GMServerModule;
use Game\Protobuf\GMSvnUP;
use Game\Protobuf\MGBanPlayer;
use Game\Protobuf\MGOutPlayer;
use Game\Protobuf\MGProhibitionPlayer;
use Game\Protobuf\MGServerModule;
use Game\Protobuf\MGSvnUP;
use Game\Protobuf\PacketId;
use Gm\Config\Config;
use Gm\Config\ErrorCode;
use Gm\Controller\Gm;
use Gm\Lib\Jwt;
use Gm\Model\Gms;
use Gm\Comm\CommFunc;

/**
 * Class Notice
 * 部分服务器操作
 */
class Operate {

    use CommFunc;

    public const DATA = 'data';
    public const INFO = 'info';
    public const MSG  = 'msg';
    public const TOKEN = 'Token';
    public const USERNAME = 'username';
    public const NAME = 'name';

    public function ModuleFindAndChange()
    {
        $params = json_decode(file_get_contents("php://input"));
        $server_id = (int)$params->server_id;
        $close_module = $params->close_module;   // 关闭模块
        $cModule = [];
        foreach ($close_module as $mid) {
            $cModule[] = $mid;
        }
        $option = (int)$params->option;          // 操作类型 1查询 2修改
        $user = Jwt::verifyToken();
        $token = getallheaders()[self::TOKEN];

        // 组装数据
        $msg = new MGServerModule();
        $msg->setOption($option);
        $msg->setCloseModule($cModule);

        if(!Gms::SaveMsgDB($server_id, PacketId::MG_ServerModule, $token, $msg)) {
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_SERVER_MODULE_SAVE_DB_FAILED,
                'send server module save msg db error!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_ServerModule, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_SERVER_MODULE_SAVE_DB_FAILED,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::LOG_MODULE, $user[self::INFO][self::USERNAME]
            );
            return ;
        }
        // 取出返回数据
        $code = 0;
        if(!Gms::SearchMsgDB($token, PacketId::GM_ServerModule, $data, $code, $server_id)) {
            if($code !== 0) {
                (new Gm())->CheckAPIResult(
                    $code,
                    [
                        self::DATA => [],
                        self::INFO =>  ErrorCode::CODE_MAP[$code],
                        self::MSG => ErrorCode::CODE_MAP[$code],
                    ],
                    Gm::LOG_MODULE, $user[self::INFO][self::USERNAME]
                );
                return ;
            }
            // 超时处理
            LogMark::getInstance()->markWarn(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                'search server module get data timeout!',
                ['serverID' => $server_id, 'packetID' => PacketId::GM_ServerModule, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::LOG_MODULE, $user[self::INFO][self::USERNAME]
            );
            return ;
        }

        // 解析数据
        $resData = base64_decode($data);
        $rankMsg = new GMServerModule();
        $rankMsg->mergeFromString($resData);
        $code = $rankMsg->getCode();
        $closeModule = [];
        foreach ($rankMsg->getCloseModule() as $id) {
            $closeModule[] = $id;
        }

        if($code == ErrorCode::SUCCESS) {
            $temp = [
                'closeModule' => $closeModule,
            ];
            $res[self::DATA] = $temp;
            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_SUCC];
            $res[self::MSG] = json_encode($temp);
        } else {
            $res[self::DATA] = [];
            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
            $res[self::MSG]  = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
        }

        (new Gm())->CheckAPIResult(
            $code,
            $res,
            Gm::LOG_MODULE,
            $user[self::INFO][self::USERNAME],
        );
    }

    public function OutPlayer()
    {
        $params = json_decode(file_get_contents("php://input"));
        $server_id = (int)$params->server_id;
        $role_id = $params->role_id;   // roleID
        $nick_name = $params->nick_name;   // 昵称

        $user = Jwt::verifyToken();
        $token = getallheaders()[self::TOKEN];

        // 组装数据
        $msg = new MGOutPlayer();
        $msg->setRoleID($role_id);
        $msg->setNickName($nick_name);

        if(!Gms::SaveMsgDB($server_id, PacketId::MG_OutPlayer, $token, $msg)) {
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_OUT_PLAYER_SAVE_DB_FAILED,
                'send out player save msg db error!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_OutPlayer, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_OUT_PLAYER_SAVE_DB_FAILED,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::OUT_PLAYER, $user[self::INFO][self::USERNAME]
            );
            return ;
        }
        // 取出返回数据
        $code = 0;
        if(!Gms::SearchMsgDB($token, PacketId::GM_OutPlayer, $data, $code, $server_id)) {
            if($code !== 0) {
                (new Gm())->CheckAPIResult(
                    $code,
                    [
                        self::DATA => [],
                        self::INFO =>  ErrorCode::CODE_MAP[$code],
                        self::MSG => ErrorCode::CODE_MAP[$code],
                    ],
                    Gm::OUT_PLAYER, $user[self::INFO][self::USERNAME]
                );
                return ;
            }
            // 超时处理
            LogMark::getInstance()->markWarn(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                'search out player res get data timeout!',
                ['serverID' => $server_id, 'packetID' => PacketId::GM_OutPlayer, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::OUT_PLAYER, $user[self::INFO][self::USERNAME]
            );
            return ;
        }

        // 解析数据
        $resData = base64_decode($data);
        $resMsg = new GMOutPlayer();
        $resMsg->mergeFromString($resData);
        $code = $resMsg->getCode();

        if($code == ErrorCode::SUCCESS) {
            $res[self::DATA] = [];
            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_SUCC];
            $res[self::MSG] = "";
        } else {
            $res[self::DATA] = [];
            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
            $res[self::MSG]  = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
        }

        (new Gm())->CheckAPIResult(
            $code,
            $res,
            Gm::OUT_PLAYER,
            $user[self::INFO][self::USERNAME],
        );
    }

    // 封禁玩家
    public function BanPlayer()
    {
        $params = json_decode(file_get_contents("php://input"));
        $server_id = (int)$params->server_id;
        $nick_name = $params->nick_name;
        $role_id = $params->role_id;
        $time_value = $params->time_value;
        $time_select = $params->time_select;
        $option = (int)$params->option;            // 操作类型 1查询 2修改
        $user = Jwt::verifyToken();
        $token = getallheaders()[self::TOKEN];

        // 组装数据
        $msg = new MGBanPlayer();
        $msg->setRoleID($role_id);
        $msg->setNickName($nick_name);
        $msg->setBanTime($time_value);
        $msg->setCTime($time_select);
        $msg->setOption($option);

        if(!Gms::SaveMsgDB($server_id, PacketId::MG_BanPlayer, $token, $msg)) {
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_BAN_PLAYER_SAVE_DB_FAILED,
                'send ban player save msg db error!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_BanPlayer, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_BAN_PLAYER_SAVE_DB_FAILED,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::BAN_PLAYER, $user[self::INFO][self::USERNAME]
            );
            return ;
        }
        // 取出返回数据
        $code = 0;
        if(!Gms::SearchMsgDB($token, PacketId::GM_BanPlayer, $data, $code, $server_id)) {
            if($code !== 0) {
                (new Gm())->CheckAPIResult(
                    $code,
                    [
                        self::DATA => [],
                        self::INFO =>  ErrorCode::CODE_MAP[$code],
                        self::MSG => ErrorCode::CODE_MAP[$code],
                    ],
                    Gm::BAN_PLAYER, $user[self::INFO][self::USERNAME]
                );
                return ;
            }
            // 超时处理
            LogMark::getInstance()->markWarn(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                'search ban player get data timeout!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_BanPlayer, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::BAN_PLAYER, $user[self::INFO][self::USERNAME]
            );
            return ;
        }

        // 解析数据
        $resData = base64_decode($data);
        $rankMsg = new GMBanPlayer();
        $rankMsg->mergeFromString($resData);
        $code = $rankMsg->getCode();
        $time = $rankMsg->getTime();

        if($code == ErrorCode::SUCCESS) {
            if(empty($time)) {
                $res[self::DATA] = [
                    'banTime' => $time
                ];
            } else {
                $res[self::DATA] = [
                    'banTime' => date("Y-m-d H:i:s", $time)
                ];
            }

            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_SUCC];
            $res[self::MSG] = $time;
        } else {
            $res[self::DATA] = [];
            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
            $res[self::MSG] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
        }

        (new Gm())->CheckAPIResult(
            $code,
            $res,
            Gm::BAN_PLAYER,
            $user[self::INFO][self::USERNAME],
        );
    }


    // 禁言玩家
    public function ProhibitionPlayer()
    {
        $params = json_decode(file_get_contents("php://input"));
        $server_id = (int)$params->server_id;
        $nick_name = $params->nick_name;
        $role_id = $params->role_id;
        $time_value = $params->time_value;
        $time_select = $params->time_select;
        $option = (int)$params->option;            // 操作类型 1查询 2修改
        $user = Jwt::verifyToken();
        $token = getallheaders()[self::TOKEN];

        // 组装数据
        $msg = new MGProhibitionPlayer();
        $msg->setRoleID($role_id);
        $msg->setNickName($nick_name);
        $msg->setProhibitionTime($time_value);
        $msg->setCTime($time_select);
        $msg->setOption($option);

        if(!Gms::SaveMsgDB($server_id, PacketId::MG_ProhibitionPlayer, $token, $msg)) {
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_PROHIBITION_PLAYER_SAVE_DB_FAILED,
                'send prohibition player save msg db error!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_ProhibitionPlayer, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_PROHIBITION_PLAYER_SAVE_DB_FAILED,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::PROHIBITION_PLAYER, $user[self::INFO][self::USERNAME]
            );
            return ;
        }
        // 取出返回数据
        $code = 0;
        if(!Gms::SearchMsgDB($token, PacketId::GM_ProhibitionPlayer, $data, $code, $server_id)) {
            if($code !== 0) {
                (new Gm())->CheckAPIResult(
                    $code,
                    [
                        self::DATA => [],
                        self::INFO =>  ErrorCode::CODE_MAP[$code],
                        self::MSG => ErrorCode::CODE_MAP[$code],
                    ],
                    Gm::PROHIBITION_PLAYER, $user[self::INFO][self::USERNAME]
                );
                return ;
            }
            // 超时处理
            LogMark::getInstance()->markWarn(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                'search prohibition player get data timeout!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_ProhibitionPlayer, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::PROHIBITION_PLAYER, $user[self::INFO][self::USERNAME]
            );
            return ;
        }

        // 解析数据
        $resData = base64_decode($data);
        $rankMsg = new GMProhibitionPlayer();
        $rankMsg->mergeFromString($resData);
        $code = $rankMsg->getCode();
        $time = $rankMsg->getTime();

        if($code == ErrorCode::SUCCESS) {
            if(empty($time)) {
                $res[self::DATA] = [
                    'prohibitionTime' => $time
                ];
            } else {
                $res[self::DATA] = [
                    'prohibitionTime' => date("Y-m-d H:i:s", $time)
                ];
            }

            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_SUCC];
            $res[self::MSG] = $time;
        } else {
            $res[self::DATA] = [];
            $res[self::INFO] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
            $res[self::MSG] = ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR];
        }

        (new Gm())->CheckAPIResult(
            $code,
            $res,
            Gm::PROHIBITION_PLAYER,
            $user[self::INFO][self::USERNAME],
        );
    }


    // svn 更新
    public function SvnUP()
    {
        $params = json_decode(file_get_contents("php://input"));
        $server_id = (int)$params->server_id;
        $svn_id = $params->svn_id;
        $svnDIR = Config::SVN_DIR_MAP[$svn_id];
        $user = Jwt::verifyToken();
        $token = getallheaders()[self::TOKEN];

        // 组装数据
        $msg = new MGSvnUP();
        $msg->setSvnDir($svnDIR);
        if(!Gms::SaveMsgDB($server_id, PacketId::MG_SvnUP, $token, $msg)) {
            LogMark::getInstance()->markError(
                ErrorCode::ERROR_SVN_UP_SAVE_DB_FAILED,
                'send svn up save msg db error!',
                ['serverID' => $server_id, 'packetID' => PacketId::MG_SvnUP, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_SVN_UP_SAVE_DB_FAILED,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::SVN_UP, $user[self::INFO][self::USERNAME]
            );
            return ;
        }
        // 取出返回数据
        $code = 0;
        if(!Gms::SearchMsgDB($token, PacketId::GM_SvnUP, $data, $code, $server_id, 600)) {
            if($code !== 0) {
                (new Gm())->CheckAPIResult(
                    $code,
                    [
                        self::DATA => [],
                        self::INFO =>  ErrorCode::CODE_MAP[$code],
                        self::MSG => ErrorCode::CODE_MAP[$code],
                    ],
                    Gm::SVN_UP, $user[self::INFO][self::USERNAME]
                );
                return ;
            }
            // 超时处理
            LogMark::getInstance()->markWarn(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                'search svn up get data timeout!',
                ['serverID' => $server_id, 'packetID' => PacketId::GM_SvnUP, self::TOKEN => $token]
            );
            // 返回失败
            (new Gm())->CheckAPIResult(
                ErrorCode::ERROR_GAME_SERVER_TIMEOUT,
                [
                    self::DATA => [],
                    self::INFO => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                    self::MSG => $user[self::INFO][self::USERNAME] . ErrorCode::CODE_MAP[ErrorCode::SEARCH_ERR],
                ],
                Gm::SVN_UP, $user[self::INFO][self::USERNAME]
            );
            return ;
        }

        // 解析数据
        $resData = base64_decode($data);
        $rankMsg = new GMSvnUP();
        $rankMsg->mergeFromString($resData);
        $code = $rankMsg->getCode();
        $result = $rankMsg->getExecMsg();

        if($code == ErrorCode::SUCCESS) {
            if(strpos($result, 'At revision') || strpos($result, 'Updated to revision') ) {
                $res[self::DATA] = [];
                $res[self::INFO] = ' 更新成功 '. '   '. $result;
                $res[self::MSG] = "更新成功";
            } else {
                $res[self::DATA] = [$result];
                $res[self::INFO] = ' 更新失败 ' . '   '. $result;
                $res[self::MSG] = ErrorCode::CODE_MAP[ErrorCode::ERROR_EXEC_FAILED];
            }
        } else {
            $res[self::DATA] = [$result];
            $res[self::INFO] = ' 更新失败 ' . '   '. $result;
            $res[self::MSG] = ErrorCode::CODE_MAP[ErrorCode::ERROR_EXEC_FAILED];
        }

        (new Gm())->CheckAPIResult(
            $code,
            $res,
            Gm::SVN_UP,
            $user[self::INFO][self::USERNAME],
        );
    }
}