<?php

namespace APP\api\admin\api;

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

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

        $db_connect = Setting::dbConnect();

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

    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) {
            $start_num = ($page * $limit) - 1;
        } else {
            $start_num = 0;
        }

        $end_num = $start_num + $limit;

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

        // 搜索数据，如不存在则正常索引
        if (Request::Request('search') != '') {
            $cond = explode('|', Request::Request('search'));
            if (count($cond) == 1) {
                $where['apiname'] = $cond[0];
            } else {
                if ($cond[0] != '') {
                    $where['apiname'] = $cond[0];
                    $where['apipath'] = $cond[1];
                } else {
                    $where['apipath'] = $cond[1];
                }
            }
        }

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

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


                $apinsp = str_replace('\\','/',$data[$key]['apipath']);

                // 查找目标对象是否存在
                $class_path = LyApi . '/app/api/' . $apinsp . '.php';
                if (!file_exists($class_path)) {
                    $data[$key]['apistatus'] = '3';
                }

                if ($data[$key]['apitype'] == '1') {
                    $data[$key]['apitype'] = '接口程序';
                } else {
                    $data[$key]['apitype'] = '视图程序';
                }

                if ($data[$key]['apistatus'] == '1') {
                    $data[$key]['apistatus'] = '正常';
                } elseif ($data[$key]['apistatus'] == '2') {
                    $data[$key]['apistatus'] = '停用';
                } else {
                    $data[$key]['apistatus'] = '异常';
                }

                $data[$key]['tduse'] = $LyMaster->visitState("APP\\api\\" . $data[$key]['apipath']);
            }
        }

        return $data;
    }

    // 取得 接口列表
    public function trees()
    {
        return AdminApis::apiTree();
    }

    // 取得对应的模板列表
    public function template()
    {
        $do = Request::Request('do');
        if ($do == '') {
            $do = 'get';
        }

        if ($do == 'get') {
            $where = [];
            if (Request::Get('id') == '') {
                $type = Request::Request('type');

                if ($type == 'api') {
                    $where = ['type' => 1];
                } elseif ($type == 'view') {
                    $where = ['type' => 2];
                }
            } else {
                $where['id'] = Request::Get('id');
            }

            $db_connect = Setting::dbConnect();
            return $db_connect->select('api_templates', '*', $where);
        } else if ($do == 'new') {
            if (Verify::isLogin()) {
                if (Verify::authCheck('doapi')) {

                    // 检查参数完整程度
                    $tname = Request::Post('tname');
                    $ttype = Request::Post('ttype');
                    $tsave = Request::Post('tsave');
                    $tpath = Request::Post('tpath');

                    if ($tname != '' && $ttype != '' && $tsave != '' && $tpath != '') {
                        if ($tsave == 1) {
                            if (!file_exists(LyApi . '/admin/template/' . $tpath)) {
                                return ['#code' => '400', '#msg' => '文件不存在'];
                            }
                        }

                        $db_connect = Setting::dbConnect();
                        if (!$db_connect->has('api_templates', ['name' => $tname, 'type' => $ttype])) {
                            $result = $db_connect->insert('api_templates', [
                                'name' => $tname,
                                'type' => $ttype,
                                'savetype' => $tsave,
                                'path' => $tpath
                            ]);

                            if ($result->errorCode() == '00000') {
                                return 'OK';
                            } else {
                                return ['#code' => '500', '#msg' => '更新数据失败'];
                            }
                        } else {
                            return ['#msg' => '名称已占用'];
                        }
                    }
                    return ['#code' => '400', '#msg' => '参数不完整'];
                } else {
                    return ['#code' => '401', '#msg' => '账号无权限'];
                }
            } else {
                return ['#code' => '401', '#msg' => '账号未登录'];
            }
        } else if ($do == 'del') {
            // 删除一个 Template 的操作

            if (Verify::isLogin()) {
                if (Verify::authCheck('doapi')) {
                    $id = Request::Request('tpl');
                    if ($id != '') {
                        $db_connect = Setting::dbConnect();
                        $db_connect->delete('api_templates', ['id' => $id]);
                        return 'OK';
                    }
                    return ['#code' => '400', '#msg' => '参数不完整'];
                } else {
                    return ['#code' => '401', '#msg' => '账号无权限'];
                }
            } else {
                return ['#code' => '401', '#msg' => '账号未登录'];
            }
        }
        return ['#code' => '400', '#msg' => '未知操作'];
    }

    // 创建新的接口
    public function addapi($type, $args)
    {
        // 预留内部启动方法
        if ($type == 'API') {

            $apiname = Request::Post('apiname');
            $apipath = Request::Post('apipath');
            $apitype = Request::Post('apitype');
            $template = Request::Post('template');
            $apiabout = Request::Post('apiabout');
        } else {
            return ['#msg' => '暂不支持内部启动'];
        }

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

        if ($apiname != '' && $apipath != '' && $apitype != '' && $template != '') {

            if ($apiabout == '') {
                $apiabout = '本接口还未设置任何备注';
            }

            $db_connect = Setting::dbConnect();

            // 检查是否用重复数据
            if (!$db_connect->has('apis', ['apiname' => $apiname, 'apiclass' => $apipath])) {

                // 取得新接口类型
                if ($apitype == 'api') {
                    $apitype = '1';
                } else {
                    $apitype = '2';
                }


                // 目标模板检测
                $template_context = '';
                // $template_file = LyApi . '/admin/template/' . $template . '.php';
                // if (file_exists($template_file)) {
                //     $template_context = file_get_contents($template_file);
                // } else {
                //     return ['#code' => '500', '#msg' => '安装模板不存在'];
                // }

                if($template != '使用生成器模板代码'){
                    $tpl_data = $db_connect->get('api_templates', ['savetype', 'path'], ['id' => $template]);
                    if ($tpl_data !== false) {
                        if ($tpl_data['savetype'] == 1) {
                            $template_file = LyApi . '/admin/template/' . $tpl_data['path'];
                            if (!file_exists($template_file)) {
                                return ['#code' => '500', '#msg' => '安装模板不存在'];
                            } else {
                                $template_context = file_get_contents($template_file);
                            }
                        } else {
                            // 云端模板: 测试是否访问正常
                            $request = DI::Unirest();
                            $response = $request::get($tpl_data['path']);
                            if ($response->code != '200') {
                                return ['#code' => '500', '#msg' => '安装模板不存在'];
                            } else {
                                $template_context = $response->body;
                            }
                        }
                    } else {
                        return ['#code' => '500', '#msg' => '安装模板不存在'];
                    }
                }else{
                    // 使用生成器当前代码创建
                    $component = new Component();
                    if($apitype == 'view'){
                        $ctype = "VIEW";
                    }else{
                        $ctype = "API";
                    }
                    $template_context = $component->getTpl($ctype);
                }

                // 替换部分内容
                $namespace = explode('\\', $apipath);
                $class = array_pop($namespace);

                if (count($namespace) == 0) {
                    $namespace = 'APP\\api';
                    $class = $apipath;
                } else {
                    $namespace = implode('\\', $namespace);
                    $namespace = 'APP\\api\\' . $namespace;
                }

                // 分割目标命名空间
                $apinsp = explode('\\', $apipath);
                array_pop($apinsp);
                $apinsp = implode('/', $apinsp);
                if (!is_dir(LyApi . '/app/api/' . $apinsp)) {
                    mkdir(LyApi . '/app/api/' . $apinsp, 0777, true);
                }

                $template_context = str_replace('__namespace', $namespace, $template_context);
                $template_context = str_replace('__class', $class, $template_context);

                // 写入接口类容
                $fwrite = file_put_contents(LyApi . '/app/api/' . $apinsp . '/' . $class . '.php', $template_context);

                if ($fwrite > 0) {
                    // 先将接口数据写入数据库
                    $result = $db_connect->insert('apis', [
                        'apiname' => $apiname,
                        'apipath' => $apipath,
                        'apiabout' => $apiabout,
                        'apisecure' => '9',
                        'apitype' => $apitype,
                        'apistatus' => '1',
                        'finaledit' => time()
                    ]);
                    if ($result->errorCode() == '00000') {
                        return 'OK';
                    } else {
                        return ['#code' => '500', '#msg' => '数据新增失败'];
                    }
                } else {
                    return ['#code' => '500', '#msg' => '数据新增失败'];
                }
            } else {
                return ['#msg' => '接口信息已存在'];
            }
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }

    // 删除接口操作
    public function delapi($type, $args)
    {
        // 预留内部启动方法
        if ($type == 'API') {

            $id = Request::Post('id');
            $apiname = Request::Post('apiname');
            $password = Request::Post('password');
        } else {
            return ['#msg' => '暂不支持内部启动'];
        }

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

        // 判断参数是否齐全
        if ($id != '' && $apiname != '' && $password != '') {
            $db_connect = Setting::dbConnect();

            $secret = $db_connect->get('users', 'secret', ['id' => $_SESSION['userid']]);
            $password = Verify::encryptPwd($password, $secret);

            if ($db_connect->has('users', ['id' => $_SESSION['userid'], 'password' => $password])) {
                // 判定接口是否已存在
                if (!$db_connect->has('apis', ['id' => $id, 'apiname' => $apiname])) {
                    return ['#msg' => '接口不存在'];
                }
                $apipath = $db_connect->get('apis', 'apipath', ['id' => $id]);

                // 如果文件存在则删除文件

                $apipath = str_replace('\\','/',$apipath);

                if (LyApi . '/app/api/' . $apipath . '.php') {
                    unlink(LyApi . '/app/api/' . $apipath . '.php');
                }

                $db_connect->delete('apis', [
                    'id' => $id,
                    'apiname' => $apiname
                ]);
                return 'OK';
            } else {
                return ['#code' => '400', '#msg' => '密码验证失败'];
            }
        } else {
            return ['#code' => '400', '#msg' => '参数不完整'];
        }
    }
}
