<?php
namespace Gm\Controller;
/**
 * Class Server
 * Desc  分区管理类
 */

use Gm\Config\ErrorCode;
use Gm\Model\Servers;
use Gm\Model\Logs;
use Gm\Lib\Jwt;
use Gm\Comm\CommFunc;
use Gm\Config\Config;

class Server {
    use CommFunc;
    public function __construct() {

    }

    public const USER_LOG_TYPE = 2;
    public const ITEM_CFG_TYPE = 8;
    public const PLATFORM_TYPE = 9;

    // 区服列表
    public function List() {
        $search = $_GET['search'];
        $page = $_GET['page'];
        $limit = $_GET['limit'];

        $data = Servers::GetServerList($search, $page, $limit);
        $count = Servers::GetServerCount($search);
        $r = [
            "data" => $data,
            "count" => (int)$count
        ];
        $this->ReturnSucc(ErrorCode::SUCCESS, '查询成功',$r);
    }

    // 筛选区服
    public function GetServerList() {
        $platform = $_GET['id'];
        $data = Servers::GetServerListByPlatform($platform);
        $r = [
            "data" => $data,
        ];
        $this->ReturnSucc(ErrorCode::SUCCESS, '查询成功',$r);
    }

    // 新增和修改区服
    public function Save() {
        $params = json_decode(file_get_contents("php://input"));
        $platform_id = $params->platform_id;
        $id = $params->id;
        $name = $params->name;
        $server_id = $params->server_id;
        $game_url = $params->game_url;
        $item_id = $params->item_id;
        $config = $params->config;
        $desc = $params->desc;

        // 判断道具表状态是否为可用 status == 1
        if(self::CheckItemStatusIsHave($item_id)) {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "道具表请填写已更新道具的使用！");
            return ;
        }

