<?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\model\Question as byQuestion;
use app\wendasns\model\Category;
use app\wendasns\model\Answer;
use app\wendasns\model\Report;
use app\wendasns\model\Seo;
use app\wendasns\model\User;
use app\wendasns\service\PwSeo;
use app\wendasns\service\PwAsk;
use app\wendasns\model\Collect;
use app\wendasns\service\PwSrv;
	
use wendasns\Wend;
use think\Exception;
use think\App;
use think\facade\Route;
use think\facade\View;

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

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

		$typear = ['new'=>'最新','hot'=>'热门','unsolved'=>'未解决','unanswer'=>'未回答','solved'=>'已解决'];
		$pages = $page>1?' - 第'.$page.'页':'';
		
		$logs = PwAsk::getAll($type, $cname, $page);
		
		$data = [
			'category' => $category,
			'logs' => $logs,
			'type' => $type,
			'categoryname' => $cname
		];
		
		$dm = Seo::where('type','question')->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('QuestionListPage');
        return View::fetch();
    }

    //问题详情页
	public function show($id=0, $kid='', $category='')
	{
		
		if($kid){
			$dm = byQuestion::getByKid($kid);
		}else{
			$dm = byQuestion::find($id);
		}
		
		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('问题不存在或已经失效');
				}
			}
		}
		
		//分页大小
		$limit = configure('page.pageAnswer', 10);
        
		//刷新访问量
		$dm->inc('visits')->update();
        
        
		//最佳答案
		$dm->adopt = $dm->answers()->where([
			['id','=',$dm->adopt_id],
			['remove','=',0],
			['status','=','normal'],
			['user_id','<>',$this->loginUser->uid],
		])->find();

		//回答列表
		$answer = $dm->answers()->where([
			['id','<>',$dm->adopt_id],
        	['remove','=',0],
        	['user_id','<>',$this->loginUser->uid],
        	['status','=','normal']
		])->order('create_time', 'desc')->paginate(5);

        //我的回答
        $dm->isanswer = $dm->answers()->where('user_id',$this->loginUser->uid)->find();
        if($dm->isanswer){
        	if($answer->total()>0){
		        foreach($answer as $k=>$v){
		        	$answer[$k+1] = $v;
		        	if($k==0){
		        		$answer[$k] = $dm->isanswer;
		        	}
		        }
        	}else{
        		$answer[0] = $dm->isanswer;
        	}
        }
        
        //相关问题
        $alike = byQuestion::where('tags','like',array_map(function($value){return "%$value%";},explode(',',$dm->tags)),'OR')->where('id','<>',$dm->id)->order('create_time','desc')->limit(10)->select();
        
        //收藏
        $dm->iscollect = Collect::where('mold','question')->where('user_id',$this->loginUser->uid)->where('source_id',$dm->id)->find();
        
		$data = [
			'question' => $dm,
			'answer' => $answer,
			'alike' => $alike,
		];
		$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('QuestionPage');
		return View::fetch();
	}
	
	//提问页面
    public function post()
    {
    	action_check('question.post');
    	if(request()->isPost()){
    		$this->ask();
    	}
    	$category = Category::where('type','question')->where('status',1)->where('category_id',0)->select();
		$seo = new PwSeo();
		$seo->title = '提问';
		$seo->set();
		View::assign(['category'=>$category]);
		event('QuestionPostPage');
    	return View::fetch();
    }

    //问题关闭，禁止回答
    public function close()
    {
    	$id = input('post.id',0,'intval');
        try {
        	$question = new PwAsk();
            $question->id = $id;
            $question->close();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功',[],true);
    }
    
    //采纳
    public function adopt()
    {
    	$qid = input('post.id',0,'intval');
    	$aid = input('post.aid',0,'intval');
    	$content = input('post.content','','wendasns\facade\Filter::cleanHtml');//采纳评语
    	action_check('question.adopt');
    	event('Adopt');
        try {
        	$question = new PwAsk();
        	$question->id = $qid;
        	$question->aid = $aid;
            $question->content = $content;
            $question->adopt();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功',[],true);
    }

    //修改问题
    public function edit()
    {
    	$qid = input('post.id',0,'intval');
    	$content = input('post.content','','');
    	action_check('question.edit');
    	event('QuestionEdit');
        try {
        	$question = new PwAsk();
        	$question->id = $qid;
            $question->content = $content;
            $question->update();
        } catch (\think\Exception $e) {
            error($e->getMessage());
        }
        success('操作成功',[],true);
    }
    
    //删除
    public function remove()
    {
    	$qid = input('post.id',0,'intval');
    	action_check('question.remove');
    	event('QuestionRemove');
        try {
        	$question = new PwAsk();
        	$question->id = $qid;
            $question->remove();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功',[],true);
    }
    
    //收藏
    public function collect()
    {
    	$id = input('post.id',0,'intval');
    	$dm = byQuestion::find($id);
    	if(!$dm){
    		error('问题不存在');
    	}
    	$collect = Collect::where('user_id',$this->loginUser->uid)->where('mold','question')->where('source_id',$id)->find();
    	if($collect){
    		error('已收藏');
    	}
    	Collect::create(['user_id'=>$this->loginUser->uid, 'mold'=>'question', 'source_id'=>$id, 'create_time'=>Wend::getTime()]);
    	$dm->inc('collect')->update();
    	$user = User::find($this->loginUser->uid);
    	$user->datas()->inc('collect')->update();
    	success('收藏成功');
    }
    
    //回答列表
    public function answer()
    {
    	$id = input('get.id',0,'intval');
    	$dm = byQuestion::find($id);
    	$answer = $dm->answers()->where([
			['id','<>',$dm->adopt_id],
			['status','=','normal'],
			['remove','=',0]
		])->order('create_time', 'desc')->paginate(5);
		
		return view('/answer',['question'=>$dm,'answer'=>$answer]);
    }
    
    //提问
    private function ask()
    {
    	$title = input('post.title','');//标题
    	$content = input('post.content','');//问题描述
    	$category_id = input('post.category',0,'intval');//分类
    	$tags = input('post.tags','');//标签

        //验证数据，包括敏感词
        try {
            $this->validate([
                'title'  => $title,
                'tags' => $tags,
                'content' => $content,
                'category' => Category::where('id',$category_id)->where('type','question')->find()
            ],'\app\wendasns\validate\Question');
        } catch (\think\exception\ValidateException $e) {
            error($e->getError());
        }
        
        event('QuestionPost');
        try {
        	$question = new PwAsk();
            $question->uid = $this->loginUser->uid;
            $question->cid = $category_id;
            $question->title = $title;
            $question->content = $content;
            $question->tags = $tags;
            $dm = $question->save();
        } catch (Exception $e) {
            error($e->getMessage());
        }
    	
    	success('操作成功', [], (string)url('wendasns/question/show',$dm));
    }

}