<?php
namespace app\admin\controller;
use think\App;
use think\facade\Session;
use think\facade\View;
use think\facade\Request;

class article extends Base{

    public function index(){
		
		//判断内容栏目权限str
		$admin_id=Session::get('admin_id');
		$tq_admin_info=\app\admin\model\Admin::admin_info(1,$admin_id);
		if($tq_admin_info['content_auth_id']>0){
			$content_group=\app\admin\model\AuthRule::content_group_info($tq_admin_info['content_auth_id']);
			$content_group_rid[]=json_decode($content_group['rid']);
			
			foreach($content_group_rid[0] as $k=>$c){
			    $s=$this->shangji($c);
			    if($s!=''){
    				$content_group_rid[]=$s;
			    }
			}
			$result = array_reduce($content_group_rid, function ($result, $value) { return array_merge($result, array_values($value)); }, array());		

			//dump($result);
			$list=\app\admin\model\Cate::where('id','in',$result)->order('sort asc')->field('id,pid,model_id,catename')->select();
		}else{
			$list=\app\admin\model\Cate::order('sort asc')->field('id,pid,model_id,catename')->select();
		}
		//判断内容栏目权限end

		$spread=TQ('TREE_OPEN',true);
		foreach($list as $k=>$c){
			$new_list[$k]['id']=$c['id'];
			$new_list[$k]['pid']=$c['pid'];
			$new_list[$k]['mid']=$c['model_id'];
			$new_list[$k]['title']=$c['catename'];
			if($c['model_id']==1){
				$new_list[$k]['href']=url('cate',array('id'=>$c['id']))->build();
			}else{
				$new_list[$k]['href']=url('article',array('id'=>$c['id']))->build();
			}
			if($c['pid']==0){
			$new_list[$k]['spread']=$spread;
			}
		}
		$data=$this->getTree($new_list);
		$data=json_encode($data);
		
		if(isset($list)){
			if($list[0]['model_id']==1){
				$iframe_url=url('cate',array('id'=>$list[0]['id']));
			}else{
				$iframe_url=url('article',array('id'=>$list[0]['id']));
			}
		}
		
		View::assign(['data'=>$data,'iframe_url'=>$iframe_url]);
		return View::fetch();
    }

    public function shangji($id){
        $ssf=get_id_array($id,2);
        if(count($ssf)>=3){
            $ss1=get_id_array($id,1);
    		return $ss1;
        }
	}

    public function cate(){
		$tdata=Request::param();

		//判断内容栏目权限str
		$admin_id=Session::get('admin_id');
		$tq_admin_info=\app\admin\model\Admin::admin_info(1,$admin_id);
		if($tq_admin_info['content_auth_id']>0){
			$content_group=\app\admin\model\AuthRule::content_group_info($tq_admin_info['content_auth_id']);
			$content_group_rid[]=json_decode($content_group['rid']);
            foreach($content_group_rid[0] as $k=>$c){
			    $s=$this->shangji($c);
			    if($s!=''){
    				$content_group_rid[]=$s;
			    }
			}
			$result = array_reduce($content_group_rid, function ($result, $value) { return array_merge($result, array_values($value)); }, array());				
			if(inarray($tdata['id'],$result)==0){
				echo '无权限';
				exit;
			}
		}
		//判断内容栏目权限end
		
		$info=\app\admin\model\Cate::info($tdata['id']);

		//获取cate_content表扩展字段
		$field_list_array=\app\admin\model\TableField::where('table','CateContent')->order('sort asc')->select()->toArray();

		View::assign(['field_list_array'=>$field_list_array,'info'=>$info]);
		return View::fetch();
    }

	//Article cate 更新
    public function cate_update(){
		$tdata=Request::param();
		
		if($tdata['catename']==''){
			$data =['type' =>2,'msg' =>'栏目名称不能为空'];
			return json($data);
		}
		
		//主表更新
		$id=\app\admin\model\Cate::update($tdata);
		
		$is_null=\app\admin\model\CateContent::where('cate_id',$tdata['id'])->find();

		//日志需求ID
		$log_id=$tdata['id'];
		
		//副表更新或插入
		unset($tdata['id']);
		if(isset($is_null)){
			$cate_id=\app\admin\model\CateContent::where('cate_id',$tdata['cate_id'])->strict(false)->update($tdata);
		}else{
			$cate_id=\app\admin\model\CateContent::where('1=1')->strict(false)->insert($tdata);
		}

		//添加日志
		$log=\app\admin\model\Log::insert('修改栏目内容:数据ID='.$log_id.'');
		
		$data =['type' =>1,'msg' =>'修改成功'];
		return json($data);
    }

