<?php
namespace Gm\Controller;
use Framework\Log\LogMark;
use Game\Protobuf\MGNoticeCancel;
use Game\Protobuf\PacketId;
use Gm\Config\Config;
use Gm\Config\ErrorCode;
use Gm\Core\RedisLib;
use Gm\Lib\Jwt;
use Gm\Model\Gms;
use Gm\Model\Logs;
use Gm\Model\Notices;
use Gm\Comm\CommFunc;
use Gm\Model\Servers;
use Gm\Controller\Gm;
use http\Header;

/**
 * Class Notice
 * 公告
 */

class Notice {

    use CommFunc;

    public const LAMP_TIMER_KEY = "lampTimer";

    public function Save() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $title = $params->title;
        $title_short = $params->title_short;
        $time_send = $params->time_send;
        $time_end = $params->time_end;
        $sort = $params->sort;
        $icon = $params->icon;
        $status = $params->status;
        $content = $params->content;
        $content_image = $params->content_image;

        $user = Jwt::verifyToken();
        $user_name = $user['info']['username'];

        if(empty($id)) {
            // 存储公告数据
            if(Notices::AddNotice($title, $title_short, $time_send, $time_end, $sort, $status, $content,
                $content_image, $icon)) {
                $log_info = $user['info']['username']. ' 增加了公告：'. $title;
                $log_data = [
                    'title' => $title,
                ];
                Logs::InsData(Gm::NOTICE_LOG, $user_name, $log_info, json_encode($log_data));
                $this->ReturnSucc(ErrorCode::SUCCESS);
            } else {
                $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "公告创建失败");
            }
        } else {
            $beforeNotice = Notices::GetNoticeById($id);
            $user = Jwt::verifyToken()['info'];

            // 修改公告数据
            if(Notices::UpdateNotice($id, $title, $title_short, $time_send, $time_end, $sort, $status, $content,
                $content_image, $icon)) {
                $update_info = '';

                if ($beforeNotice['title'] != $title) {
                    $update_info .= ' 标题 '. $beforeNotice['title'] . ' 修改为 ' . $title . ';';
                }

                if ($beforeNotice['title_short'] != $title_short) {
                    $update_info .= ' 短标题 '. $beforeNotice['title_short'] . ' 修改为 ' . $title_short . ';';
                }

                if ($beforeNotice['time_send'] != $time_send) {
                    $update_info .= ' 开始时间 '. date('Y-m-d H:i:s', $beforeNotice['time_send'])
                        . ' 修改为 ' . date('Y-m-d H:i:s', $time_send) . ';';
                }

                if ($beforeNotice['time_end'] != $time_end) {
                    $update_info .= ' 结束时间 '. date('Y-m-d H:i:s', $beforeNotice['time_end'])
                        . ' 修改为 ' . date('Y-m-d H:i:s', $time_end) . ';';
                }

                if ($beforeNotice['sort'] != $sort) {
                    $update_info .= ' 排序 '. $beforeNotice['sort'] . ' 修改为 ' . $sort . ';';
                }
                if ($beforeNotice['icon'] != $icon) {
                    $update_info .= ' icon '. $beforeNotice['icon'] . ' 修改为 ' . $icon . ';';
                }
                if ($beforeNotice['content_image'] != $content_image) {
                    $update_info .= ' 内容图 '. $beforeNotice['content_image'] . ' 修改为 ' . $content_image . ';';
                }

                if ($beforeNotice['content'] != $content) {
                    $update_info .= ' 内容 '. $beforeNotice['content'] . ' 修改为 ' . $content . ';';
                }

                if (empty($update_info)) {
                    $this->ReturnSucc(ErrorCode::SUCCESS, '未改变数据，修改无效');
                } else {
                    $log_info = $user['username']. ' 修改了公告： ' . $beforeNotice['title'] . $update_info;
                    $log_data = [
                        'before' => $beforeNotice,
                        'after'   => [
                            'title' => $title,
                            'title_short' => $title_short,
                            'time_send' => $time_send,
                            'time_end' => $time_end,
                            'content' => $content,
                        ]
                    ];

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

    public function List() {
        $search = $_GET['search'];
        $page = $_GET['page'];
        $limit = $_GET['limit'];
        $time_start = $_GET['time_start'];
        $time_end = $_GET['time_end'];
        $status = $_GET['status'];
        $data = Notices::GetNoticeList($search, $page, $limit, $time_start, $time_end, $status);
        $dataRes = [];
        foreach ($data as $item) {
            if(time() < $item['time_send']) {
                $status = 1; // 未开始
            } elseif (time() > $item['time_end']) {
                $status = 3; // 已过期
            } else {
                $status = 2; // 展示中
            }
            $dataRes[] = [
                'id' => $item['id'],
                'title' => $item['title'],
                'title_short' => $item['title_short'],
                'time_send' => date("Y-m-d H:i:s", $item['time_send']),
                'time_end' => date("Y-m-d H:i:s", $item['time_end']),
                'time_create' => date("Y-m-d H:i:s", $item['time_create']),
                'time_s' => $item['time_send'],
                'time_e' => $item['time_end'],
                'sort' => $item['sort'],
                'icon' => $item['icon'],
                'content' => $item['content'],
                'content_image' => $item['content_image'],
                'status' => $status,
            ];
        }

        $count = Notices::GetCount($search);
        $r = [
            "data" => $dataRes,
            "count" => (int)$count
        ];
        // 处理参数
        $this->ReturnSucc(ErrorCode::SUCCESS, '查询成功',$r);
    }

    public function Delete() {
        $params = json_decode(file_get_contents("php://input"));
        $id = $params->id;
        $user = Jwt::verifyToken()['info'];
        $notice = Notices::GetNoticeById($id);
        $log_info = $user['username'] . ' 删除了公告：'. $notice['title'];

        if(Notices::DeleteNoticeById($id)) {
            Logs::InsData(Gm::NOTICE_LOG, $user['username'], $log_info, $log_info);
            $this->ReturnSucc(ErrorCode::SUCCESS, '删除成功');
        } else {
            $this->ReturnErr(ErrorCode::ERROR_GM_INTERNAL, "删除失败");
        }
    }

    public function Build() {
        // 获取公告列表
        $data = Notices::BuildNoticeList();
        $str = "";
        if(!empty($data)) {
            $str .= "[";
            foreach($data as $item) {
                $str .= "{";
                $str .= "id: ". $item['id'] . ',';
                $str .= "title: '". $item['title'] . "',";
                $str .= "title_min: '". $item['title_short'] . "',";
                $str .= "time_send: ". $item['time_send'] . ',';
                $str .= "time_end: ". $item['time_end'] . ',';
                $str .= "time_s: `". date("Y-m-d H:i:s", $item['time_send']) . '`,';
                $str .= "time_e: `". date("Y-m-d H:i:s", $item['time_end']) . '`,';
                $str .= "icon: ". $item['icon'] . ',';
                $str .= "content: `".$item['content']  . "`,";
                $str .= "content_image: '". $item['content_image'] . "',";
                $str .= "},";
            }
            $str .= "]";
        }

        // 行高特殊处理
        $str_exe = str_replace('<p style="', '<p style="margin: 0.6% 0 ;', $str);

        // 读取html文件内容
        $template_dir = Config::NOTICE_TEMPLATE_DIR;
        $new_file = Config::NOTICE_LIST_DIR;
        $fp = fopen($template_dir, 'rb');
        $file = fopen($new_file, 'wb');
        while(!feof($fp)) {
            $buffer = fgets($fp, 4096);
            $buffer = str_replace('replace', $str_exe, $buffer);
            fwrite($file, $buffer);
        }

        fclose($file);
        fclose($fp);

        $this->ReturnSucc(ErrorCode::SUCCESS, '生成成功！');
    }
}