<?php

namespace Admin\plugin\Exaster;

use APP\DI;
use APP\program\admin\Setting;
use APP\program\admin\user\Notification;
use APP\program\admin\Verify;
use APP\program\CuteDB;
use APP\program\Resource;
use LyApi\core\error\CustomException;
use LyApi\core\request\Request;
use LyApi\LyApi;
use LyApi\tools\Config;
use LyApi\tools\Template;
use Plugin\LyMaster\LyMaster;
use Plugin\LyMaster\plugin\Processor;

/**
 * 插件主程序
 */
class options
{

    // 插件基础设置
    const SIGN = "Exaster";                                   // 框架标志（与文件夹同名）
    const NAME = '系统拓展包';                                 // 插件名称（展示名）
    const VERSION = "V1";                                    // 插件当前版本号
    const PATH = LyApi . '/admin/plugin/' . self::SIGN;     // 插件根目录路径
    const USABLE = true;                                   // 插件是否可用

    // 插件自定义变量

    // 插件数据库列表
    public $tables = [];

    public $config = [];

    // 插件处理器对象
    private $processor;
    private $resources;

    // 本地 Cute 数据库处理程序
    private $_db;

    // 插件构造函数 
    public function __construct()
    {
        // 初始化官方插件处理器程序
        $this->processor = new Processor();
        $this->resources = new Resource();

        $this->_db = new CuteDB();

        // 初始化插件配置程序
        $this->config = [
            'debug' => true // 配置插件是否开启 Debug 模式
        ];
    }

    /**
     * 插件注册事件：当插件被 Admin系统 检测并加载时所调用参数
     * !(本事件仅一次！请完成部分安装操作)
     */
    public function onInstall()
    {
        // 当插件被安装(检测) 是执行，可完成 数据库初始化、信息验证...
        if (!is_dir(self::PATH . '/data')) {
            mkdir(self::PATH . '/data');
        }

        $this->processor->applyIndexPage(self::NAME);
        $this->_db->open(self::PATH . '/data/markdown');
        $this->_db->set('index-md', file_get_contents(LyApi . '/README.md'));
    }

    /**
     * 插件卸载事件：当插件被 Admin系统 卸载时所调用参数
     * !(本事件仅一次！请完成部分卸载操作)
     */
    public function onUninst()
    {
        // 当插件被删除时执行，可完成 数据库清理 等操作...
    }

    /**
     * 加载页面列表事件：当 Admin系统 管理页面列表被加载时执行
     * !(将注册页面程序写入本函数可有效减少资源消耗)
     */
    public function onLoadPages()
    {

        // 本函数将在 后台页面结构生成时被调用(请完成页面注册操作)

        $this->processor->title = self::NAME; // 建议不要修改
        $this->processor->icon = 'fa fa-support'; // 建议不要修改

        $this->_db->open(self::PATH . '/data/markdown');
        $this->processor->registerSP($this, [
            'title' => "基础配置", // 选项标题显示
            'icon' => 'fa fa-sun-o', // 选项图标显示 (fontawesome)
            'context' => Template::RenderTemplate(
                file_get_contents(self::PATH . '/view/admin/base.html'),
                [
                    'MarkDown' => $this->_db->get('index-md')
                ]
            )
        ]);
    }