    public function cate_edit(){
		$tdata=Request::param();
		$info=\app\admin\model\Cate::info($tdata['id']);
		
		//模型
		$cate_type_list=\app\admin\model\CateType::order('id asc')->select()->toArray();
		
		//下级栏目
		$map['is_effect']=1;
		$map['pid']=$tdata['id'];
		$cate_pid_list=\app\admin\model\Cate::where($map)->field('id,catename')->order('sort asc')->select();
		
		View::assign(['info'=>$info,'cate_pid_list'=>$cate_pid_list,'cate_type_list'=>$cate_type_list]);
		return View::fetch();
	}


    public function article(){
		$tdata=Request::param();

		//判断内容栏目权限str
		$admin_id=Session::get('admin_id');
		$tq_admin_info=\app\admin\model\Admin::admin_info(1,$admin_id);
		if($tq_admin_info['content_auth_id']>0){
			$content_group=\app\admin\model\AuthRule::content_group_info($tq_admin_info['content_auth_id']);
			$content_group_rid[]=json_decode($content_group['rid']);
            foreach($content_group_rid[0] as $k=>$c){
			    $s=$this->shangji($c);
			    if($s!=''){
    				$content_group_rid[]=$s;
			    }
			}
			$result = array_reduce($content_group_rid, function ($result, $value) { return array_merge($result, array_values($value)); }, array());				
			if(inarray($tdata['id'],$result)==0){
				echo '无权限';
				exit;
			}
		}
		//判断内容栏目权限end


		$cate_info=\app\admin\model\Cate::field('id,catepage,model_id,is_sort,is_info')->find($tdata['id']);
		$model=\app\admin\model\CateType::find($cate_info['model_id']);

		$template=app()->getRootPath()."view\admin\article\\".$model['list'].".html";
		if (is_file($template)) {
			$template=$model['list'];
		}else{
			$template='';
		}
		
		$auto_page=tq_value(1,'auto_page','system');
		$auto_page_num=tq_value(1,'page_num','system');
		
		$strtime=isset($tdata['strtime'])?$tdata['strtime']:'';
		$endtime=isset($tdata['endtime'])?$tdata['endtime']:'';
		$keyword=isset($tdata['keyword'])?$tdata['keyword']:'';
		
		View::assign([
			'id'=>$tdata['id'],
			'model_name'=>$model['name'],
			'model_id'=>$model['id'],
			'model_table'=>$model['table'],
			'auto_page'=>$auto_page,
			'auto_page_num'=>$auto_page_num,
			'is_sort'=>$cate_info['is_sort'],
			'is_info'=>$cate_info['is_info'],
			'strtime'=>$strtime,
			'endtime'=>$endtime,
			'keyword'=>$keyword
		]);
		return View::fetch($template);
    }

    public function add(){
		$tdata=Request::param();
		$info=\app\admin\model\Cate::find($tdata['pid'])->toArray();
		
		//获取模型信息
		$model=\app\admin\model\CateType::find($info['model_id'])->toArray();
		
		//获取表扩展字段
		$table="Article".ucfirst($model['table']);
		$field_list_array=\app\admin\model\TableField::where('table',$table)->order('sort asc')->select()->toArray();
		foreach($field_list_array as $k=>$c){
			$info[$c['field_name']]='';
		}
		
		//设置默认sort
		$pid_array=get_id_array($tdata['pid'],2);//获取父级，拿到顶级
		$pid_array=get_id_array($pid_array[0],1);//获取所有子级。
		$pid_array=get_id_array_filter($pid_array,$info['model_id']);//过滤不是当前模型的栏目
				
		$sort=\app\admin\model\Article::where('pid','in',$pid_array)->order('sort desc')->select();
		if($sort->isEmpty()){
		$info['new_sort']=1;
		}else{
		$info['new_sort']=$sort[0]['sort']+1;
		}
		
		//自定义属性
		$ARTICLE_ATT=config('common.ARTICLE_ATT');

		View::assign(['info'=>$info,'model_name'=>$model['name'],'model_table'=>$model['table'],'field_list_array'=>$field_list_array,'ARTICLE_ATT'=>$ARTICLE_ATT]);
		return View::fetch();
	}

