<?php
namespace app\wendasns\service;

use app\wendasns\model\Article;
use app\wendasns\service\PwSrv;
use app\wendasns\model\Category;

use wendasns\Wend;
use think\Exception;

class PwArticle
{
	public $id = 0;
	
    public function __construct()
    {
        
    }
    
	//
	public function save()
	{
    	if(empty($this->id)){
    		return $this->add();
    	}else{
    		return $this->update();
    	}
	}

	//添加文章
	private function add()
	{
		//是否审核
    	$status = configure('wenda.postCheck') ? 'check' : 'normal';
    	$create_time = Wend::getTime();
    	
    	$summary = empty($this->summary) ? mb_substr(strip_tags($this->content),0,80,'utf-8') : $this->summary;
    	$data = [
    		'user_id' => $this->user_id,
    		'category_id' => $this->category_id,
    		'title' => $this->title,
    		'content' => $this->content,
    		'summary' => $summary,
    		'tags' => $this->setTags($this->tags),
    		'close' => $this->speak,
			'cover' => $this->setCover($this->cover,$this->content),
    		'ip' => request()->ip(),
    		'create_time' => $create_time,
    		'status' => $status,
    		'client' => Wend::getClient()
    	];

    	$dm = Article::create($data);
    	if(isset($dm->id)){
    		$dm->kid = getKid($dm->id, $dm->create_time);
    		$dm->save();
    		//设置标签
            PwSrv::setTags($dm->id, $dm->tags, 'article');

    		//更新用户数据
    		$dm->users()->find()->datas()->inc('article')->update();
    		
    		//记录用户行为
    		$dm->users()->find()->behaviors()->save(['source_id'=>$dm->id,'action'=>'article','create_time'=>$create_time]);
    		
    		//钩子
    		event('EndArticlePost', $dm);
    		$this->id = $dm->id;
    		return $dm;
    	}else{
    		throw new Exception('发布失败');
    	}
	}
	
	//更新文章
	private function update()
	{
    	$dm = Article::find($this->id);
    	if(!$dm){
    		throw new Exception('文章不存在');
    	}
    	
		if(!admin_check('thread.edit')){
			if(request()->loginUser->uid<>$dm->user_id){
				throw new Exception('所在用户组没有操作权限');
			}
			
	    	if($dm->remove){
	    		throw new Exception('文章已删除');
	    	}

	    	if($dm->status<>'normal'){
	    		throw new Exception('文章正在审核中，禁止编辑');
	    	}
		}

    	$status = configure('wenda.postCheck') ? 'check' : 'normal';
        $dm->category_id = $this->category_id;
        $dm->title = $this->title;
        $dm->content = $this->content;
        $dm->summary = $this->summary;
        $dm->tags = $this->setTags($this->tags);
        $dm->speak = $this->speak;
		$dm->cover = $this->setCover($this->cover,$this->content);
        $dm->status = $status;
		$dm->update_time = Wend::getTime();
		$dm->save();
		//设置标签
        PwSrv::setTags($dm->id, $dm->tags, 'article');
        event('EndArticleEdit', $dm);
		return $dm;
	}
	
	//删除文章
	public function remove()
	{
    	$dm = Article::find($this->id);
    	if(!$dm){
    		throw new Exception('文章不存在');
    	}
    	if(!admin_check('thread.remove')){
    		if(request()->loginUser->uid<>$dm->user_id){
    			throw new Exception('所在用户组没有操作权限');
    		}

	    	if($dm->remove){
	    		throw new Exception('文章已删除');
	    	}
    	
    	}

    	$dm->remove = 1;
    	$dm->save();
    	$dm->users->datas()->dec('article')->update();
    	
    	event('EndArticleRemove',$dm);
    	return $dm;
	}
	
    //获取文章列表
    public static function get($type='new', $category='all', $page=1, $limit=0)
    {
    	$limit || $limit = configure('page.pageArticle',10);

		if($category=='all'){
			$mark = '>';
			$term = 0;
		}else{
			$dm = Category::where([
				['type','=','article'],
				['dir_name','=',$category],
				['status','=',1],
			])->find();
			if(!$dm){
				return [];
			}
			$mark = 'in';
			$term = categoryQuery($dm);
		}
		$sql = [
			'new' => [],
			'hot' => [],
			'top' => [
				['top','>',0]
			],
			'recommend'=>[
				['recommend','>',0]
			]
		];
		if($type!='top') $sql[$type][] = ['top', '=', 0];
		$sql[$type][] = ['category_id', $mark, $term];
		$order = $type=='hot'?'visits':'create_time';
		$dm = Article::where($sql[$type])->where('remove',0)->order($order, 'desc')->paginate(['list_rows'=>$limit,'page'=>$page,'query'=>['cname'=>$category,'type'=>$type,'_s'=>'wendasns/article/index']]);
		return $dm;
	}

	private function setCover($vars,$content)
	{
		$cover = '';
    	if(empty($vars)){
    		preg_match('/<img.*?src="(.*?)".*?>/',$content, $img);
    		$cover = isset($img[1])?$img[1]:'';
    	}else{
    		$cover = $vars;
    	}
    	return $cover;
	}
	
	private function setTags($vars)
	{
    	$tags = explode(',',$vars);
    	$tags_ar = [];
    	foreach($tags as $v){
    		if(!empty($v)){
    			$tags_ar[] = $v;
    		}
    	}
    	if($tags_ar){
    		return implode(',',$tags_ar);
    	}else{
    		return '';
    	}
	}
}