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

class Navlist extends Base
{
	protected $navgroup = ['G1','G2','G3','G4','G5','G6','G7','G8'];

	// 栏目列表
	public function index()
	{
		if(Request::isPost()) {
			if(Request::post('siteid')) {
				$data = NavlistModel::useGlobalScope(false)->append(['navtype','haschild','url'])->select();
			} else {
				$data = NavlistModel::order('torder','id')->append(['navtype','haschild','url'])->select();
			}
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data->toArray(),'count'=>count($data)]);
		}
		return $this->fetch();
	}

	// 增加栏目
	public function add($pid = 0)
	{
		if(Request::isPost()) {
			$data = Request::post();
			$data['site_id'] = session('siteid');
			if(!empty($data['alias'])) $data['alias'] = str_replace(' ', '_', trim($data['alias']));
			$this->checkData($data);
			switch ($data['type']) {
				case 'about':
					$data['listtemp']=null;
					$data['infotemp']=null;
					$data['link']=null;
					$data['keys']=null;
					$data['desc']=null;
					break;
				case 'model':
					$data['link']=null;
					$Cmsmodels = Cmsmodels::get($data['typeid']);
					break;
				case 'link':
					$data['listtemp']=null;
					$data['infotemp']=null;
					$data['alias']=null;
					$data['typeid']=0;
					$data['keys']=null;
					$data['desc']=null;
				default:
					# code...
					break;
			}
			$name_arr = explode("\n",$data['name']);
			if(count($name_arr)>1) {
				$data['ename']=null;
				$data['alias']=null;
			}
			$data_arr = [];
			foreach ($name_arr as $k => $v) {
				if(!empty($v)) {
					$data['name'] = $v;
					$data_arr[$k] = $data;
				}
			}
			// 新增单页
			if(empty($data['typeid']) && $data['type'] == 'about') {
				foreach ($data_arr as $k => $v) {
					$addAbout = \app\common\model\About::create(['title' => $v['name'],'status' => 1]);
					$data_arr[$k]['typeid'] = $addAbout->id;
				}
			}
            $result = (new NavlistModel())->saveAll($data_arr);
            adminlog(2,'新增('.NavlistModel::getLastsql().')',$result?1:0);
			if ($result) {
				cache("site_nav_list", NULL);
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		$templist = scan_dir('./public/'.config('tpl_path').'/'.$this->siteinfo['pctemplate'].'/'.$this->siteinfo['pchtml'],0,['html']);
		return $this->fetch('',compact('pid','templist'));
	}

	// 修改栏目
	public function edit($id)
	{
		$info = NavlistModel::whereSiteId(session('siteid'))->get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			if(!empty($data['alias'])) $data['alias'] = str_replace(' ', '_', trim($data['alias']));
			unset($data['create_time']);
			unset($data['update_time']);
			$data['site_id'] = session('siteid');
			$this->checkData($data);
			if(!isset($data['list_switch'])) {
				switch ($data['type']) {
					case 'about':
						$data['listtemp']=null;
						$data['infotemp']=null;
						$data['link']=null;
						break;
					case 'model':
						$data['link']=null;
						$Cmsmodels = Cmsmodels::get($data['typeid']);
						break;
					case 'link':
						$data['listtemp']=null;
						$data['infotemp']=null;
						$data['alias']=null;
						$data['typeid']=0;
					default:
						# code...
						break;
				}
			}
			$result = $info->allowField(true)->save($data);
			adminlog(2,'编辑('.NavlistModel::getLastsql().')',$result?1:0);
			if ($result) {
				cache("site_nav_list", NULL);
				$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('info','templist'));
	}

	// 删除栏目
	public function del()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$info = NavlistModel::get($data['id'])->append(['haschild']);
			if($info->haschild) $this->error(lang('delfalse'));
			if($info['type'] == 'model') {
				$model = Cmsmodels::get($data['typeid']);
				if(!empty($model)) {
					// 获取内容ID
					$cids = \think\Db::name($model['tablename'])->whereNavlistId($data['id'])->column('id');
					// 删除内容
					\think\Db::name($model['tablename'])->whereNavlistId($data['id'])->delete();
					// 删除动态字段
					\app\common\model\Diyfields::whereTablename($model['tablename'])->whereIn('cid',$cids)->delete();
					// 获取附属表
					if(!empty($model['attamodel_id'])) {
						$attamodel = Cmsmodels::get($model['attamodel_id']);
						// 删除附属表内容
						\think\Db::name($attamodel['tablename'])->whereIn('c_id',$cids)->delete();
					}
				}
			}
			$result = $info->delete();
			adminlog(2,'删除('.NavlistModel::getLastsql().')',$result?1:0);
			if ($result) {
				cache("site_nav_list", NULL);
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 批量设置模型
	public function setmodel()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$result = NavlistModel::whereIn('id',$data['ids'])->strict(false)->update($data);
			adminlog(2,'编辑('.NavlistModel::getLastsql().')',$result?1:0);
			if ($result) {
				cache("site_nav_list", NULL);
				$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'));
	}

	// 栏目组列表
	public function groupindex()
	{
		if(Request::isPost())
		{
			$data = Navgroup::withAttr('navlistcount',function($value,$data){
				return NavlistModel::where($data['name'],1)->count();
			})->append(['navlistcount'])->order('id')->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
		return $this->fetch();
	}

	// 增加组
	public function addgroup()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$data['site_id'] = session('siteid');
			$this->checkGroupData($data);
			$result = Navgroup::create($data,true);
			adminlog(2,'新增('.Navgroup::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		$navgroup = array_diff($this->navgroup,Navgroup::whereSiteId(session('siteid'))->column('name'));
		return $this->fetch('',compact('navgroup'));
	}

	// 修改组
	public function editgroup($id)
	{
		$info = Navgroup::get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$data['site_id'] = session('siteid');
			$this->checkGroupData($data);
			$result = $info->allowField(true)->save($data);
			adminlog(2,'编辑('.Navgroup::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
		$navgroup = array_diff($this->navgroup,Navgroup::whereSiteId(session('siteid'))->where('name','<>',$info['name'])->column('name'));
		return $this->fetch('',compact('info','navgroup'));
	}

	// 删除组
	public function delgroup()
	{
		if(Request::isPost()) {
			$data = Request::post();
			NavlistModel::setField($data['name'],0);
			$result = Navgroup::destroy($data['id']);
			adminlog(2,'删除('.Navgroup::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 数据验证
	private function checkData($data)
	{
		if(!isset($data['list_switch'])) {
			$validate = new \app\admin\validate\Navlist;
			if(!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}

	private function checkGroupData($data)
	{
		$validate = new \app\admin\validate\Navgroup;
		if(!$validate->check($data)) {
			$this->error($validate->getError());
		}
	}
}