<?php
namespace app\wendasns\service;

use app\wendasns\model\Answer;
use app\wendasns\model\Question;
use app\wendasns\model\User;
use app\wendasns\model\Category;
use app\wendasns\service\PwSrv;
use wendasns\Wend;
use think\Exception;
use think\helper\Str;

class PwAsk
{
	public $id = 0;
	
	//提问
	public function save()
	{
		//是否审核
    	$status = configure('wenda.postCheck') ? 'check' : 'normal';
    	$create_time = Wend::getTime();
    	$data = [
    		'user_id' => $this->uid,
    		'category_id' => $this->cid,
    		'title' => $this->title,
    		'content' => $this->content,
    		'tags' => $this->setTags($this->tags),
    		'ip' => request()->ip(),
    		'create_time' => $create_time,
    		'status' => $status,
    		'client' => Wend::getClient()
    	];
		
    	$dm = Question::create($data);
    	if($dm->id){
    		$dm->kid = getKid($dm->id, $dm->create_time);
    		$dm->save();
    		//设置标签
            PwSrv::setTags($dm->id, $dm->tags);
            
    		//更新用户数据
    		$dm->users()->find()->datas()->inc('ask')->update();
    		//记录用户行为
    		$dm->users()->find()->behaviors()->save(['source_id'=>$dm->id,'action'=>'ask','create_time'=>$create_time]);
    		
            //钩子
    	    event('EndQuestionPost',$dm);
    	    $this->id = $dm->id;
    		return $dm;
    	}else{
    		throw new Exception('提问失败');
    	}
	}

    //问题关闭，禁止回答
    public function close()
    {
    	$dm = Question::find($this->id);
    	if(!$dm){
    		throw new Exception('问题不存在');
    	}
    	if(!admin_check('thread.question.close')){
    		if(request()->loginUser->uid<>$dm->user_id){
    			throw new Exception('所在用户组没有操作权限');
    		}
    		
	    	if($dm->remove){
	    		throw new Exception('问题已删除');
	    	}
	    	if($dm->status<>'normal'){
	    		throw new Exception('问题正在审核中，禁止操作');
	    	}
    	}

    	$dm->close = 1;
    	$dm->save();
    	event('EndQuestionClose',$dm);
    }
    
	//采纳
	public function adopt()
	{
		$dm = Question::find($this->id);
    	if(!$dm){
    		throw new Exception('问题不存在');
    	}

    	$answer = Answer::find($this->aid);
    	if(!$answer){
    		throw new Exception('回答不存在');
    	}
    	
    	if(!admin_check('thread.question.adopt')){
    		if(request()->loginUser->uid<>$dm->user_id){
    			throw new Exception('所在用户组没有操作权限');
    		}
	    	if($dm->remove){
	    		throw new Exception('问题已删除');
	    	}
	    	if($dm->status<>'normal'){
	    		throw new Exception('问题正在审核中，禁止采纳');
	    	}
	    	if($dm->adopt_id>0){
	    		throw new Exception('问题已采纳');
	    	}
	    	if($answer->remove){
	    		throw new Exception('回答已删除');
	    	}
    	}
    	
    	$dm->adopt_id = $this->aid;
    	$dm->adopt_thank = $this->content;
    	$dm->save();
    	$dm->answers()->inc('adopt')->update();
    	
    	//记录提问用户行为
    	$dm->users()->find()->behaviors()->save(['source_id'=>$dm->id,'action'=>'adopt','create_time'=>Wend::getTime()]);
    	
    	$user = User::find($answer->user_id);
    	if($user){
    		//更新被采纳者的数据
    		$user->datas()->inc('adopt')->update();
    		
    		//给被采纳用户发送通知
    		PwSrv::sendNotice($user->id, "{$dm->users->username}采纳了您的回答", $answer->content);
    		$user->datas()->inc('notices')->update();
    	}

    	event('EndAdopt',$dm);
	}

	//问题补充
	public function update()
	{
    	$dm = Question::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('问题正在审核中，禁止编辑');
	    	}
	    	if($dm->adopt_id>0){
	    		throw new Exception('问题已采纳，禁止编辑');
	    	}
    	}

    	$status = configure('wenda.askCheck') ? 'check' : 'normal';
    	$dm->content = $this->content;
    	$dm->status = $status;
		$dm->update_time = Wend::getTime();
		$dm->save();
		event('EndQuestionEdit',$dm);
	}
	
	//删除问题
	public function remove()
	{
    	$dm = Question::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('问题已删除');
	    	}
	    	if($dm->status<>'normal'){
	    		throw new Exception('问题正在审核中，禁止删除');
	    	}
    	}

    	$dm->remove = 1;
    	$dm->save();
    	$dm->users->datas()->dec('ask')->update();
        event('EndQuestionRemove',$dm);
	}
	
    //获取问题列表
    public static function getAll($type='new', $category='all', $page=1, $limit=0)
    {
    	$limit || $limit = configure('page.pageQuestion', 10);

		if($category=='all'){
			$mark = '>';
			$term = 0;
		}else{
			$dm = Category::where([
				['type','=','question'],
				['dir_name','=',$category],
				['status','=',1],
			])->find();
			if(!$dm){
				return [];
			}
			$mark = 'in';
			$term = categoryQuery($dm);
		}
		$sql = [
			'unsolved' => [
			    ['adopt_id','=',0]
			],
			'unanswer' => [
			    ['answer','=',0]
			],
			'solved' => [
			    ['adopt_id','>',0]
			],
			'new' => [],
			'hot' => [],
			'top' => [
				['top','>',0]
			],
			'recommend'=>[
				['recommend','>',0]
			]
		];
		if($type!='top') $sql[$type][] = ['top', '=', 0];
		$sql[$type][] = ['remove', '=', 0];
		$sql[$type][] = ['category_id', $mark, $term];
		$order = $type=='hot'?'visits':'create_time';
		$dm = Question::where($sql[$type])->order($order, 'desc')->paginate(['list_rows'=>$limit,'query'=>['page'=>$page,'cname'=>$category,'type'=>$type,'_s'=>'wendasns/question/index']]);
		return $dm;
	}
	
	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 '';
    	}
	}
}