<?php

namespace APP\api\admin\api;

use APP\program\admin\Component;
use APP\program\admin\Setting;
use APP\program\admin\Verify;
use APP\program\system\System;
use LyApi\core\classify\API;
use LyApi\core\error\CustomException;
use LyApi\tools\DString;

class maker extends API
{

    private $comp_rpath;

    public function __construct()
    {
        $this->comp_rpath = LyApi . '/admin/components/';
    }

    // 取得 components
    public function component($type, $args)
    {
        $component = new Component();
        if (array_key_exists("do", $args)) {
            if ($args['do'] == 'list') {
                $json = file_get_contents(LyApi . '/admin/components/comp.json');
                $json = json_decode($json, true);

                if (array_key_exists('item', $args)) {
                    $item = $args['item'];
                } else {
                    $item = 'register';
                }

                if (array_key_exists($item, $json)) {
                    $data = $json[$item];
                    $result = [];
                    if ($item == 'register') {
                        foreach ($data as $key => $value) {
                            if ($component->checkComp($value['path'])) {
                                array_push($result, $value);
                            }
                        }
                    }
                    return $result;
                }
                return '';
            } else if ($args['do'] == 'form') {
                if (array_key_exists("name", $args)) {
                    // 取得表单列表
                    return $component->getForms($component->getPath($args['name']));
                }
                return [];
            } else if ($args['do'] == 'secc') {

                header('content-type:text/html;charset=utf-8');

                if (array_key_exists("name", $args)) {

                    $data = $args;
                    unset($data['do']);
                    unset($data['name']);

                    $result = $component->getConsole($component->getPath($args['name']), $data);
                    if ($result == false) {
                        throw new CustomException('no-console', 200);
                    } else {
                        throw new CustomException($result, 200);
                    }
                }
                throw new CustomException('no-console', 200);
            }
            return ['#code' => '400', '#msg' => '参数不完整'];
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }

    // Components 最终处理程序
    public function managers($type, $args)
    {

        if (array_key_exists('comp', $args) && array_key_exists('data', $args)) {

            // 处理 Component 的数据操作
            $component = new Component();
            if ($component->checkComp($args['comp'])) {
                $path = $this->comp_rpath . $args['comp'] . '/';
            } else if ($component->checkComp($component->getPath($args['comp']))) {
                $args['comp'] = $component->getPath($args['comp']);
                $path = $this->comp_rpath . $args['comp'] . '/';
            } else {
                return ['#code' => '400', '#msg' => '组件不存在'];
            }

            // 取得目标处理程序位置
            if (is_file($path . 'setting.json')) {
                $json = json_decode(file_get_contents($path . 'setting.json'), true);

                if (gettype($json['manager']) == 'string') {
                    // 处理对应生成器代码
                    $path = explode('.', $json['manager']);
                    if (count($path) >= 2) {

                        $func = array_pop($path);
                        $class = array_pop($path);

                        if (count($path) > 1) {
                            $path = './';
                        } else {
                            $path = implode('/', $path) . '/';
                        }

                        // 取得目标返回值

                        $args['comp'] = str_replace("./", '', $args['comp']);

                        $namespace = 'Admin\\components\\' . $args['comp'] . '\\' . $class;
                        if (class_exists($namespace)) {
                            $obj = new $namespace();
                            $response = $obj->$func(json_decode($args['data'], true));
                            if (gettype($response) == 'array') {
                                if (
                                    array_key_exists('imports', $response) &&
                                    array_key_exists('template', $response) &&
                                    array_key_exists('funcname', $response)
                                ) {
                                    $component->template('add', [
                                        'component' => $component->getName($args['comp']),
                                        'template' => $response['template'],
                                        'imports' => $response['imports'],
                                        'funcname' => $response['funcname'],
                                    ]);
                                    return "OK";
                                }
                            }
                            return ['#code' => '500', '#msg' => '非法数据返回'];
                        } else {
                            return ['#code' => '400', '#msg' => '对象不存在'];
                        }
                    } else {
                        return ['#code' => '400', '#msg' => '未知的目标'];
                    }
                } else {
                    return ['#code' => '400', '#msg' => '未知的类型'];
                }
            } else {
                return ['#code' => '400', '#msg' => '组件不存在'];
            }
        }
        return ['#code' => '400', '#msg' => '参数不完整'];
    }

    // 当前已存在组件操作
    public function comps($type, $args)
    {
        if (!array_key_exists('do', $args)) {
            $args['do'] = 'all';
        }

        if ($args['do'] == 'all') {
            // 取得所有组件列表
            $component = new Component();
            return $component->template('get', 'all');
        } else if ($args['do'] == 'del') {
            // 权限检测
            if (!Verify::isLogin()) {
                return ['#code' => '401', '#msg' => '用户未登录'];
            }

            // 删除单个组件
            if (array_key_exists('sign', $args)) {
                $component = new Component();
                $result = $component->delOne($args['sign']);
                if ($result[0]) {
                    return 'OK';
                } else {
                    return ['#code' => '500', '#msg' => $result[1]];
                }
            } else {
                return ['#code' => '400', '#msg' => '参数不完整'];
            }
        } else if ($args['do'] == 'clean') {
            // 清除当前模板
            if (!Verify::isLogin()) {
                return ['#code' => '401', '#msg' => '用户未登录'];
            }
            $component = new Component();
            $component->clean();
            return 'OK';
        }
        return ['#code' => '400', '#msg' => '操作不存在'];
    }

    public function getTpl($type, $args)
    {
        // 权限检测
        if (!Verify::isLogin()) {
            return ['#code' => '401', '#msg' => '用户未登录'];
        }

        $ctype = "API";
        if (array_key_exists('type', $args)) {
            if ($args['type'] == 'VIEW') {
                $ctype = "VIEW";
            } else {
                $ctype = "API";
            }
        }

        $component = new Component();
        throw new CustomException($component->getTpl($ctype), 200);
    }

    // 使用Maker程序创建Template
    public function newTpl($type, $args)
    {
        if (array_key_exists('tname', $args) && array_key_exists('ttype', $args)) {
            if (Verify::isLogin()) {
                if (Verify::authCheck('doapi')) {

                    $ttype = strtolower($args['ttype']);
                    $tname = strtolower($args['tname']);

                    $tpath = $ttype . '/maker/' . System::getRandomStr(6,false) . '.php';

                    if (file_exists(LyApi . '/admin/template/' . $tpath)) {
                        return ['#code' => '400', '#msg' => '名称已存在'];
                    } else {
                        $component = new Component();
                        $code = $component->getTpl($ttype);
                        $change = file_put_contents(LyApi . '/admin/template/' . $tpath, $code);
                        if($change < 1){
                            return ['#code' => '500', '#msg' => '文件写入异常'];
                        }
                    }

                    $db_connect = Setting::dbConnect();
                    if (!$db_connect->has('api_templates', ['name' => $tname, 'type' => $ttype])) {
                    
                        if($ttype == 'view'){
                            $tnum = 2;
                        }else{
                            $tnum = 1;
                        }

                        $result = $db_connect->insert('api_templates', [
                            'name' => $tname,
                            'type' => $tnum,
                            'savetype' => 1,
                            'path' => $tpath
                        ]);

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