<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-07-15
* @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 app\admin\model\Navlist;
use Request;
use Db;

class Content extends Base
{
	protected $modelclass;
	protected $modellist;
	protected $modelinfo;
	protected function initialize()
    {
    	parent::initialize();
    	// 获取所有栏目模型
        $this->modellist = Cmsmodels::whereType(1)->order('torder asc')->select();
		
		$this->assign('modellist',$this->modellist);
		// 当前模型信息
		if(Request::has('model_id','param')) {
			$this->modelinfo = Cmsmodels::whereType(1)->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]['recycle_count'] = $Class::onlyTrashed()->whereSiteId(session('siteid'))->count();
			$this->modellist[$k]['attamodel'] = Cmsmodels::get($v['attamodel_id']);
		}
		$this->assign('modellist',$this->modellist);
		return $this->fetch();
	}

	// 数据列表
	public function clist($navlist_id='')
	{
		$Class = new $this->modelclass;
		$recycle_count = $Class::onlyTrashed()->whereSiteId(session('siteid'))->count();
		if($navlist_id) {
			// 获取数据列表
			if(Request::isPost()) {
				$data = $Class::whereSiteId(session('siteid'))->with('navlist')->where(function($query)use($navlist_id){
					// 获取分类自身和子孙ID集
					$navlist_ids = array_column(get_sons(Navlist::all()->toArray(),$navlist_id),'id');
					$navlist_ids = array_merge([$navlist_id],$navlist_ids);
					$query->whereIn('navlist_id',$navlist_ids);
				})->when(!empty(Request::post('order')),function($query){
					$query->order([Request::post('order')['field'] => Request::post('order')['type']]);
				},function($query){
					$query->order(['istop' => 'desc','torder' => 'asc','create_time' => 'desc']);
				})->append(['url'])->paginate(Request::post('limit/d'))->toArray();
				return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total'],'recycle_count' => $recycle_count]);
			}
			return $this->fetch('list2',compact('navlist_id'));
		} else {
			// 获取数据列表
			if(Request::isPost()) {
				$data = $Class::whereSiteId(session('siteid'))->with('navlist')->when(!empty(Request::post('navlist_id')),function($query){
					// 获取分类自身和子孙ID集
					$navlist_ids = array_column(get_sons(Navlist::all()->toArray(),Request::post('navlist_id')),'id');
					$navlist_ids = array_merge([Request::post('navlist_id')],$navlist_ids);
					$query->whereIn('navlist_id',$navlist_ids);
				})->when(!empty(Request::post('order')),function($query){
					$query->order([Request::post('order')['field'] => Request::post('order')['type']]);
				},function($query){
					$query->order(['istop' => 'desc','torder' => 'asc','create_time' => 'desc']);
				})->append(['url'])->paginate(Request::post('limit/d'))->toArray();
				return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total'],'recycle_count' => $recycle_count]);
			}
			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'))->with('navlist')->when(!empty(Request::post('order')),function($query){
				$query->order([Request::post('order')['field'] => Request::post('order')['type']]);
			},function($query){
				$query->order(['istop' => 'desc','torder' => 'asc','create_time' => 'desc']);
			})->when(!empty($data['id']),function($query)use($data){
				$query->whereId($data['id']);
			})->when(!empty($data['title']),function($query)use($data){
				$query->where([['title','like','%'.$data['title'].'%']]);
			})->where($map)->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
	}
	
	// 添加
	public function add($type='')
	{
		$Class = new $this->modelclass;
		if($type == 'batch') {
			if(Request::isPost()) {
				$datas = [];
				$data = Request::post();
				if(empty($data['imgs'])) $this->error(lang('addfalse'));
				$imges = json_decode($data['imgs'],true);
				$bcount = count($imges);
				unset($data['imgs']);
				foreach ($imges as $k => $v) {
					if(!empty($v['title']) && !empty($v['src'])) {
						$datas[$k] = $data;
						$datas[$k]['title'] = !empty($data['title'])?$data['title']:$v['title'];
						$datas[$k]['img'] = $v['src'];
						$datas[$k]['admin_id'] = session('adminid');
	            		$datas[$k]['site_id'] = session('siteid');
	            		$datas[$k]['cmsmodels_id'] = $this->modelinfo['id'];
					}
				}
				$tablename = $this->modelinfo['tablename'];
				$result = Db::name($tablename)->data($datas)->limit(50)->insertAll();
				if ($result) {
					$this->success("成功添加".$result."条,失败".($bcount-$result)."条");
				} else {
					$this->error(lang('addfalse'));
				}
			}
		} else {
			if(Request::isPost()) {
				$data = Request::post();
	            $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;
		$templist = scan_dir('./public/'.config('tpl_path').'/'.$this->siteinfo['pctemplate'].'/'.$this->siteinfo['pchtml'],0,['html']);
		$this->assign('torder',$torder);
		$this->assign('templist',$templist);
		return $this->fetch($type?'add_'.$type:'');
	}

	// 修改
	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'));
			}
		}
		$templist = scan_dir('./public/'.config('tpl_path').'/'.$this->siteinfo['pctemplate'].'/'.$this->siteinfo['pchtml'],0,['html']);
		return $this->fetch('',compact('templist','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();
            if(Request::param('type') == 'soft') {
            	$result = Db::name($this->modelinfo['tablename'])->whereSiteId(session('siteid'))->whereIn('id',$data['id'])->setField('delete_time',time()); // Db类实现软删除
            	adminlog(2,'删除('.Db::name($this->modelinfo['tablename'])->getLastsql().')',$result?1:0);
            } else {
            	$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($this->modelinfo->region) {
            	// 	Regiondata::whereIn('cid',$data['id'])->whereCmsmodelsId($this->modelinfo->id)->delete();
            	// }
            }
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 回收站
	public function recycle()
	{
		$Class = new $this->modelclass;
		// 获取数据列表
		if(Request::isPost()) {
			$list = $Class::onlyTrashed()->whereSiteId(session('siteid'))->order('torder')->with('navlist')->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$list['data'],'count'=>$list['total']]);
		}
		return $this->fetch();
	}

	// 恢复
	public function restore()
	{
		if(Request::isPost()) {
			$data = Request::post();
            $result = Db::name($this->modelinfo['tablename'])->whereSiteId(session('siteid'))->whereIn('id',$data['id'])->setField('delete_time',0); // Db类实现数据恢复
			if ($result) {
				$this->success(lang('resttrue'));
			} else {
				$this->error(lang('restfalse'));
			}
		}
	}

	// 复制内容
	public function copy()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$Class = new $this->modelclass;
			$datalist = $Class::whereIn('id',$data['id'])->select()->toArray();
			foreach ($datalist as $k => $v) {
				unset($datalist[$k]['id']);
				$datalist[$k]['navlist_id'] = $data['navlist_id'];
				$datalist[$k]['alias'] = '';
				$datalist[$k]['create_time'] = $datalist[$k]['update_time'] = time();
				unset($datalist[$k]['delete_time']);
			}
			// 用DB方法，提升效率
			$result = Db::name($this->modelinfo['tablename'])->insertAll($datalist);
			if ($result) {
				return ['code'=>1 ,'msg'=>lang('acttrue')];
			} else {
				return ['code'=>0 ,'msg'=>lang('actfalse')];
			}
		}
	}

	// 数据验证
	private function checkData($data)
	{
		if(!isset($data['list_switch'])) {
			$validate = new \think\Validate;
			$rulelist = ['title|标题' => 'require','navlist_id|栏目' => 'require','alias|文件名' => 'chsDash|unique:'.$this->modelinfo['tablename'].',site_id^alias|min:3'];
			$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());
			}
		}
	}
}