<?php

namespace app\controller\admin;

use app\service\admin\PluginsServiceFacade;
use laytp\controller\Backend;
use laytp\library\Http;
use think\facade\Config;

/**
 * 插件管理
 */
class Plugins extends Backend
{
    /**
     * files模型对象
     * @var \app\model\Files
     */
    protected $model;
    public    $hasSoftDel = 1;//是否拥有软删除功能

    // 获取laytp官网定义的插件分类列表
    public function category()
    {
        $url  = Config::get('plugin.apiUrl') . '/plugins/category';
        $data = json_decode(Http::get($url), true)['data'];
        return $this->success('获取成功', $data);
    }

    // 查看
    public function index()
    {
        $params['page']        = $this->request->param('page', 1);
        $params['limit']       = $this->request->param('limit', 10);
        $params['category_id'] = $this->request->param('category_id', 0);
        $url                   = Config::get('plugin.apiUrl') . '/plugins/index';
        $data                  = json_decode(Http::get($url, $params), true)['data'];
        $installed             = Config::get('plugin.installed');
        foreach ($data['data'] as $k => $datum) {
            if ($installed && in_array($datum['alias'], $installed)) {
                $data['data'][$k]['installed'] = 1;
                $pluginInfo                    = PluginsServiceFacade::getPluginInfo($datum['alias']);
                if (isset($pluginInfo['version'])) {
                    $version = $pluginInfo['version'];
                } else {
                    $version = '1.0.0';
                }
                $data['data'][$k]['version'] = $version;
            } else {
                $data['data'][$k]['installed'] = 2;
            }
        }
        return $this->success('获取成功', $data);
    }

    // 离线安装 - 所有的离线安装都是覆盖安装
    public function offLineInstall()
    {
        if (PluginsServiceFacade::offLineInstall()) {
            sleep(1);
            $file = request()->file('laytpUploadFile'); // 获取上传的文件
            $pluginConf = Config::get('plugin');
            $fileName = $file->getOriginalName();
            $pathinfo = pathinfo($fileName);
            $plugin = $pathinfo['filename'];
            $pluginConf['installed'][] = $plugin;
            $pluginConf['installed'] = array_unique($pluginConf['installed']);
            sort($pluginConf['installed']);

            $info = PluginsServiceFacade::getPluginInfo($plugin);
            if(isset($info['is_editor']) && $info['is_editor']){
                $pluginConf['installedEditor'][] = $plugin;
                $pluginConf['installedEditor'] = array_unique($pluginConf['installedEditor']);
                sort($pluginConf['installedEditor']);
            }

            return $this->success('安装成功', [
                'pluginConf' => $pluginConf
            ]);
        } else {
            return $this->error(PluginsServiceFacade::getError());
        }
    }

    // 卸载
    public function uninstall()
    {
        $plugin = $this->request->param('plugin');
        $info = PluginsServiceFacade::getPluginInfo($plugin);

        if (PluginsServiceFacade::unInstall($plugin)) {
            $pluginConf = Config::get('plugin');
            foreach($pluginConf['installed'] as $k=>$installed){
                if($installed === $plugin) unset($pluginConf['installed'][$k]);
            }
            $pluginConf['installed'] = array_unique($pluginConf['installed']);
            sort($pluginConf['installed']);

            if(isset($info['is_editor']) && $info['is_editor']){
                foreach($pluginConf['installedEditor'] as $k=>$installedEditor){
                    if($installedEditor === $plugin) unset($pluginConf['installedEditor'][$k]);
                }
                $pluginConf['installedEditor'] = array_unique($pluginConf['installedEditor']);
                sort($pluginConf['installedEditor']);
                // 如果根目录下有相应的html文件，将文件内容进行替换
                $htmlFile = root_path() . 'public/admin/' . $plugin . '.html';
                if(is_file($htmlFile)){
                    file_put_contents($htmlFile, '<p style="color:blue">请先到插件市场安装' . $plugin . '编辑器。</p>
<p style="color:red">注意：安装或卸载编辑器后，需要清空浏览器缓存才能生效</p>');
                }
            }

            return $this->success($plugin . '插件卸载成功', [
                'pluginConf' => $pluginConf,
                'info' => $info
            ]);
        } else {
            return $this->error(PluginsServiceFacade::getError());
        }
    }

    // 安装
    public function install()
    {
        $plugin       = $this->request->param('plugin');
        $laytpGwToken = $this->request->param('laytpGwToken');

        if (PluginsServiceFacade::install($plugin, $laytpGwToken)) {
            // 如果是文件存储，插件安装信息，刚安装完成马上要取出来，取出来的不会是最新的文件内容
            sleep(1);
            $pluginConf = Config::get('plugin');
            $pluginConf['installed'][] = $plugin;
            $pluginConf['installed'] = array_unique($pluginConf['installed']);
            sort($pluginConf['installed']);

            $info = PluginsServiceFacade::getPluginInfo($plugin);
            if(isset($info['is_editor']) && $info['is_editor']){
                $pluginConf['installedEditor'][] = $plugin;
                $pluginConf['installedEditor'] = array_unique($pluginConf['installedEditor']);
                sort($pluginConf['installedEditor']);
            }

            return $this->success($plugin . '插件安装成功', [
                'pluginConf' => $pluginConf
            ]);
        } else {
            $error = PluginsServiceFacade::getError();
            return $this->error($error['msg'], $error['code']);
        }
    }
}