        $user = Jwt::verifyToken();
        if(empty($id)) {
            // 判断区服是否存在
            if($this::serverIsHave($name)) {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "区服名称已经存在，请勿重复添加！");
                return ;
            }
            // 区服id不能重复
            if($this::serverIDIsHave($server_id)) {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "区服ID已经存在，请勿重复添加！");
                return ;
            }

            // 存储区服数据
            if(Servers::AddServer($name, $server_id, $game_url, $config, $desc, $platform_id)) {

                $log_info = $user['info']['username']. ' 增加了区服：'. $name;
                $log_data = [
                    'server_id' => $server_id,
                    'servername' => $name,
                    'game_url' => $game_url,
                    'config' => $config,
                    'desc'   => $desc,
                ];

                Logs::InsData(Server::USER_LOG_TYPE, $user['info']['username'], $log_info, json_encode($log_data));
                $this->ReturnSucc(ErrorCode::SUCCESS);
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "区服创建失败");
            }
        } else {
            $beforeServer = Servers::GetServerById($id);
            $user = Jwt::verifyToken()['info'];

            // 区服id不能重复
            if($this->editServerIDIsHave($id, $server_id)) {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "区服ID已经存在，请勿重复添加！");
                return ;
            }

            // 修改区服数据
            if(Servers::UpdateServer($id, $name, $server_id, $game_url, $config, $desc, $item_id, $platform_id)) {
                $update_info = '';

                if ($beforeServer['server_id'] != $server_id) {
                    $update_info .= '区服ID '. $beforeServer['server_id'] . ' 修改为 ' . $server_id . ';';
                }

                if ($beforeServer['name'] != $name) {
                    $update_info .= '区服名称 '. $beforeServer['name'] . ' 修改为 ' . $name . ';';
                }

                if ($beforeServer['game_url'] != $game_url) {
                    $update_info .= '游戏路径 '. $beforeServer['game_url'] . ' 修改为 ' . $game_url . ';';
                }

                if ($beforeServer['config'] != $config) {
                    $update_info .= '配置信息 '. $beforeServer['config'] . ' 修改为 ' . $config . ';';
                }

                if ($beforeServer['desc'] != $desc) {
                    $update_info .= '区服描述 '. $beforeServer['desc'] . ' 修改为 ' . $desc . ';';
                }

                if ($beforeServer['item_id'] != $item_id) {
                    $update_info .= '区服描述 '. $beforeServer['item_id'] . ' 修改为 ' . $item_id . ';';
                }

                if ($beforeServer['platform_id'] != $platform_id) {
                    $update_info .= '平台 '. $beforeServer['platform_id'] . ' 修改为 ' . $platform_id . ';';
                }

                if (empty($update_info)) {
                    $this->ReturnSucc(ErrorCode::SUCCESS, '未改变数据，修改无效');
                } else {
                    $log_info = $user['username']. ' 修改了 '. $update_info;
                    $log_data = [
                        'before' => $beforeServer,
                        'after'   => [
                            'server_id' => $server_id,
                            'servername' => $name,
                            'game_url' => $game_url,
                            'config' => $config,
                            'desc'     => $desc,
                        ]
                    ];

                    Logs::InsData(Server::USER_LOG_TYPE, $user['username'], $log_info, json_encode($log_data));
                    $this->ReturnSucc(ErrorCode::SUCCESS, '修改成功');
                }
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "区服更新失败");
            }
        }
    }

    public function serverIsHave($name) {
        $server = Servers::GetServerByName($name);
        if(empty($server)) {
            return false;
        }
        return true;
    }

    public function CheckItemStatusIsHave($id) {
        $item = Servers::CheckItemStatusIsHave($id);
        if(empty($item)) {
            return true;
        }
        return false;
    }

    public function serverIDIsHave($id) {
        $server = Servers::GetServerByServerId($id);
        if(empty($server)) {
            return false;
        }
        return true;
    }

    public function editServerIDIsHave($id, $sid) {
        $server = Servers::editServerIDIsHave($id, $sid);
        if(empty($server)) {
            return false;
        }
        return true;
    }

    public function Delete() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $user = Jwt::verifyToken()['info'];
        $server = Servers::GetServerById($id);
        $log_info = $user['username'] . ' 删除了区服 '. $server['name'];

        if(Servers::DeleteServerById($id)) {
            Logs::InsData(Server::USER_LOG_TYPE, $user['username'], $log_info, $log_info);
            $this->ReturnSucc(ErrorCode::SUCCESS, '删除成功');
        } else {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "删除区服失败");
        }
    }

    public function Exec() {
        // 查询出所有数据写入文件
        $server_info = Servers::GetServerInfo();
        if(empty($server_info)) {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "区服信息为空，不可部署。");
            return ;
        }

        $info = ['m_GameLogicListInfo'=>[],'END_OF_JSON'=>''];
        foreach($server_info as $v) {
            $arr = [
                'ID'           => (int)(substr($v['server_id'], -8) - substr($v['server_id'], -4))
                    / 10000,
                'Name'         => $v['name'],
                'GameLogicUrl' => $v['game_url'],
            ];
//            asort($arr);
            $info['m_GameLogicListInfo'][] = $arr;
        }
        // 排序
        $mgl = array_column($info['m_GameLogicListInfo'], 'ID');
        array_multisort($mgl, SORT_ASC, $info['m_GameLogicListInfo']);

        try {
            $filename = Config::WRITE_SERVER_LIST_DIR;
            $file = fopen($filename, 'wb');
            $content = json_encode($info, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            fwrite($file, $content);
            fclose($file);
            $this->ReturnSucc(ErrorCode::SUCCESS, '生成成功');

        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "操作失败, $msg");
        }

    }

    ////////////////////////////////////////////// 道具 ///////////////////////////////////////////////////////
    // 道具
    public function ItemList() {
        $page = $_GET['page'];
        $limit = $_GET['limit'];

        $data = Servers::GetItemCfgList($page, $limit);
        $count = Servers::GetItemCount();
        $r = [
            "data" => $data,
            "count" => (int)$count
        ];
        $this->ReturnSucc(ErrorCode::SUCCESS, '查询成功',$r);
    }

    // 新增和修改道具配置
    public function ItemSave() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $desc = $params->desc;
        $user = Jwt::verifyToken();
        if(empty($id)) {
            // 存储区服数据
            if(Servers::AddItemCfg($desc)) {

                $log_info = $user['info']['username']. ' 增加了道具配置：'. $desc;
                $log_data = [
                    'desc'   => $desc,
                ];
                Logs::InsData(Server::ITEM_CFG_TYPE, $user['info']['username'], $log_info, json_encode($log_data));
                $this->ReturnSucc(ErrorCode::SUCCESS);
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "道具配置创建失败");
            }
        } else {
            $beforeItemCfg = Servers::GetItemCfgById($id);
            $user = Jwt::verifyToken()['info'];

            // 修改区服数据
            if(Servers::UpdateItemCfg($id,$desc)) {
                $update_info = '';

                if ($beforeItemCfg['desc'] != $desc) {
                    $update_info .= '道具配置描述 '. $beforeItemCfg['desc'] . ' 修改为 ' . $desc . ';';
                }

                if (empty($update_info)) {
                    $this->ReturnSucc(ErrorCode::SUCCESS, '未改变数据，修改无效');
                } else {
                    $log_info = $user['username']. ' 修改了 '. $update_info;
                    $log_data = [
                        'before' => $beforeItemCfg,
                        'after'   => [
                            'desc'     => $desc,
                        ]
                    ];

                    Logs::InsData(Server::ITEM_CFG_TYPE, $user['username'], $log_info, json_encode($log_data));
                    $this->ReturnSucc(ErrorCode::SUCCESS, '修改成功');
                }
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "道具更新失败");
            }
        }
    }

    // 道具配置删除
    public function ItemCfgDelete() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $user = Jwt::verifyToken()['info'];
        $cfg = Servers::GetItemCfgById($id);

        // 判断是否有区服使用了此配置 如果使用则删除道具配置失败
        $info = Servers::GetServerUseItemCfg($id);