    /**
     * 注册接口事件：当LyApi注册接口时执行
     * !(可将插件需要单独注册的VIEW或API程序写入本处)
     */
    public function onRegisterApi()
    {

        $this->processor->registerAPI(function ($type, $args, $backval) {
            header('Content-type: application/json');
            if ($backval['holder'][0] == 'markdown') {
                $which = Request::Get("which");
                if ($which == 'index') {
                    $context = Request::Post('context');

                    $cute = new CuteDB();
                    $cute->open($backval['path'] . '/data/markdown');

                    if ($context != '') {
                        $cute->set("index-md", $context, true);
                        return "OK";
                    } else {
                        $get = Request::Get('get');
                        if ($get == 'markdown') {
                            return $cute->get('index-md');
                        }
                    }
                }
            } else if ($backval['holder'][0] == 'feedback') {
                $message = Request::Get('message');
                if ($message != '') {
                    $this->_db->open(self::PATH . '/data/setting');
                    $status = $this->_db->get('feedback-api');
                    if ($status == '1' || $status === false) {
                        $nowuser = '匿名用户';
                        if (Verify::isLogin()) {
                            $nowuser = $_SESSION['nickname'];
                        }

                        Notification::sendMessage(
                            Template::RenderTemplate(
                                file_get_contents($backval['path'] . '/view/template/feedback.html'),
                                [
                                    'message' => $message,
                                    'user' => $nowuser
                                ]
                            ),
                            "EX反馈系统",
                            'info',
                            '收到反馈信息，快点开看看吧！',
                            "1"
                        );
                        return "OK";
                    } else {
                        return "DISABLED";
                    }
                }
            } else if ($backval['holder'][0] == 'setting') {
                $which = Request::Get('which');
                if ($which == 'feedback-api') {
                    $status = Request::Get('status');

                    if ($status != '') {
                        if ($status != '0' && $status != '1') {
                            $status = '1';
                        }

                        $this->_db->open(self::PATH . '/data/setting');
                        $this->_db->set('feedback-api', $status, true);
                        return $status;
                    } else {
                        $this->_db->open(self::PATH . '/data/setting');
                        return $this->_db->get('feedback-api');
                    }
                } else if ($which == 'now-idxp') {

                    if (Request::Get('do') == 'apply') {
                        $backval['processor']->applyIndexPage($backval['plugin_name']);
                        return "OK";
                    }

                    $cute = Setting::localDB('plugin');
                    $idx = $cute->get('index_control');
                    if ($idx != false) {
                        $db_connect = Setting::dbConnect();
                        if ($db_connect->has('plugin', ['sign' => $idx])) {
                            return $db_connect->get("plugin", 'name', ['sign' => $idx]);
                        }
                    }
                    return '框架本体';
                }
            } else if ($backval['holder'][0] == 'statip') {
                $do = Request::Get("do");

                if ($do == "set") {
                    $key = Request::Get("key");
                    $val = Request::Get("val");

                    $old = Config::getConfig("maps", "plugin/OCore", 'json');
                    $old[$key] = $val;

                    Config::setConfig("maps", $old, "cover", "plugin/OCore");
                } else if ($do == "del") {
                    $key = Request::Get("key");
                    $old = Config::getConfig("maps", "plugin/OCore", 'json');
                    unset($old[$key]);
                    Config::setConfig("maps", $old, "cover", "plugin/OCore");
                } else {
                    return Config::getConfig("maps", "plugin/OCore", 'json');
                }
            }
        }, [
            "type" => 'API',
            "path" => "exaster/api/*"
        ], [
            "path" => self::PATH,
            'processor' => $this->processor,
            'plugin_name' => self::NAME
        ]);
    }

    /**
     * 注册命令行指令事件：当LyMaster注册命令行插件指令时执行
     * !(可将插件需要单独注册的命令行指令程序写入本处)
     */
    public function onRegisterCmd()
    {
        // Cmder http://domain/admin/cmder 命令注册程序

        $this->processor->registerCommand(["cd"], function ($commands, $num) {
            return "Welcome Exaster !!";
        });

        $this->processor->registerCommand(["exa", "exaster"], function ($commands, $num) {
            // 参数: $commands 输入命令列表(为数组，使用空格分隔而成)
            // 参数: $num      $commands 数组长度
            if ($num > 1) {
                return "Hello " . $commands[1];
            } else {
                return "Hello Exaster";
            }
        });
    }

    /**
     * 主页面渲染事件：当主页面管控程序为本插件时
     * !(可将插件需要单独注册的命令行指令程序写入本处)
     */
    public function indexPage()
    {
        // 当 index 页面被此插件接管后，此函数将处理页面渲染

        if (!is_dir(self::PATH . '/data')) {
            mkdir(self::PATH . '/data');
        }

        $this->_db->open(self::PATH . '/data/markdown');

        $nickname = null;
        if (array_key_exists('nickname', $_SESSION)) {
            $nickname = $_SESSION['nickname'];
        }

        return Template::RenderTemplate(
            file_get_contents(self::PATH . '/view/index.html'),
            [
                'title' => Setting::getSetting('site_title'),
                'login' => $nickname
            ]
        );
    }

    // 回传 Processor (请勿删除本函数，否则出现运行错误！！)
    public function getProcessor()
    {
        return $this->processor;
    }
}
