<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */


namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\admin\model\AdminLog;
use app\admin\model\Urlconfig;
use think\Cache;
use think\Db;

class Webconfig extends Permissions
{
    public function index()
    {
        $this->assign('web_config', Db::name('webconfig')->where('id', 1)->find());
        $this->assign('is_close_site_key', (new Urlconfig())->getCloseSiteKey());
        $this->assign('admin_log_num', (new AdminLog())->count());
        $this->assign('backend_pass', (new Urlconfig())->getBackendPass());
        $this->assign('default_static_path', \app\common\model\Templet::DEFAULT_STATIC_PATH);
        $this->assign('default_templet_path', \app\common\model\Templet::DEFAULT_TEMPLET_PATH);
        $this->assign('default_backup_path', Databackup::DEFAULT_PATH);
        $grouptabs = (new \app\common\model\ConfigTab())->order('sort desc')->select();
        $this->assign('tabs', $grouptabs);
        return $this->fetch();
    }

    public function publish()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new \think\Validate([
                ['file_type', 'requireWith:name', '上传类型不能为空'],
                ['file_size', 'requireWith:name', '上传大小不能为空'],
                ['host', 'url'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            if (isset($post['article_ftp_config']) && !empty($post['article_ftp_config'])) {
                $json = json_decode($post['article_ftp_config'], true);
                if (!is_array($json)) {
                    $this->error('ftp配置格式错误');
                } else {
                    $post['article_ftp_config'] = json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
                }
            }
            if (!isset($post['is_log'])) {
                $post['is_log'] = 0;
            }
            if (!isset($post['is_close_site'])) {
                $post['is_close_site'] = 0;
            }
            $model = (new \app\common\model\Webconfig())->where('id', 1)->find();
            if (false == $model->allowField(true)->save($post)) {
                $this->error('提交失败');
            } else {
                Cache::clear();
                $this->success('提交成功', 'admin/webconfig/index');
            }
        }
    }
}
