<?php

namespace APP\api\admin;

use APP\program\admin\Plugin as AdminPlugin;
use APP\program\admin\Setting;
use APP\program\admin\Verify;
use APP\program\Resource;
use LyApi\core\classify\API as ClassifyAPI;
use LyApi\core\design\Register;
use LyApi\core\error\CustomException;
use LyApi\core\request\Request;
use LyApi\tools\Template;

class plugin extends ClassifyAPI
{
    // 页面加载程序 (转发自住程序)
    public function __page($type, $args)
    {

        if ($type != 'TRANS') {
            header("Content-type:text/html");
            throw new CustomException("<h1>非法的访问入口</h1>", 200);
        }

        $to = 'manage';
        $file = '';
        $res = new Resource();
        $vars = [
            'domain' => $res->Domain(),
            'resource' => $res->Domain() . '/resource/admin'
        ];

        if (array_key_exists('to', $args)) {
            $to = $args['to'];
        }

        if ($to == 'manage') {
            $file = 'index.html';
        }


        $html = file_get_contents(LyApi . '/app/view/html/admin/plugin/' . $file);
        return Template::RenderTemplate($html, $vars);
    }

    public function pages()
    {
        header("Content-type:text/html");

        $pmanager = Register::Get('PManager');
        $pmanager->pluginPages();

        $pid = Request::Get('pid');
        $title = Request::Get('title');
        if ($pid != '' && $title != '') {
            $pdata = Register::Get('PageContext');
            if ($pdata != '') {
                if (array_key_exists($pid, $pdata)) {
                    throw new CustomException($pdata[$pid][$title], 200);
                }
            }
        }
        throw new CustomException(file_get_contents(LyApi . '/app/view/html/admin/page/404.html'), 200);
    }

    // 插件列表
    public function lists($type, $args)
    {
        if (!Verify::isLogin()) {
            return ['#code' => 401, '#msg' => '账号无权限...'];
        } else if (!Verify::authCheck("doplugin")) {
            return ['#code' => 401, '#msg' => '账号无权限...'];
        }

        if ($type == "API") {
            $limit = Request::Request('limit');
            $page = Request::Request('page');
        } else {
            $limit = $args['limit'];
            $page = $args['page'];
        }

        if ($limit == '' || $page == '') {
            $limit = 15;
            $page = 1;
        }

        $db_connect = Setting::dbConnect();

        // 取得读取的数据前后
        if ($page > 1) {
            $page -= 1;
            $start_num = ($page * $limit);
        } else {
            $start_num = 0;
        }

        $end_num = $start_num + $limit;

        $where = [
            'LIMIT' => [$start_num, $limit]
        ];

        // 搜索数据，如不存在则正常索引
        if (Request::Request('search') != '') {
            $where['name'] = Request::Request('search');
        }

        $data = $db_connect->select('plugin', '*', $where);

        if (count($data) == 0) {
            // 接口数据为空，无法正常读取
            return ['#msg' => '无任何已加载插件...'];
        } else {
            // // 预处理一些数据
            foreach ($data as $key => $value) {

                if ($data[$key]['status'] == '1') {
                    $data[$key]['status'] = '已开启';
                } else {
                    $data[$key]['status'] = '已关闭';
                }

                $config = unserialize($data[$key]['config']);
                if (array_key_exists('debug', $config)) {
                    if ($config['debug']) {
                        $data[$key]['version'] .= ' <span style="color:red;">「开发版」</span>';
                    }
                }
            }
        }

        return $data;
    }

    // 识别插件程序
    public function replugin()
    {

        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '账号未登录'];
        } else if (!Verify::authCheck('doplugin')) {
            return ['#code' => '401', '#msg' => '账号无权限'];
        }

        $adp = new AdminPlugin();
        return $adp->reloadPlugin();
    }

    public function reset()
    {

        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '账号未登录'];
        } else if (!Verify::authCheck('doplugin')) {
            return ['#code' => '401', '#msg' => '账号无权限'];
        }

        $pid = Request::Get('pid');
        if ($pid != '') {
            $adp = new AdminPlugin();
            if ($adp->reloadSet($pid)) {
                return 'OK';
            }
            return ['#code' => '400', '#msg' => '未知的ID号'];
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }


    // 完成插件 [打开 \ 关闭] 操作
    public function cstatus($type, $args)
    {

        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '账号未登录'];
        } else if (!Verify::authCheck('doplugin')) {
            return ['#code' => '401', '#msg' => '账号无权限'];
        }

        $pid = Request::Get('pid');
        if ($pid != '') {
            $db_connect = Setting::dbConnect();
            if ($db_connect->has('plugin', ['id' => $pid])) {
                $now_status = $db_connect->get('plugin', 'status', ['id' => $pid]);
                if ($now_status == 0) {
                    $new_status = 1;
                } else {
                    $new_status = 0;
                }
                $db_connect->update('plugin', [
                    'status' => $new_status
                ], ['id' => $pid]);

                if ($new_status == 0) {
                    return '关闭';
                } else {
                    return '开启';
                }
            }
            return ['#code' => '400', '#msg' => '数据不存在'];
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }

    // 删除数据操作
    public function delete()
    {

        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '账号未登录'];
        } else if (!Verify::authCheck('doplugin')) {
            return ['#code' => '401', '#msg' => '账号无权限'];
        }

        $pid = Request::Post('pid');
        $pwd = Request::Post('pwd');
        if ($pid != '' && $pwd != '') {
            $db_connect = Setting::dbConnect();
            if ($db_connect->has('plugin', ['id' => $pid])) {

                $secret = $db_connect->get('users', 'secret', ['id' => $_SESSION['userid']]);
                $passwd = Verify::encryptPwd($pwd, $secret);
                if ($db_connect->has('users', ['id' => $_SESSION['userid'], 'password' => $passwd])) {
                    $db_connect->delete('plugin', ['id' => $pid]);
                    return "OK";
                } else {
                    return ['#code' => '401', '#msg' => '密码验证失败'];
                }
            }
            return ['#code' => '400', '#msg' => '数据不存在'];
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }
}
