<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-28
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Controller;
use think\Container;
use app\admin\model\Addons as AddonsModel;
use app\admin\model\Hooks;
use Request;
use think\facade\Env;

class Addons extends Base
{
	public function Index()
	{
		if(Request::isPost()) {
			$addons = [];
			$addons_path = Env::get('addons_path');
			// 获取已存在的插件
			$addons_arr = array_column(AddonsModel::select()->toArray(), NULL,'name');
			//扫描插件文件夹
			$files = scandir($addons_path);
			foreach ($files as $file) {
				$isinstall = false;
				$status = false;
				// 已安装的插件
				if (isset($addons_arr[strtolower($file)])) {
					$isinstall = true;
					$status = $addons_arr[strtolower($file)]['status'];
				}
				// 所有的插件
				if ($file != '.' && $file != '..' && is_dir($addons_path . $file)) {
					if ($object = $this->getInstance($file)) {
						$addons[] = array_merge($object->getInfo(),['status' => $status] , ['setting' => empty($object->getConfig())?false:$object->getConfig()],['isinstall' => $isinstall],['hooks' => implode(',',Hooks::whereAddonName($object->getName())->column('name'))]);
					}
				}
			}
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$addons,'count'=>count($addons)]);
		}
		return $this->fetch();
	}

	/**
     * 安装插件
     */
    public function install()
    {
    	if(Request::isPost()) {
    		$name = Request::post('name');
    		if (!$name) $this->error('参数错误');
	        if ($object = $this->getInstance($name)) {
	            $data = $object->getInfo();
	            $data['setting'] = $object->getConfig();
	            if(AddonsModel::whereName($data['name'])->find()) $this->error('该插件已安装，请勿重复安装!');
	            // 读取插件目录及钩子列表
	            $base = get_class_methods("\\think\\Addons");
	            // 读取出所有公共方法
	            $methods = (array)get_class_methods($object);
	            // 跟插件基类方法做比对，得到差异结果
	            $hooks = array_diff($methods, $base);
	            $hooks = implode(',',$hooks);
	            // 检测钩子
		        if (!empty($hooks)) {
		        	if(!Hooks::checkHook($hooks)) {
		        		$this->error('此插件钩子命名不可用！');
		        	}
		        }
		        if(!$object->checkInfo()) $this->error('插件基础信息不完整，安装失败!');
		        if (!$object->install()) $this->error('执行插件内置安装方法出现错误！');
		        $data['status']=1;
		        if(AddonsModel::create($data,true)) {
		        	if(!empty($hooks)) {
		        		if (!Hooks::addhooks($hooks, $name)) $this->error('安装插件钩子时出现错误！');
		        	}
		        	$this->success('安装成功');
		        }
	        }
    	}
        $this->error('安装失败');
    }

    // 卸载
    public function uninstall()
    {
    	if(Request::isPost()) {
    		$name = Request::post('name');
    		if (!$name) $this->error('参数错误');
    		$info = AddonsModel::whereName($name)->find();
    		if ($info && $object = $this->getInstance($name)) {
    			// 卸载钩子
		        if (false === Hooks::deletehooks($name)) $this->error('卸载插件钩子出错！');
		        if(!$object->uninstall()) $this->error('执行插件内置卸载方法出现错误！');
		        // 删除插件
                if($info->delete()) $this->success('插件卸载成功');
                $this->error('插件卸载失败！');
    		}
    		$this->error('插件卸载失败！');
    	}
    }

	/**
     * 删除插件
     */
    public function delete()
    {
    	if(Request::isPost()) {
    		$name = Request::post('name','');
	        $addons_path = Env::get('addons_path');
	        if ($name) {
	            rm_dirs($addons_path . $name);
	            $this->success('删除成功');
	        }
	        $this->error('参数错误');
    	}
    }

	/**
     * 获取插件实例
     * @param $file
     * @return bool|object
     */
    protected function getInstance($file)
    {
        $class = "\\addons\\{$file}\\Widget";
        if (class_exists($class)) {
            return Container::get($class);
        }
        return false;
    }

	// 插件市场
	public function market()
	{
		if(Request::isPost()) {
			$data=[];
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data,'count'=>count($data)]);
		}
		return $this->fetch();
	}

    // 配置
    public function config($addon_name)
    {
    	$name = $addon_name;
    	if (!$name) $this->error('参数错误');
    	if($object = $this->getInstance($name)) {
    		$config = $object->getConfig();
    		if(empty($config)) $this->error('无插件配置信息！');
    	}
    	if(Request::isPost()) {
    		$data = Request::post();
            foreach ($config as $k => $v) {
            	if(isset($data[$k])) {
            		$config[$k]['value'] = $data[$k];
            	}
            }
            $addons_path = Env::get('addons_path') . $name . DIRECTORY_SEPARATOR;
            // 读取当前插件配置信息
	        if (is_file($addons_path . 'config.php')) {
	            $config_file = $addons_path . 'config.php';
	            $result = file_put_contents($config_file, "<?php\nreturn " . var_export($config, true) . ";");
	            // 更新插件配置
		        if ($result) {
		            $this->success(lang('edittrue'));
		        } else {
		            $this->error(lang('editfalse'));
		        }
	        }
	        $this->error(lang('editfalse'));
    	}
    	
        if(!$config) $this->error('无插件配置信息！');
        $this->view->config('view_path', env('module_path').'view' . DS);
        return $this->fetch('',compact('addon_name','config'));
    }

    // 开关
    public function setstatus()
    {
    	if(Request::isPost()) {
    		$data = Request::post();
            if(!$info = AddonsModel::whereName($data['name'])->find()) $this->error('无此插件!');
	        if ($info->save($data)) {
	            $this->success(lang('edittrue'));
	        } else {
	            $this->error(lang('editfalse'));
	        }
    	}
    }
}