<?php
namespace app\wendasns\service;

use app\wendasns\model\Question;
use app\wendasns\model\Category;

class PwQuestion
{
	//获取相关问题
	public static function alike($tagIds, $id, $limit=10){
		$dm = byQuestion::where('id', 'in', function ($query) use ($tagIds) {
            $query->name('topic_list')->where('topic_id', 'in', $tagIds)->where('type', 'question')->field('source_id');
        })->where('id', '<>', $id)->where('state', '=', 'show')->limit($limit)->order('create_time', 'asc')->select();
        return $dm;
	}
    
    //获取问题列表
    public static function get($type='new', $limit=10, $category='all') {
		if($category=='all'){
			$mark = '>';
			$term = 0;
		}else{
			$dm = Category::where('dir_name', $category)->where('type', 'question')->find();
			if(!$dm){
				return [];
			}
			$mark = '=';
			$term = $dm['id'];
		}
		$condition = [
			'price' => [
			    ['reward','>',0]
			],
			'unsolved' => [
			    ['adopt_id','=',0]
			],
			'unanswer' => [
			    ['answer','=',0]
			],
			'solved' => [
			    ['adopt_id','>',0]
			],
			'new' => [],
			'hot' => []
		];
		
		$condition[$type][] = ['remove', '=', 0];
		$condition[$type][] = ['category_id', $mark, $term];
		$order = $type=='hot'?'visits':'create_time';
		$dm = Question::where($condition[$type])->order($order, 'desc')->paginate($limit);
		//返回标签数组
		$dm->withAttr('tags',function($value, $data) {
        	return explode(',', $value);
        });
		return $dm;
	}
	
	public static function query(string $type = 'all', int $limit = 10)
	{
    	$sql[] = ['user_id','=', request()->loginUser->uid];
    	switch ($type){
    		case 'noanswer':
    			$sql[] = ['answer','=',0];
    			break;
    		case 'answer':
    			$sql[] = ['answer','>',0];
    			break;
    		case 'noadopt':
    			$sql[] = ['adopt_id','=',0];
    			break;
    		case 'delete':
    			$sql[] = ['remove','>',0];
    			break;
    		default:
    	}
    	$dm = byQuestion::where($sql)->order('create_time', 'desc')->paginate($limit);
    	return $dm;
	}
}