    public function create(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		if(trim($tdata['title']=='')){
			$data =['type' =>1,'msg' =>'请填写标题'];
			return json($data);
		}
		
		//主表插入数据
		$tdata['create_time']=strtotime($tdata['create_time']);
		$tdata['end_time']=strtotime($tdata['end_time']);
		$tdata['admin_id']=Session::get('admin_id');
		$cate_id=\app\admin\model\Article::strict(false)->json(['att'])->insertGetId($tdata);
		
		//扩展表插入数据
		$aid=\app\admin\model\Article::create_table($cate_id);

		//添加日志
		$log=\app\admin\model\Log::insert('添加文章内容:数据ID='.$cate_id.'');
		
		$data =['type' =>2,'msg' =>'添加成功'];
		return json($data);
	}
	
	
    public function edit(){
		$tdata=Request::param();
		$info_cate=\app\admin\model\Cate::find($tdata['pid'])->toArray();
		
		//获取模型信息
		$model=\app\admin\model\CateType::find($info_cate['model_id'])->toArray();
		
		//获取表扩展字段
		$table="Article".ucfirst($model['table']);
		$field_list_array=\app\admin\model\TableField::where('table',$table)->order('sort asc')->select()->toArray();
		
		//信息详情
		$info=\app\admin\model\Article::info($tdata['id'],$model['table']);
		//dump($info);
		//自定义属性
		$ARTICLE_ATT=config('common.ARTICLE_ATT');
		
		//cate栏目信息 待确认（where('model_id','<>',1)）
		$cate_list=\app\admin\model\Cate::order('sort asc')->select()->toArray();
		$cate_list=cate_list($cate_list);
		
		View::assign([
					'info'=>$info,
					'cate_list'=>$cate_list,
					'model_id'=>$model['id'],
					'model_name'=>$model['name'],
					'model_table'=>$model['table'],
					'field_list_array'=>$field_list_array,
					'ARTICLE_ATT'=>$ARTICLE_ATT]
		);
		return View::fetch();
	}
	
    public function update(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		if(trim($tdata['title']=='')){
			$data =['type' =>1,'msg' =>'请填写标题'];
			return json($data);
		}

		//主表更新
		$tdata['create_time']=strtotime($tdata['create_time']);
		$tdata['end_time']=strtotime($tdata['end_time']);
		if(empty($tdata['att'])){
		$tdata['att']='';
		}
		$id=\app\admin\model\Article::strict(false)->json(['att'])->update($tdata);
		//扩展表更新
		$aid=\app\admin\model\Article::update_aid();

		//添加日志
		$log=\app\admin\model\Log::insert('修改文章内容:数据ID='.$tdata['id'].'');
		
		$data =['type' =>2,'msg' =>'修改成功'];
		return json($data);
	}
	
	//批量复制
    public function copy(){
		$model_id=Request::param('model_id');
		$ids=Request::param('ids');
		$table=Request::param('model_table');
		$list=\app\admin\model\Cate::order('sort asc')->select()->toArray();
		$list=cate_list($list);

		View::assign(['list'=>$list,'ids'=>$ids,'table'=>$table,'model_id'=>$model_id]);
		return View::fetch();
	}
	
	//批量复制数据处理
    public function copy_update(){
		IS_AJAX(Request::isAjax());
		$article_copy=\app\admin\model\Article::article_copy();
		$data =['type' =>1,'ss'=>$article_copy,'msg' =>'操作成功'];
		return json($data);
	}

	//批量转移
    public function move(){
		$model_id=Request::param('model_id');
		$ids=Request::param('ids');
		$list=\app\admin\model\Cate::order('sort asc')->select()->toArray();
		$list=cate_list($list);

		View::assign(['list'=>$list,'ids'=>$ids,'model_id'=>$model_id]);
		return View::fetch();
	}