//        var_dump($info);
        $msg = '';
        if(!empty($info)) {
            foreach ($info as $item) {
                $msg .= $item['name'] . ';';
            }
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "有服务器 ". $msg .' 配置了此道具表! 请修改区服后再删除!');
            return ;
        }

        $log_info = $user['username'] . ' 删除了道具配置 '. $cfg['desc'];

        if(Servers::DeleteItemCfgById($id)) {
            Logs::InsData(Server::ITEM_CFG_TYPE, $user['username'], $log_info, $log_info);
            $this->ReturnSucc(ErrorCode::SUCCESS, '删除成功');
        } else {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "删除道具配置失败");
        }
    }

    public function ItemInsDB() {
        $file = $_FILES;
        $id = $_POST['id'];
        $user = Jwt::verifyToken()['info'];
        $cfg = Servers::GetItemCfgById($id);

        $temp_name = $file['file']['tmp_name'];
        $fp = fopen($temp_name, "r");
        $arr = [];
        while(!feof($fp)) {
            $str = fgets($fp);
            $line = explode("\t", $str);
            if(isset($line[16]) && $line[0] !== "ItemId") {
                $arr[] = [
                    'itemID' => trim($line[0]),
                    'itemName' => trim($line[18]),
                ];
            }
        }
        if(Servers::ItemInsDB($arr, $id)) {
            $log_info = $user['username'] . ' 更新了道具表 '. $cfg['desc'];
            Logs::InsData(Server::ITEM_CFG_TYPE, $user['username'], $log_info, $log_info);
            $this->ReturnSucc(ErrorCode::SUCCESS, '更新成功！');
        } else {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "更新失败！");
        }
    }

    ////////////////////////////////////////////// platform ///////////////////////////////////////////////////////
    // 道具
    public function PlatformList() {
        $page = $_GET['page'];
        $limit = $_GET['limit'];

        $data = Servers::GetPlatformList($page, $limit);
        $count = Servers::GetPlatformCount();
        $r = [
            "data" => $data,
            "count" => (int)$count
        ];
        $this->ReturnSucc(ErrorCode::SUCCESS, '查询成功',$r);
    }

    // 新增和修改道具配置
    public function PlatformSave() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $name = $params->name;
        $desc = $params->desc;
        $user = Jwt::verifyToken();
        if(empty($id)) {
            // 存储区服数据
            if(Servers::AddPlatform($name, $desc)) {
                $log_info = $user['info']['username']. ' 增加了平台：'. $name;
                $log_data = [
                    'name'   => $name,
                    'desc'   => $desc,
                ];
                Logs::InsData(Server::PLATFORM_TYPE, $user['info']['username'], $log_info, json_encode($log_data));
                $this->ReturnSucc(ErrorCode::SUCCESS);
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "平台信息创建失败");
            }
        } else {
            $beforeItemCfg = Servers::GetPlatformById($id);
            $user = Jwt::verifyToken()['info'];

            // 修改区服数据
            if(Servers::UpdatePlatform($id, $name, $desc)) {
                $update_info = '';

                if ($beforeItemCfg['desc'] != $desc) {
                    $update_info .= '平台描述 '. $beforeItemCfg['desc'] . ' 修改为 ' . $desc . ';';
                }

                if ($beforeItemCfg['name'] != $name) {
                    $update_info .= '平台名称 '. $beforeItemCfg['name'] . ' 修改为 ' . $name . ';';
                }

                if (empty($update_info)) {
                    $this->ReturnSucc(ErrorCode::SUCCESS, '未改变数据，修改无效');
                } else {
                    $log_info = $user['username']. ' 修改了 '. $update_info;
                    $log_data = [
                        'before' => $beforeItemCfg,
                        'after'   => [
                            'name'     => $name,
                            'desc'     => $desc,
                        ]
                    ];

                    Logs::InsData(Server::PLATFORM_TYPE, $user['username'], $log_info, json_encode($log_data));
                    $this->ReturnSucc(ErrorCode::SUCCESS, '修改成功');
                }
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "平台更新失败");
            }
        }
    }

    // 道具配置删除
    public function DelPlatform() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $user = Jwt::verifyToken()['info'];
        $cfg = Servers::GetPlatformById($id);

        // 判断是否有区服使用了此配置 如果使用则删除道具配置失败
        $info = Servers::GetServerUsePlatform($id);
//        var_dump($info);
        $msg = '';
        if(!empty($info)) {
            foreach ($info as $item) {
                $msg .= $item['name'] . ';';
            }
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "有服务器 ". $msg .' 配置了此渠道! 请修改服务器渠道后再删除!');
            return ;
        }

        $log_info = $user['username'] . ' 删除了道具配置 '. $cfg['name'];

        if(Servers::DeletePlatformById($id)) {
            Logs::InsData(Server::ITEM_CFG_TYPE, $user['username'], $log_info, $log_info);
            $this->ReturnSucc(ErrorCode::SUCCESS, '删除成功');
        } else {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "删除平台失败");
        }
    }
}