<?php

namespace app\wendasns\service;

use app\wendasns\model\Question;
use app\wendasns\model\Category;
use app\wendasns\model\Allow;
use app\wendasns\model\User;
use app\wendasns\model\Notice;
use wendasns\Wend;

class PwSrv
{
	//权限发布权限，包括账号状态、所在用户组权限
	public static function checkAction(int $uid, string $keys)
	{
		$dm = User::find($uid);
		if($dm->status==0){
			return new \think\Exception('账号审核中，禁止操作');
		}
    	$rkey = strtr($keys,['.'=>'_']);
    	$dm = Allow::where('group_id',$dm->group_id)->where('rkey',$rkey)->find();
    	if(!$dm || $dm->rvalue==0){
    		return new \think\Exception('所在用户组没有操作权限');
    	}
        return true;
	}
	
	//获取相关问题
	public static function similar_question($id, $tags, $limit=10)
	{
		$result = Question::where('tags','like',array_map(function($value){return "%$value%";},$tags),'OR')->where('id','<>',$id)->order('create_time','desc')->limit($limit)->select();
		return $result;
	}
	
	public static function getCategoryList($type=0) {
		if($type==0){
			$result = \app\main\model\Category::select();
		}else{
			$result = \app\main\model\Category::where('type',$type)->select();
		}
		return $result;
	}
	
	public static function getCreditList($open=1) {
		if($open<0){
			$result = \app\main\model\Credit::select();
		}else{
			$result = \app\main\model\Credit::where('open',$open)->select();
		}
		return $result;
	}
	
	public static function updateArticleVisits($id,$number=0) {
		if($number>0){
			\app\main\model\Article::where('id',$id)->visits($number)->save();
		}else{
			\app\main\model\Article::where('id',$id)->inc('visits')->update();
		}
	}
	
	public static function addArticleTag($id,$tag){
		if(!is_array($tag)){
			return false;
		}
		
		foreach($tag as $v){
			$topic_id = '';
			$row = \app\main\model\Tag::where('name',$v)->find();
			if($row){
				$topic_id = $row['id'];
			}else{
				$Tags = new \app\main\model\Tag;
				$Tags->name = $v;
				$Tags->save();
				$topic_id = $Tags->id;
			}
			if($topic_id){
				$data = ['topic_id' => $topic_id, 'type' => 'article', 'source_id'=>$id];
				\think\facade\Db::name('topic_list')->insert($data);
			}

		}
	}
	
	public static function getUserInfoById($uid){
		$user = \app\main\model\User::find($uid);
		$u = json_decode($user,true);
		$user_data = \think\facade\Db::name('user_data')->where('uid',$uid)->find();
		foreach($user_data as $k=>$v){
			$u[$k] = $v;
		}
		$user_info = \think\facade\Db::name('user_info')->where('uid',$uid)->find();
		foreach($user_info as $k=>$v){
			$u[$k] = $v;
		}
		return $u;//array_merge((array)$row,(array)$user_data,(array)$user_info);
	}
	
	//相关文章/问题
	public static function toListByTag($type,$tagIds,$id){
		if($type=='article'){
			$m = new \app\main\model\Article;
		}else{
			$m = new \app\main\model\Question;
		}
		$row = $m::where('id', 'in', function ($query) use ($tagIds, $type) {
            $query->name('topic_list')->where('topic_id', 'in', $tagIds)->where('type', $type)->field('source_id');
        })->where('id', '<>', $id)->where('state', '=', 'show')->limit(10)->order('create_time', 'asc')->select();
        return $row;
	}

    //获取问题
    public static function getQuestionList($type='new', $limit=10, $category='all') {
		if($category=='all'){
			$mark = '>';
			$term = 0;
		}else{
			$dm = Category::where('dir_name', $category)->where('type', 1)->find();
			if(!$dm){
				//$this->showError('分类不存在');
			}
			$mark = '=';
			$term = $dm['id'];
		}
		$condition = [
			'price' => [
			    ['reward','>',0]
			],
			'unsolved' => [
			    ['adopt_id','=',0]
			],
			'unanswer' => [
			    ['answer','=',0]
			],
			'solved' => [
			    ['adopt_id','>',0]
			],
			'new' => [],
			'hot' => []
		];
		
		$condition[$type][] = ['category_id', $mark, $term];
		$order = $type=='hot'?'visits':'create_time';
		$logs = Question::where($condition[$type])->order($order, 'desc')->paginate($limit);
		//返回标签数组
		$logs->withAttr('tags',function($value, $data) {
        	return explode(',', $value);
        });
		return $logs;
	}
	
