<?php
namespace app\admin\model;
use think\Model;

// 引入框架内置类
use think\facade\Db;
use think\facade\Event;
use think\facade\Session;
use think\facade\Request;

class Article extends Model{
	
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
	
	
	//新增副表数据
    public static function create_table($aid){
		$tdata=Request::param();
		$table='article_'.$tdata['table'];
		$tdata['aid']=$aid;
		$aid=Db::name($table)->strict(false)->insertGetId($tdata);
		return $aid;
	}
	
    public static function info($id,$table){
		$table='article_'.$table;
		$data =Article::alias('a')->join(''.$table.' c', 'a.id = c.aid','left')->field('a.*,c.*')->find($id);
		return $data;
	}
	
	//更新副表数据
    public static function update_aid(){
		$tdata=Request::param();
		$table='article_'.$tdata['table'];
		$info=Db::name($table)->where('aid',$tdata['id'])->find();

		if($info){
			$tdata['fid']=$info['fid'];
			$aid=Db::name($table)->strict(false)->update($tdata);
		}else{
			$tdata['aid']=$tdata['id'];
			$aid=Db::name($table)->strict(false)->insertGetId($tdata);
		}
		return $info;
	}

	//副表数据copy
    public static function article_copy(){
		$tdata=Request::param();
		$table='article_'.$tdata['table'];
		
		$pid_array=get_id_array($tdata['pid'],2);//获取父级，拿到顶级
		$pid_array=get_id_array($pid_array[0],1);//获取所有子级。
		$model_id=tq_value($tdata['pid'],'model_id','cate');//获取栏目模型
		$pid_array=get_id_array_filter($pid_array,$model_id);//过滤不是当前模型的栏目
		
		$sort=\app\admin\model\Article::where('pid','in',$pid_array)->field('sort')->order('sort desc')->limit(1)->select();
		if($sort->isEmpty()){
			$sort=1;
		}else{
			$sort=$sort[0]['sort']+1;
		}

		$data =Article::alias('a')->join(''.$table.' c', 'a.id = c.aid','left')->where('id','in',$tdata['ids'])->order(['a.sort'=>'asc'])->field('a.*,c.*')->select()->toArray();
		foreach($data as $k=>$c){
			$data[$k]['pid']=$tdata['pid'];
			$data[$k]['sort']=$sort+$k;
			$data[$k]['create_time']=strtotime($c['create_time']);
			$data[$k]['update_time']=strtotime($c['update_time']);
			$data[$k]['admin_id']=Session::get('admin_id');
			unset($data[$k]['id']);	
			unset($data[$k]['fid']);
		}

		foreach($data as $k=>$c){
			$id[$k]=Db::name('article')->strict(false)->insertGetId($c);
			$c['aid']=$id[$k];
			$fid=Db::name($table)->strict(false)->insertGetId($c);
		}

		return $sort;
	}
	
	//数据转移操作move
    public static function move_update(){
		$tdata=Request::param();
		$ids_array=explode(',',$tdata['ids']);
		foreach($ids_array as $k=>$c){
			$list[$k]['id']=$c;	
			$list[$k]['pid']=$tdata['pid'];	
			$data=Db::name('article')->update($list[$k]);
		}
		return $data;
	}
}