<?php

namespace APP\program\admin;

use APP\DI;
use APP\program\system\System;
use LyApi\tools\Template;

/**
 * LyApi - Admin System
 * 用于Component程序操作
 */

class Component
{

    private $comp_rpath;

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

    // 检查 Component 是否符合标准
    public function checkComp($name)
    {
        if (is_dir($this->comp_rpath . $name)) {
            $path = $this->comp_rpath . $name . '/';
            if (file_exists($path . 'setting.json')) {
                $json = json_decode(file_get_contents($path . 'setting.json'), true);
                if (
                    array_key_exists("name", $json) && array_key_exists("sign", $json) &&
                    array_key_exists("form", $json) && array_key_exists('filter', $json) &&
                    array_key_exists("manager", $json)
                ) {
                    return true;
                }
            }
        }
        return false;
    }

    /// 取得目标路径
    public function getPath($sign)
    {
        $json = file_get_contents(LyApi . '/admin/components/comp.json');
        $json = json_decode($json, true);
        $regs = $json['register'];
        foreach ($regs as $key => $value) {
            if ($value['sign'] == $sign) {
                return $value['path'];
            }
        }
        return false;
    }

    /// 取得目标名称
    public function getName($pname)
    {
        $path = LyApi . '/admin/components/' . $pname . '/';
        if (is_dir($path)) {
            if (file_exists($path . 'setting.json')) {
                return json_decode(file_get_contents($path . 'setting.json'), true)['name'];
            }
        }
        return null;
    }

    // 取得 表单数据
    public function getForms($name)
    {
        if ($this->checkComp($name)) {
            $path = $this->comp_rpath . $name . '/';
            $json = json_decode(file_get_contents($path . 'setting.json'), true);

            // 过滤关键词
            $result = $json['form'];

            foreach ($result as $k => $v) {
                if ($v['label'] == 'select') {
                    if (array_key_exists('child', $v)) {
                        if (gettype($v['child']) == 'string') {
                            // 处理对应生成器代码
                            $path = explode('.', $v['child']);
                            if (count($path) >= 2) {

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

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

                                // 取得目标返回值
                                $namespace = 'Admin\\components\\' . explode('/', $name)[1] . '\\' . $class;
                                if (class_exists($namespace)) {
                                    $obj = new $namespace();
                                    $data = $obj->$func();
                                    $result[$k]['child'] = $data;
                                }
                            }
                        }
                    }
                }
            }

            return $result;
        } else {
            return [];
        }
    }

    // 取得控制台程序信息
    public function getConsole($name, $data = [])
    {
        if ($this->checkComp($name)) {
            $path = $this->comp_rpath . $name . '/';
            $json = json_decode(file_get_contents($path . 'setting.json'), true);
            if (array_key_exists('console', $json)) {
                $file = $json['console'];
                // 判断 console 类型

                $pattern = '/^prompt\[(.*):(.*)\]$/';
                preg_match($pattern, $file, $matches);
                if ($matches != [] && $matches != null) {
                    // 基础输入框程序
                    return json_encode([
                        "type" => 'prompt',
                        "title" => $matches[1],
                        "name" => $matches[2]
                    ], JSON_UNESCAPED_UNICODE);
                } else {
                    if (file_exists($this->comp_rpath . $name . '/' . $file)) {
                        return Template::RenderTemplate(file_get_contents($this->comp_rpath . $name . '/' . $file), $data);
                    }
                    return false;
                }
            }
            return false;
        }
    }

    // 模板操作程序
    public function template($do, $option = [])
    {
        $cache = DI::FileCache('admin/maker');

        // 初始化基础数据键
        if (!$cache->has('comp-list')) {
            $cache->set('comp-list', []);
        }
        if (!$cache->has('used-list')) {
            $cache->set('used-list', []);
        }
        if (!$cache->has('func-list')) {
            $cache->set('func-list', []);
        }

        if ($do == 'add') {
            if (gettype($option) == 'array') {

                if (!array_key_exists('component', $option)) {
                    return false;
                }

                if (!array_key_exists('funcname', $option)) {
                    return false;
                }

                // 生成组件识别码
                $new_code = System::getRandomStr(8, false);

                $compset = $cache->get('comp-list');
                $ncomps = [
                    'name' =>  $option['component'],
                    'code' => $new_code,
                    'func' => $option['funcname']
                ];

                if (array_key_exists('template', $option)) {
                    $ndata = $cache->get('func-list');

                    $template = "\tpublic function " . $option['funcname'] . "(\$type,\$args){\n";
                    $template .= "\t\t" . $option['template'] . "\n";
                    $template .= "\t}";

                    $ndata[$new_code] = $template;
                    $ndata = $cache->set('func-list', $ndata);
                }

                if (array_key_exists('imports', $option)) {
                    $ndata = $cache->get('used-list');
                    $ndata = array_merge($ndata, $option['imports']);
                    $ndata = $cache->set('used-list', $ndata);
                    $ncomps['used'] = $option['imports'];
                }

                // 插入组件数据到缓存
                array_push($compset, $ncomps);
                $ndata = $cache->set('comp-list', $compset);
            }
            return false;
        } else if ($do == 'get') {
            if ($option == 'all') {
                return $cache->get('comp-list');
            }else{
                $data = $cache->get("comp-list");
                foreach ($data as $key => $value) {
                    if($value['code'] == $option){
                        return $value;
                    }
                }
            }
            return false;
        }
    }

    // 删除单个库中组件
    public function delOne($sign)
    {
        $cache = DI::FileCache('admin/maker');
        // 验证 Sign 是否存在
        $ndata = $cache->get('func-list');
        if (array_key_exists($sign, $ndata)) {
            unset($ndata[$sign]);
            $ndata = $cache->set('func-list', $ndata);
            $ndata = $cache->get('used-list');
            unset($ndata[$sign]);
            $ndata = $cache->set('used-list', $ndata);

            // 遍历找出具体信息并同步删除
            $compset = $cache->get('comp-list');
            foreach ($compset as $key => $value) {
                if ($value['code'] == $sign) {
                    unset($compset[$key]);
                    break;
                }
            }
            $ndata = $cache->set('comp-list', $compset);
            return [true,'OK'];
        } else {
            return [false, '数据不存在'];
        }
    }

    // 清空当前组件库
    public function clean(){
        $cache = DI::FileCache('admin/maker');
        $cache->clean();
    }

    // 取得模板程序代码内容
    public function getTpl($type = "API"){
        $cache = DI::FileCache('admin/maker');
        $funcs = $cache->get('func-list');
        $useds = $cache->get('used-list');
        
        $functions = '';
        $imports = '';

        $funcs = array_filter($funcs);
        $useds = array_filter($useds);

        foreach ($funcs as $key => $value) {
            $functions .= "\t" . $value . "\n";
        }

        foreach ($useds as $key => $value) {
            $imports .= "use " . $value . ";\n";
        }

        // 默认对象模板
        $class_code = "<?php\n" .
        "namespace __namespace;\n\n" .
        "use LyApi\core\classify\[ptype] as Classify[ptype];\n" .
        $imports . "\n\n" .
        "// Made with LyApi Admin - Maker\n\n" .
        "class __class extends Classify[ptype]\n{\n" .
        $functions . "\n" .
        "}";

        $class_code = str_replace('[ptype]',$type,$class_code);

        return $class_code;
    }

}