	//获取热门文章
	public static function getHotArticle($number=1)
	{
		$row = \app\main\model\Article::limit($number)->order('visits', 'desc')->select();
		return $row;
	}
	
	//获取热门标签
	public static function getHotTag($number=10)
	{
		//$row = \app\main\model\Tag::limit($number)->order('visits', 'desc')->select();
		$r = \think\facade\Db::name('topic_list')->field('topic_id,COUNT(topic_id) num')->group('topic_id')->order('num', 'desc')->select();
		$aa = [];
		foreach($r as $v){
			$aa[] = $v['topic_id'];
		}
		$row = \app\wendasns\model\Topic::where('id', 'in', $aa)->limit($number)->select();
		return $row;
	}
	
	//获取推荐专家
	public static function getHotEexpert($number=1)
	{
		//$row = \app\main\model\Tag::limit($number)->order('visits', 'desc')->select();
		return [];
	}
	
	//检查是否有禁用词
	public static function safeUserName($value)
	{
		$securityBanUsername = configure('register.disableName', '');
		$arr = explode(',',$securityBanUsername);
		$regular = implode('|', array_map('preg_quote', $arr));
		if(preg_match("/$regular/i", $value)){
			return true;
		}
		return false;
	}
	
	//设置内链
	public static function setLink($value)
	{
		$string = $value;
		$row = \app\wendasns\model\Links::where('status', 1)->where('type', 'inside')->select();
		foreach($row as $v){
			if(strpos($string, $v->keyword) !== false){//存在关键词
				$url = '<a href="'.$v->url.'" title="'.$v->keyword.'">'.$v->keyword.'</a>';
				$string = str_replace($v->keyword, $url, $string); // 正则查找然后替换
			}
			
		}
		return $string;
	}
	
	//检查敏感词
	public static function limitWords()
	{
		return false;
	}
	
	//设置标签
	public static function setTags($id, $tags, $type='question')
	{
		if(empty($tags)) return false;
		$tags_array = explode(',', $tags);
		$tags_array = array_unique($tags_array);//函数移除数组中的重复的值
		$topic_list = [];
		$dm = \app\wendasns\model\Topic::where('name','in',$tags_array)->select();
		foreach($dm as $v){
			$key = array_search($v->name, $tags_array);//在数组中查找一个键值
			if($key!==false){
				unset($tags_array[$key]);
				$topic_list[] = ['topic_id'=>$v->id,'type'=>$type,'source_id'=>$id];
			}
		}
		$topic_logs = array_map(function($value){
			$row = @file_get_contents('http://open.phalapi.net/api/admin.php?s=Admin.Pinyin.Convert&text='.urlencode($value));
			$data = json_decode($row,1);
			$alias = '';
			if(isset($data['data']['pinyin'])){
				$alias = str_replace(' ','',$data['data']['pinyin']);
			}
			return ['name'=>$value,'alias'=>$alias];
		}, $tags_array);
		if($topic_logs){
			$topic = new \app\wendasns\model\Topic;
			$topic_add_row = $topic->saveAll($topic_logs);
			foreach($topic_add_row as $v){
				$topic_list[] = ['topic_id'=>$v->id,'type'=>$type,'source_id'=>$id];
			}
		}
		
		if($topic_list){
			$topiclist = new \app\wendasns\model\TopicList;
			$topiclist->saveAll($topic_list);
		}
	}
	
	//获取标签列表
	public static function getTags($limit=30)
	{
		
		if(!is_numeric($limit)){
			$inarr = explode(',',$limit);
			$dm = \app\wendasns\model\Topic::where('name', 'in', $inarr)->select();
			return $dm;
		}
		$row = \app\wendasns\model\TopicList::field('topic_id,COUNT(topic_id) num')->group('topic_id')->order('num', 'desc')->limit($limit)->select();
		
		$inarr = array_map(function($value){
			return $value['topic_id'];
		},$row->toArray());

		$list = \app\wendasns\model\Topic::where('id', 'in', $inarr)->select();
		return $list;

	}
	
	//发送通知
	public static function sendNotice(int $uid, string $title, string $content)
	{
		Notice::create([
			'user_id' => $uid,
    		'title' => $title,
    		'content' => $content,
    		'create_time' => Wend::getTime()
    	]);
	}
}
