<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-07
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Controller;
use app\common\model\Site;
use app\admin\model\Cmsmodels;
use app\admin\model\Cmsfields;
use Request;
use Db;

class Funcontent extends Base
{
	protected $modelclass;
	protected $modellist;
	protected $modelinfo;
	protected function initialize()
    {
    	parent::initialize();
    	// 获取所有栏目模型
        $this->modellist = Cmsmodels::whereType(2)->order('torder asc')->select();
		
		$this->assign('modellist',$this->modellist);
		// 当前模型信息
		if(Request::has('model_id','param')) {
			$this->modelinfo = Cmsmodels::whereType(2)->get(Request::param('model_id'));
        	if(!$this->modelinfo) $this->error('模型不存在');
        	$this->modelclass = 'app\\common\\model\\'.$this->modelinfo['classname'];
        	if(!class_exists($this->modelclass)) $this->error('模型文件不存在');
        	// 模型信息
        	$this->assign('modelinfo',$this->modelinfo);
        }
    }
	// 内容首页
	public function index()
	{
		foreach ($this->modellist as $k => $v) {
			$class = 'app\\common\\model\\'.$v->classname;
			$Class = new $class;
			$this->modellist[$k]['content_count'] = $Class::whereSiteId(session('siteid'))->count();
			$this->modellist[$k]['attamodel'] = Cmsmodels::get($v['attamodel_id']);
		}
		$this->assign('modellist',$this->modellist);
		return $this->fetch();
	}

	// 数据列表
	public function clist()
	{
		$Class = new $this->modelclass;
		// 获取数据列表
		if(Request::isPost()) {
			$data = $Class::whereSiteId(session('siteid'))->when(!empty(Request::post('order')),function($query){
				$query->order([Request::post('order')['field'] => Request::post('order')['type']]);
			},function($query){
				$query->order(['torder' => 'asc','create_time' => 'desc']);
			})->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
		return $this->fetch();
	}

	// 搜索
	public function search()
	{
		$Class = new $this->modelclass;
		$modelsearchfields = Cmsfields::whereCmsmodelsId($this->modelinfo['id'])->whereStatus(1)->where('is_search > 0')->order('torder')->select();
		if(Request::isPost()) {
			$data = Request::post();
			foreach ($modelsearchfields as $k => $v) {
				if(!empty($data[$v->name])) {
					$map[] = $v->is_search == 1 ? [$v->name,'like','%'.$data[$v->name].'%'] : [$v->name,'=',$data[$v->name]];
				}
			}
			$map = !empty($map) ? $map : '1=1';
			$data = $Class::whereSiteId(session('siteid'))->when(!empty(Request::post('order')),function($query){
				$query->order([Request::post('order')['field'] => Request::post('order')['type']]);
			},function($query){
				$query->order(['torder' => 'asc','create_time' => 'desc']);
			})->when(!empty($data['id']),function($query)use($data){
				$query->whereId($data['id']);
			})->where($map)->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
	}
	
	// 添加
	public function add()
	{
		$Class = new $this->modelclass;
		if(Request::isPost()) {
			$data = Request::post();
			$data['create_time'] = time();
			$data['admin_id'] = session('adminid');
            $data['site_id'] = session('siteid');
            $data['cmsmodels_id'] = $this->modelinfo['id'];
            $this->checkData($data);
			$result = $Class::create($data,true);
			adminlog(2,'新增('.$Class::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		$torder = $Class->whereSiteId(session('siteid'))->count()+1;
		return $this->fetch('',compact('torder'));
	}

	// 修改
	public function edit($id)
	{
		$Class = new $this->modelclass;
		$info = $Class::whereSiteId(session('siteid'))->get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$data['admin_id'] = session('adminid');
            $data['site_id'] = session('siteid');
            unset($data['update_time']);
            unset($data['delete_time']);
            $this->checkData($data);
			$result = $info->allowField(true)->save($data);
			adminlog(2,'编辑('.$Class::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
		return $this->fetch('',compact('info'));
	}

	// 批量修改和内容转移
	public function edits()
	{
		if(Request::isPost()) {
			$data = Request::post();
            $Class = new $this->modelclass;
			$result = $Class::whereIn('id',$data['id'])->setField($data['field'],$data['value']);
			adminlog(2,'编辑('.$Class::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
	}

	// 删除
	public function del()
	{
		if(Request::isPost()) {
			$data = Request::post();
            $result = Db::name($this->modelinfo['tablename'])->whereSiteId(session('siteid'))->whereIn('id',$data['id'])->delete(); // Db类实现真实删除
            adminlog(2,'删除('.Db::name($this->modelinfo['tablename'])->getLastsql().')',$result?1:0);
            \app\common\model\Diyfields::whereTablename($this->modelinfo['tablename'])->whereIn('cid',$data['id'])->delete();
            if($this->modelinfo['attamodel_id']) {
        		$atta_table = Cmsmodels::getFieldById($this->modelinfo['attamodel_id'],'tablename');
        		Db::name($atta_table)->whereSiteId(session('siteid'))->whereIn('c_id',$data['id'])->delete();
        	}
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 数据验证
	private function checkData($data)
	{
		if(!isset($data['list_switch'])) {
			$validate = new \think\Validate;
			$rulelist = [];
			$listfields = Cmsfields::whereCmsmodelsId($this->modelinfo['id'])->whereStatus(1)->order('torder')->select();
			foreach ($listfields as $k => $v) {
				$rule = [];
				// 必填
				if($v['require'] == 1) {
					$rule = array_merge(['require'],$rule);
				}
				// 文本域
				if($v['type'] == 'input' && !empty($v['rule'])) {
					if($v['rule'] == 'regex') {
						$rule = array_merge(["regex:".$v['rule']],$rule);
					} else {
						$rule = array_merge([$v['rule']],$rule);
					}
				}
				// 整数
				if($v['type'] == 'integer') {
					$rule = array_merge(['integer'],$rule);
				}
				// 小数
				if($v['type'] == 'decimal') {
					$rule = array_merge(['float'],$rule);
				}
				$rulelist[$v['name'].'|'.$v['title']] = $rule;
			}
			$validate->rule($rulelist);
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}
}