<?php
// +----------------------------------------------------------------------
// | hulacwms 3.0 呼啦企业网站管理系统
// +----------------------------------------------------------------------
// | Copyright (c) 2021 https://www.kaifashu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 开发树
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\model\Config as ConfigModel;
use app\common\validate\Config as ConfigValiate;

class Config extends Auth
{
    /**
     * 配置管理
     */
    public function index(){
        $param=[
            'group'=>'',
            'title'=>''
        ];
        $param=$this->initParam($param);
        $map=[];
        if($param['group']!=''){
            $map[]=['group','=',$param['group']];
        }
        if($param['title']!=''){
            $map[]=['name|title','like','%'.$param['title'].'%'];
        }

        $model=new ConfigModel();
        $lists=$model->where($map)
            ->withAttr('group', function($value) {
                if (!isset($this->config['CONFIG_GROUP_LIST'][$value]))
                    return '';
                return $this->config['CONFIG_GROUP_LIST'][$value];
            })
            ->withAttr('type', function($value) {
                if (!isset($this->config['CONFIG_TYPE_LIST'][$value]))
                    return '';
                return $this->config['CONFIG_TYPE_LIST'][$value];
            })
            ->paginate($this->config['LIST_ROWS'],false,['query' => $this->getRouteQuery()]);
        $this->assign('lists',$lists);
        $this->assign('group',$this->config['CONFIG_GROUP_LIST']);
        $this->assign('param',$param);
        return $this -> fetch();
    }
    /**
     * 配置分组
     */
    public function groups(){
        $model=new ConfigModel();
        $id     =   input('id',1);

        $this->assign('id',$id);
        $lists=$model->where('group',$id)->order('sort asc')->select();
        $this->assign('lists',$lists);
        $this->assign('group',$this->config['CONFIG_GROUP_LIST']);

        return $this -> fetch();
    }

    /**
     * 配置分组批量保存
     */
    public function save($config){
        $model=new ConfigModel();
        if($config && is_array($config)){
            foreach ($config as $name => $value) {
                $model->where('name',$name)->setField('value', $value);
            }
        }
        $model->removeCache($this->request->module());
        //清除前台缓存
        $model->removeCache('index');
        //添加行为记录
        action_log("config_set","config",0,session('UID'));
        $this->success('保存成功！','');
    }

    /**
     * 新增
     */
    public function add(){
        if($this->request->isGet()){
            $this->assign('module',$this->config['CONFIG_MODULE']);
            $this->assign('group',$this->config['CONFIG_GROUP_LIST']);
            $this->assign('type',$this->config['CONFIG_TYPE_LIST']);
            return $this -> fetch();
        }
        $postData=$this->request->param();
        //验证
        $configValidate=new ConfigValiate();
        if (!$configValidate->check($postData)) {
            $this->error($configValidate->getError());
        }

        $model=new ConfigModel();
        //判断配置标识是否重复
        $config=$model->where('name',$postData['name'])->find();
        if($config){
            $this->error('配置标识已存在！');
        }
        $re=$model->add($postData);
        if($re){
            $model->removeCache($this->request->module());
            //清除前台缓存
            $model->removeCache('index');
            //添加行为记录
            action_log("config_add","config",$re,session('UID'));
            $this->success('新增成功！','');
        }
        else{
            $this->error($model->getError());
        }
    }

    /**
     * 编辑
     */
    public function edit(){
        $model=new ConfigModel();
        if($this->request->isGet()){
            $id=input('id');
            $info=$model->get($id);
            $this->assign('module',$this->config['CONFIG_MODULE']);
            $this->assign('group',$this->config['CONFIG_GROUP_LIST']);
            $this->assign('type',$this->config['CONFIG_TYPE_LIST']);
            $this->assign('info',$info);
            return $this -> fetch();
        }
        $paramData=$this->request->param();
        //验证
        $configValidate=new ConfigValiate();
        if (!$configValidate->check($paramData)) {
            $this->error($configValidate->getError());
        }
        //用户名查重
        $config=$model->where('name',$paramData['name'])->where('id','<>',$paramData['id'])->find();
        if($config){
            $this->error('配置标识已存在！');
        }

        //二次验证配置项或配置值
        $this->validateConfig($paramData['name'],$paramData['value']);
        $data['update_time']=time();

        $re=$model->edit($paramData);
        if($re){
            $model->removeCache($this->request->module());
            //清除前台缓存
            $model->removeCache('index');

            //添加行为记录
            action_log("config_edit","config",$paramData['id'],session('UID'));
            $this->success('编辑成功！','');
        }
        else{
            $this->error($model->getError());
        }
    }
    /**
     * 删除配置
     */
    public function del(){
        $id=$this->request->param('ids/a');
        foreach ($id as $value) {
            //网站基础配置 22个  不允许删除网站基础配置
            if($value<=22){
                $this->error('不允许删除网站基础配置!');
            }
        }
        $model=new ConfigModel();
        $re=$model->del($id);
        if($re){
            $model->removeCache($this->request->module());
            //清除前台缓存
            $model->removeCache('index');

            //添加行为记录
            action_log("config_del","config",$id,session('UID'));
            $this->success('删除成功！');
        }
        else{
            $this->error($model->getError());
        }
    }
    /**
     * 排序
     */
    public function sort(){
        if ($this->request->isPost()){
            $data['id']=input('id/d');
            $data['sort']=input('sort/d');
            $model=new ConfigModel();
            $re=$model->edit($data);
            if($re){
                $model->removeCache($this->config['CONFIG_MODULE']);
                //清除前台缓存
                $model->removeCache('index');

                $this->success('操作成功！');
            }else{
                $this->error($model->getError());
            }
        }
    }

    /**
     * 配置参数验证
     */
    private function validateConfig($name,$value){
        switch ($name) {
            case 'WEB_REWRITE':
                //判断是否伪静态设置，如果是，清除栏目分类缓存
                cache('DATA_DOCUMENT_CATEGORY_LIST', null);
                break;
            case 'WEB_TEMPLATE_PATH':
                $match=preg_match('/^[0-9a-zA-Z]+$/',$value);
                if(!$match){
                    $this->error('模板目录名必须以字母或数字命名！');
                }
                break;
        }
    }
}
