<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\wendasns\controller;
use app\wendasns\WenBaseController;

use app\wendasns\service\PwArticle;
use app\wendasns\service\PwSeo;
use app\wendasns\service\Srv;
use app\wendasns\model\Article as byArticle;
use app\wendasns\model\Category;
use app\wendasns\model\User;
use app\wendasns\model\Praise;
use app\wendasns\model\Collect;
use app\wendasns\model\Look;
use app\wendasns\model\Comment;
use app\wendasns\model\Reward;
use app\wendasns\model\Seo;
use app\wendasns\model\Reply;
use wendasns\Wend;
use think\Exception;
use think\App;
use think\facade\View;
use think\exception\ValidateException;

class Article extends WenBaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    	if(in_array(request()->action(true), ['post','remove','close','collect','reply'])){
    		if(!$this->loginUser->isLogin) error('请登录后再操作');
    	}
    }

	//文章列表页
    public function index($cname='all',$type='new',$page=1)
    {
    	$categoryname = '';
    	if($cname=='all'){
    		$dm = Category::where('type','article')->where('category_id','=',0)->select();
    		$category[] = ['dir_name'=>'all','list'=>$dm];
    	}else{
	    	$dm = Category::where('type','article')->where('dir_name',$cname)->find();
	    	$categoryname = ' - '.$dm->name;
	    	$category = categoryNavig($dm,'article');
    	}
		
		$logs = PwArticle::get($type, $cname, $page);

		$typear = ['new'=>'最新','hot'=>'热门'];
		$pages = $page>1?' - 第'.$page.'页':'';
		
		$data = [
			'category' => $category,
			'logs' => $logs,
			'type' => $type,
			'categoryname' => $cname
		];
		$dm = Seo::where('type','article')->find();
		$seo = new PwSeo();
		$seo->title = sprintf('%s%s%s%s',isset($typear[$type])?$typear[$type]:'',$dm->title,$categoryname,$pages);
		$seo->description = $dm->description;
		$seo->keywords = $dm->keywords;
		$seo->set();
		View::assign($data);
		event('ArticleListPage');
        return View::fetch();
    }

	public function load()
	{
		$limit = input('get.limit',10,'intval');
		$dm = byArticle::where([
			['status','=','normal'],
			['remove','=',0],
		])->order('create_time', 'desc')->paginate($limit);
		
		if($this->request->isJson()){
			$data = $dm->toArray();
			success('ok', $data['data'], ['count'=>$data['total']]);
		}
		return view('load',['article'=>$dm]);
	}
	
    //文章详情页
	public function show($id=0, $kid='', $category='')
	{
		if($kid){
			$dm = byArticle::where('kid',$kid)->find();
		}else{
			$dm = byArticle::find($id);
		}
		$limit = input('get.limit',10,'intval');

        if(!$dm){
            error('文章不存在或已删除');
        }

		if(!empty($category) && $dm->categorys->dir_name!==$category){
			error('文章不存在或已删除');
		}

        if($dm->user_id<>$this->loginUser->uid && $dm->remove){
            error('文章不存在或已删除');
        }
        
        if($dm->status=='check'){
			if($dm->user_id!==$this->loginUser->uid){
				if(!admin_check('thread.check')){
					error('文章不存在或已删除');
				}
			}
        }
		
        $dm->append(['look']);
        
        $uid = $this->loginUser->uid;

        $dm->withAttr('look',function($value, $data) use ($uid){
        	$res = Look::where([
        		['user_id','=',$uid],
        		['type','=','article'],
        		['target_id','=',$data['id']]
        	])->find();
        	if($res){
        		return 1;
        	}else{
        		if($uid==$data['user_id']){
        			return 1;
        		}else{
        			return 0;
        		}
        		
        	}
        	
        });
        
        //刷新访问量
		$dm->inc('visits')->update();
        
        //关于作者
        $user = $dm->users()->find();
        $user->ask = isset($user->datas->ask)?$user->datas->ask:0;
        $user->article = isset($user->datas->article)?$user->datas->answer:0;
        $user->answer = isset($user->datas->answer)?$user->datas->answer:0;
        $user->adopt = isset($user->datas->adopt)?$user->datas->adopt:0;
        $author = $user;
        
        //相关文章
        $alike = byArticle::where('tags','like',array_map(function($value){return "%$value%";},explode(',',$dm->tags)),'OR')->limit(10)->select();
        
        //收藏
        $dm->iscollect = Collect::where('mold','article')->where('user_id',$this->loginUser->uid)->where('source_id',$dm->id)->find();
        
		$data = [
			'article'=> $dm,
			'alikes' => $alike,
			'author' => $author,
			'comment' => $dm->comments(5)
		];
		$seo = new PwSeo();
		$seo->title = $dm->title;
		$seo->description = substr_format(strip_tags($dm->content),80);
		$seo->keywords = $dm->tags;
		$seo->set();
		View::assign($data);
		event('ArticlePage');
        return View::fetch();
	}
	
	//发布文章
    public function post($id = 0)
    {
    	action_check('article.post');
    	if(request()->isPost()){
    		$this->save();
    	}
    	if($id){
    		$dm = byArticle::find($id);
    		if(!$dm){
    			error('文章不存在或已删除');
    		}
    		$data['article'] = $dm;
    	}
    	
    	//分类数组
    	$data['category'] = Category::where('type','article')->where('category_id',0)->select();
		$seo = new PwSeo();
		$seo->title = '发布文章';
		$seo->set();
		View::assign($data);
		event('ArticlePostPage');
        return View::fetch();
    }
    
    //发布文章
    private function save()
    {
    	$id = input('post.id',0,'intval');
    	$title = input('post.title','');
    	$summary = input('post.summary','');//摘要
    	$content = input('post.content','');
    	$category_id = input('post.category',0,'intval');
    	$tags = input('post.tags','');
    	$speak = input('post.speak',0,'intval');//禁止评论
    	$cover = input('post.cover','');//封面
    	
    	//数据验证
    	try {
            $this->validate([
                'title'  => $title,
                'content' => $content,
                'tags' => $tags,
                'category' => Category::where('id',$category_id)->where('type','article')->find()
            ],'\app\wendasns\validate\Article');
        } catch (ValidateException $e) {
            error($e->getError());
        }
        event('ArticlePost');
        
    	try {
            $article = new PwArticle();
            $article->id = $id;
            $article->user_id = $this->loginUser->uid;
            $article->category_id = $category_id;
            $article->title = $title;
            $article->content = $content;
            $article->summary = $summary;
            $article->tags = $tags;
            $article->speak = $speak;
            $article->cover = $cover;
            $dm = $article->save();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功', [], (string)url('wendasns/article/show',$dm));
    }
    
    //删除文章
    public function remove()
    {
    	$id = input('post.id',0,'intval');
    	action_check('article.remove');
    	event('ArticleRemove');
    	try {
            $article = new PwArticle();
            $article->id = $id;
            $article->remove();
        } catch (\think\Exception $e) {
            error($e->getMessage());
        }
    	success('已删除');
    }

    //收藏
    public function collect()
    {
    	if(($dm = $this->article_check()) instanceof Exception){
    		error($dm->getMessage());
    	}
    	$collect = Collect::where('user_id',$this->loginUser->uid)->where('mold','article')->where('source_id',$dm->id)->find();
    	if($collect){
    		error('已收藏');
    	}
    	Collect::create(['user_id'=>$this->loginUser->uid, 'mold'=>'article', 'source_id'=>$dm->id, 'create_time'=>Wend::getTime()]);
    	$dm->inc('collect')->update();
    	$user = User::find($this->loginUser->uid);
    	$user->datas()->inc('collect')->update();
    	success('收藏成功');
    }
    
    //点赞
    public function praise()
    {
    	$id = input('post.id',0,'intval');
    	$dm = byArticle::find($id);
    	if(!$dm || $dm->remove){
    		error('文章不存在或已删除');
    	}
    	
        $sql = [
            ['mode','=','article'],
            ['source_id','=',$id],
        ];
        if($this->loginUser->isLogin){
            $sql[] = ['user_id','=',$this->loginUser->uid];
            $user_id = $this->loginUser->uid;
        }else{
            $sql[] = ['ip','=',$this->request->ip()];
            $user_id = 0;
        }
        $praise = Praise::where($sql)->find();
        if($praise){
            error('你已经点过赞了！');
        }
        Praise::create([
            'user_id'=> $user_id,
            'mode' => 'article',
            'source_id' => $dm->id,
            'ip' => $this->request->ip(),
            'create_time' => Wend::getTime()
        ]);
    	
    	$dm->praise = $dm->praise + 1;
    	$dm->save();
    	$dm->users()->find()->datas()->inc('praise')->update();
    	success('谢谢点赞');
    }

    //评论列表
    public function comment()
    {
    	$id = input('get.id',0,'intval');
    	$dm = byArticle::find($id);
    	if(!$dm){
    		return '';
    	}
    	$comment = Comment::where('types','article')->where('source_id',$dm->id)->where('remove',0)->paginate(1);
		
		return view('/comment',['comment'=>$comment]);
    }

    //回复评论
    public function reply()
    {
    	$id = input('post.id',0,'intval');
    	$rid = input('post.rid',0,'intval');
    	$content = input('post.content','');
    	
    	
    	$dm = Reply::create([
    		'user_id' => $this->loginUser->uid,
    		'reply_id' => $rid,
    		'source_id' => $id,
    		'content' => $content,
    	]);
		$html = View::fetch('reply',['item'=>$dm]);
		success('发表成功',['html'=>$html]);
    }
    
    private function article_check()
    {
    	$id = input('post.id', 0, 'intval');
    	$dm = byArticle::find($id);
    	if(!$dm || $dm->remove==1){
    		return new Exception('文章不存在或已删除');
    	}
    	
    	if($dm->status<>'normal'){
    		return new Exception('文章审核中，禁止任何操作');
    	}
    	return $dm;
    }
}