	//批量复制数据处理
    public function move_update(){
		IS_AJAX(Request::isAjax());
		$article_move=\app\admin\model\Article::move_update();
		$data =['type' =>1,'ss'=>$article_move,'msg' =>'操作成功'];
		return json($data);
	}

	
	//列表数据		
    public function list_data(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		$get_id_array=get_id_array($tdata['id'],1);
		$get_id_array=get_id_array_filter($get_id_array,$tdata['model_id']);


		$map = [];
		$map[] = ['is_delete','=',1];
		$map[] = ['pid','in',$get_id_array];

		if(!empty($tdata['strtime'])){
			$map[] = ['create_time','>=', strtotime($tdata['strtime'])];
		}
		if(!empty($tdata['endtime'])){
			$map[] = ['create_time','<=', strtotime($tdata['endtime'])];
		}
		if(!empty($tdata['keyword'])){
			$map[] = ['title','like','%'.$tdata['keyword'].'%'];
		}

		$list=\app\admin\model\Article::where($map)
			 ->order('sort '.$tdata['order'].',create_time '.$tdata['order'].'')
			 ->paginate(['list_rows' =>$tdata['limit'],'query' => request()->param(),])->toArray();
		
		foreach($list['data'] as $k=>$c){
			$list['data'][$k]['admin_name']=tq_value($c['admin_id'],'nickname','admin');
		}
		
		$data['code']=0;
		$data['count']=$list['total'];
		$data['data']=$list['data'];
		
		return json($data);
    }

	//后台内容栏目
	public function getTree($array){
        $new_array = [];        
        foreach($array as $v){
            $new_array[$v['id']] = $v;
        }
        $return_tree = [];
        foreach($new_array as $kk=>$vv){
            if(isset($new_array[$vv['pid']])){
                $new_array[$vv['pid']]['children'][] = &$new_array[$kk];
            }else{
                $return_tree[] = &$new_array[$kk];
            }
        }
        return $return_tree;
    }

	//栏目和文章组合字段列表页
    public function field(){
		$tdata=Request::param();

		$auto_page=tq_value(1,'auto_page','system');
		$auto_page_num=tq_value(1,'page_num','system');

		//dump($tdata);
		View::assign(['tdata'=>$tdata,'auto_page'=>$auto_page,'auto_page_num'=>$auto_page_num]);
		return View::fetch();
	}

    public function field_list_data(){

		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		
		$map = [];
		$map[] = ['pid','=',$tdata['pid']];

		$list=\app\admin\model\Field::where($map)
			 ->order('sort asc,id asc')
			 ->paginate(['list_rows' =>$tdata['limit'],'query' => request()->param(),])->toArray();
		
		$data['code']=0;
		$data['count']=$list['total'];
		$data['data']=$list['data'];
		
		return json($data);
	}

    public function field_add(){
		$tdata=Request::param();
		$field_name=substr($tdata['pid'],0,2);//传参前2位，c为cate或cate_content表、a为article表或article扩展表
		
		$map[] = ['field_name','=',$field_name];
		$field=\app\admin\model\TableField::where($map)->field('id,field_content')->find();
		
		$map1[] = ['pid','=',$tdata['pid']];
		$sort=\app\admin\model\Field::where($map1)->order('sort desc')->limit(1)->field('id,sort')->select();
		if($sort->isEmpty()){
			$sort=1;
		}else{
			$sort=$sort[0]['sort']+1;
		}
		
		View::assign(['pid'=>$tdata['pid'],'catename'=>$tdata['catename'],'sort'=>$sort,'field_content'=>$field['field_content']]);
		return View::fetch();
	}

    public function field_create(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		if(trim($tdata['title']=='')){
			$data =['type' =>1,'msg' =>'请填写标题'];
			return json($data);
		}
		
		//插入数据
		$tdata['create_time']=time();
		$field_id=\app\admin\model\Field::strict(false)->insertGetId($tdata);
				
		$data =['type' =>2,'msg' =>'添加成功'];
		return json($data);
	}

    public function field_edit(){
		$tdata=Request::param();
		$field_name=substr($tdata['pid'],0,2);//传参前2位，c为cate或cate_content表、a为article表或article扩展表
		
		$map[] = ['field_name','=',$field_name];
		$field=\app\admin\model\TableField::where($map)->field('id,field_content')->find();
		
		$info=\app\admin\model\Field::find($tdata['id']);
		
		View::assign(['info'=>$info,'pid'=>$tdata['pid'],'catename'=>$tdata['catename'],'field_content'=>$field['field_content']]);
		return View::fetch();
	}

    public function field_update(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		if(trim($tdata['title']=='')){
			$data =['type' =>1,'msg' =>'请填写标题'];
			return json($data);
		}

		//主表更新
		$id=\app\admin\model\Field::strict(false)->update($tdata);
		
		$data =['type' =>2,'msg' =>'修改成功'];
		return json($data);
	}
	
}
