<?php

namespace APP\api\admin\api;

use APP\DI;
use APP\program\admin\Apis as AdminApis;
use APP\program\admin\Setting;
use APP\program\admin\Verify;
use LyApi\core\classify\API;
use LyApi\core\request\Request;
use Medoo\Medoo;
use PDOException;
use Plugin\LyMaster\LyMaster;

class dbs extends API
{

    // 取得当前的数据库总数
    public function count($type, $args)
    {
        if (!Verify::isLogin()) {
            return ['#code' => 401, '#msg' => '账号无权限'];
        }

        $db_connect = Setting::dbConnect();

        return $db_connect->count('database');
    }

    public function lists($type, $args)
    {
        if (!Verify::isLogin()) {
            return ['#code' => 401, '#msg' => '账号无权限'];
        }

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

        $LyMaster = new LyMaster();

        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('database', '*', $where);

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

                if ($data[$key]['status'] == '1') {
                    $data[$key]['status'] = '正常';
                } else if ($data[$key]['status'] == '2') {
                    $data[$key]['status'] = '异常';
                } else {
                    $data[$key]['status'] = '待检测';
                }

                if (!Verify::authCheck('dodb')) {
                    $data[$key]['password'] = '权限不足，无法显示';
                }
            }
        }

        return $data;
    }

    // 新建数据库
    public function newdb()
    {
        if (Verify::isLogin()) {
            if (Verify::authCheck('dodb')) {

                $host = Request::Request('host');
                $port = Request::Request('port');
                $dbname = Request::Request('dbname');
                $username = Request::Request('username');
                $password = Request::Request('password');
                $dbtype = Request::Request('dbtype');
                $charset = Request::Request('charset');
                $status = Request::Request('status');

                if ($host != '' && $dbname != '' && $username != '' && $password != '') {
                    if ($port == '') {
                        $port = 3306;
                    }
                    if ($charset == '') {
                        $charset = 'utf8';
                    }
                    $dbtype = 'mysql';
                    if ($status == '') {
                        $status = 3;
                    }

                    $db_connect = Setting::dbConnect();

                    $db_connect->insert('database', [
                        'name' => $dbname,
                        'type' => $dbtype,
                        'host' => $host,
                        'port' => $port,
                        'username' => $username,
                        'password' => $password,
                        'charset' => $charset,
                        'status' => $status
                    ]);

                    return 'OK';
                } else {
                    return ['#code' => '400', '#msg' => '参数不完整'];
                }
            } else {
                return ['#code' => '401', '#msg' => '账号无权限'];
            }
        } else {
            return ['#code' => '401', '#msg' => '账号未登录'];
        }
    }

    // 删除数据库
    public function deldb()
    {
        if (Verify::isLogin()) {
            if (Verify::authCheck('dodb')) {
                if (Request::Request('db') != '' && Request::Request('pwd')) {
                    $db_connect = Setting::dbConnect();
                    $secret = $db_connect->get('users', 'secret', ['id' => $_SESSION['userid']]);
                    if ($db_connect->has('users', ['password' => Verify::encryptPwd(Request::Request('pwd'), $secret)])) {
                        if ($db_connect->has('database', ['id' => Request::Request('db')])) {
                            $db_connect->delete('database', ['id' => Request::Request('db')]);
                            return 'OK';
                        } else {
                            return ['#code' => '404', '#msg' => '数据不存在'];
                        }
                    } else {
                        return ['#code' => '401', '#msg' => '密码验证错误'];
                    }
                } else {
                    return ['#code' => '400', '#msg' => '参数不完整'];
                }
            } else {
                return ['#code' => '401', '#msg' => '账号无权限'];
            }
        } else {
            return ['#code' => '401', '#msg' => '账号未登录'];
        }
    }

    // 检测数据库连接（本接口建议定期调用）
    public function check()
    {

        $range = Request::Request('range');
        $operate = Request::Request('operate');

        if ($range == '') {
            $range = 'all';
        }

        if ($operate == '') {
            $operate = 'update';
        }

        if ($range == 'external') {
            $host = Request::Request('host');
            $port = Request::Request('port');
            $dbname = Request::Request('dbname');
            $username = Request::Request('username');
            $password = Request::Request('password');
            $dbtype = Request::Request('dbtype');
            $charset = Request::Request('charset');
            if ($host != '' && $dbname != '' && $username != '' && $password != '') {

                if ($port == '') {
                    $port = 3306;
                }

                if ($charset == '') {
                    $charset = 'utf8';
                }

                $dbtype = 'mysql';

                try {
                    $test_connect = new Medoo([
                        'database_type' => $dbtype,
                        'database_name' => $dbname,
                        'server' => $host,
                        'username' => $username,
                        'password' => $password,
                        'charset' => $charset,
                        'port' => $port
                    ]);
                } catch (PDOException $e) {
                    return ['#code' => '400', '#msg' => '连接测试失败'];
                }

                return 'OK';
            } else {
                return ['#code' => '400', '#msg' => '参数不完整'];
            }
        } else if ($range == 'all') {

            $db_connect = Setting::dbConnect();
            $connects = $db_connect->select('database', '*');

            $result = [
                'success' => 0,
                'failure' => 0
            ];

            foreach ($connects as $key => $connect) {
                $ok = 1;
                try {
                    $test_connect = new Medoo([
                        'database_type' => $connect['type'],
                        'database_name' => $connect['name'],
                        'server' => $connect['host'],
                        'username' => $connect['username'],
                        'password' => $connect['password'],
                        'charset' => $connect['charset'],
                        'port' => $connect['port']
                    ]);
                } catch (PDOException $e) {
                    $ok = 2;
                }

                if ($ok == 1) {
                    $result['success'] += 1;
                } else {
                    $result['failure'] += 1;
                }

                // 是否更新数据
                if ($operate == 'update') {
                    $db_connect->update('database', [
                        'status' => $ok
                    ], [
                        'id' => $connect['id']
                    ]);
                }
            }
            return $result;
        }
        return ['#code' => '400', '#msg' => '未知的操作'];
    }
}
