<?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\Comment;
use app\wendasns\model\Collect;
use app\wendasns\model\Question;
use app\wendasns\model\Answer;
use app\wendasns\model\Article;
use app\wendasns\model\Report;
use app\wendasns\model\ReportLog;
use app\wendasns\model\User;
use app\wendasns\model\Member;
use app\wendasns\model\Fans;
use app\wendasns\model\Notice;
use app\wendasns\service\PwSeo;
use wendasns\facade\Qrcode;
use wendasns\Wend;
use think\helper\Str;
use think\facade\Config;
use think\facade\Filesystem;
use think\facade\Console;

class Common extends WenBaseController
{
	
	private $sharesource = ['weibo'=>'http://v.t.sina.com.cn/share/share.php','qzone'=>'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey'];
	
    public function run()
    {
    	$cm = input('post.cm', '');
    	if(!in_array($cm,['praise','collect','report'])){
    		error('非法操作');
    	}
    	$this->$cm();
    }

    //置顶
    public function top($type='question')
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	if(!admin_check('thread.top')){
    		error('所在用户组没有操作权限');
    	}
    	$id = input('post.id',0,'intval');

    	$class_name = '\\app\\wendasns\\model\\'.ucfirst($type);
    	$dm = $class_name::find($id);
    	if(!$dm){
    		error('帖子不存在');
    	}
    	if($dm->top){
    		$dm->top = 0;
    	}else{
    		$dm->top = 1;
    	}
    	$dm->save();
    	success('操作成功');
    }

    //推荐
    public function recommend($type='question')
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	if(!admin_check('thread.recommend')){
    		error('所在用户组没有操作权限');
    	}
    	$id = input('post.id',0,'intval');

    	$class_name = '\\app\\wendasns\\model\\'.ucfirst($type);
    	$dm = $class_name::find($id);
    	if(!$dm){
    		error('帖子不存在');
    	}
    	if($dm->recommend){
    		$dm->recommend = 0;
    	}else{
    		$dm->recommend = 1;
    	}
    	$dm->save();
    	success('操作成功');
    }

    
    //审核
    public function check($type='question')
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	if(!admin_check('thread.check')){
    		error('所在用户组没有操作权限');
    	}
    	$id = input('post.id',0,'intval');

    	$class_name = '\\app\\wendasns\\model\\'.ucfirst($type);
    	$dm = $class_name::find($id);
    	if(!$dm){
    		error('帖子不存在');
    	}
    	if($dm->status=='check'){
    		$dm->status = 'normal';
    		$dm->save();
    	}
    	success('操作成功');
    }
    
    //点赞
    public function praise()
    {
    	$co = input('post.co', '', 'ucfirst');
    	$type = input('post.type', 'up');
    	$id = input('post.id', 0, 'intval');
    	if(!in_array($co,['Answer','Reply','Comment','Article'])){
    		error('非法操作');
    	}
    	if($type=='up'){
    		$item = 'praise';
    	}
    	$class_name = '\\app\\wendasns\\model\\'.$co;
    	$class_name::where('id', $id)->inc($item)->update();
    	success('操作成功');
    }
    
    //搜索
    public function search($type='question',$wd='',$page=1)
    {
    	$_GET['page'] = $page;
    	$limit = input('get.limit',2,'intval');
    	$class_name = '\\app\\wendasns\\model\\'.ucfirst($type);
		if($wd){
			$sql[] = ['title','Like',"%{$wd}%"];
		}else{
			$sql[] = ['title','=',''];
		}
    	$dm = $class_name::where($sql)->order('create_time', 'desc')->paginate(['query'=>['wd'=>$wd,'type'=>$type,'_s'=>'wendasns/common/search'],'list_rows'=>$limit]);
		$dm->withAttr('title',function($value, $data)use($wd){
        	return str_replace($wd,'<font color="red">'.$wd.'</font>',$value);
        });
		$dm->withAttr('content',function($value, $data)use($wd){
			$html = strip_tags($value);
			$html = substr_format($html,90);
        	return str_replace($wd,'<font color="red">'.$wd.'</font>',$html);
        });
    	$title = empty($wd)?'':' - '.$wd;
		$seo = new PwSeo();
		$seo->title = '搜索'.$title;
		$seo->set();
		return view('search',['logs'=>$dm,'type'=>$type,'wd'=>$wd]);
    }
    
    //举报
    public function report()
    {
    	$id = input('post.id',0,'intval');
    	$type = input('post.type','');
    	$reason = input('post.reason',0,'intval');//举报原因，0表示其它
    	$content = input('post.content','');//说明
    	$report_id = 0;
    	$dm = null;
    	switch ($type){
    		case 'question':
    			$dm = Question::find($id);
    			break;
    		case 'answer':
    			$dm = Answer::find($id);
    			break;
    		case 'article':
    			$dm = Article::find($id);
    			break;
    		case 'comment':
    			$dm = Comment::find($id);
    			break;
    		default:
    	}
    	
    	if(!$dm){
    		error('举报的帖子不存在');
    	}
    	
    	if($reason){
    		$reportRow = Report::find($reason);
    		if(!$reportRow){
    			error('举报的原因不存在');
    		}
    	}else{
    		if(empty($content)) error('请填写举报说明');
    	}
    	
    	$logs = ReportLog::where([
    		['source_id','=',$id],
    		['type','=',$type]
    	])->find();
    	
    	if($logs){
    		
    		if(!$this->loginUser->isLogin){
    			$sql[] = ['ip','=',request()->ip()];
    		}
    		$sql[] = ['user_id','=',$this->loginUser->uid];
    		$reportUserRow = $logs->users()->where($sql)->find();
    		if($reportUserRow){
    			success('您已经举报过，请耐心等待我们的处理！',[],true);
    		}
    		
    	}else{
    		$logs = ReportLog::create([
    			'source_id' => $id,
    			'type' => $type,
    			'create_time' => Wend::getTime()
    		]);
    	}
    	
    	$report = $logs->users()->save([
    		'rlog_id' => $logs->id,
    		'report_id' => isset($reportRow->id)?$reportRow->id:0,
    		'content' => $content,
    		'user_id' => $this->loginUser->uid,
    		'ip' => request()->ip(),
    		'create_time' => Wend::getTime()
    	]);
    	if($report->id){
    		$logs->Inc('num')->update(['update_time'=>Wend::getTime()]);
    		success('您的举报已提交，我们会尽快处理！',[],true);
    	}
    	error('举报失败');
    }

    //关注
    public function follow()
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	$uid = input('post.uid',0,'intval');

    	if($uid==$this->loginUser->uid){
    		error('禁止关注自己');
    	}
    	
    	$dm = User::find($uid);
    	if(!$dm){
    		error('关注的用户不存在');
    	}
    	$fans = Fans::where('user_id',$this->loginUser->uid)->where('target_id',$uid)->find();
		if($fans){//取消关注
			$fans->delete();
			$fans->users()->find()->datas()->dec('follow')->update();
			$dm->datas()->dec('fans')->update();
			success('已取消关注');
		}else{
			$fans = Fans::create([
				'user_id'=>$this->loginUser->uid,
				'target_id'=>$uid
			]);
		}
		$fans->users()->find()->datas()->inc('follow')->update();
		$dm->datas()->inc('fans')->update();
    	success('关注成功');
    }

    //头像
    public function portrait($id=0)
    {
    	$suffix = request()->ext();
    	$path = root_path('runtime'.DIRECTORY_SEPARATOR.'ucentre'.DIRECTORY_SEPARATOR.'portrait').md5((string)$id).'.'.$suffix;
    	if(file_exists($path)){
    		$content = @file_get_contents($path);
    	}else{
    		error('图片不存在');
    	}
    	return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/'.$suffix);
    }

    //收藏
    public function collect()
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	$type = input('post.type','');
    	$id = input('post.id',0,'intval');
    	$dm = null;
    	switch ($type){
    		case 'question':
    			$dm = Question::find($id);
    			break;
    		case 'article':
    			$dm = Article::find($id);
    			break;
    		default:
    	}
    	if(!$dm){
    		error('收藏的帖子不存在');
    	}
    	$collect = Collect::where([
    		['user_id','=',$this->loginUser->uid],
    		['type','=',$type],
    		['source_id','=',$id]
    	])->find();
    	
    	if($collect){
    		error('您已收藏');
    	}
    	$collect = Collect::create(['user_id'=>$this->loginUser->uid, 'type'=>$type, 'source_id'=>$id]);
    	if(isset($collect->id)){
    		success('收藏成功');
    	}
    	error('收藏失败');
    }
    
    //分享
    public function share($type='weibo')
    {
    	$uri = input('get.uri','');
    	$title = input('get.title','');
    	$_G['url'] = $uri;
    	$_G['title'] = $title;
    	$pic = request()->domain().'/static/wendasns/images/wdlogo.png';
    	
    	switch ($type){
    		case 'weibo':
    			$_G['pic'] = $pic;
    			$url = 'http://v.t.sina.com.cn/share/share.php?'.http_build_query($_G);
    			break;
    		case 'qzone':
    			$_G['pics'] = $pic;
    			$url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?'.http_build_query($_G);
    			break;
    		default:
    			error('参数不正确');
    	}
    	
    	return redirect($url);
    }

    public function qrcode()
    {
    	$url = input('get.url','');
    	Qrcode::png($url,false,'L',3);

    }
    
    //上传图片附件
    public function upload($type='')
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	
    	$files = request()->file();
    	if(isset($files['upfile'])){
    		$file = $files['upfile'];
    	}else{
    		$file = $files['file'];
    	}

    	$file_name = Str::random(6);
    	$suffix = substr($file->getOriginalName(),-3);
    	$file_name = $file_name.$file->getOriginalName();
    	$file_name = md5($file_name);
	    
    	$path = runtime_path();
    	Filesystem::getAdapter()->setPathPrefix($path);
    	Filesystem::putFileAs($type, $file, $file_name.'.'.$suffix);
    	
    	$src = (string)url('wendasns/api/image', ['type'=>$type,'name'=>$file_name], $suffix, true);
    	$data = [
    		'original'=>$file->getOriginalName(),
    		'size'=>$file->getSize(),
    		'state'=>'SUCCESS',
    		'title'=>$file_name.'.'.$suffix,
    		'type'=>'.'.$suffix,
    		'url'=>$src,
    		'data'=>['src'=>$src, 'title'=>''],
    		'code'=>0,
    		'msg'=>'上传成功'
    	];
    	return json($data);
    }
    
    //修改用户签名
    public function usersign()
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	$sign = input('post.sign','');
    	$member = Member::where('user_id',$this->loginUser->uid)->find();
    	$member->usersign = $sign;
    	$member->save();
    	success('操作完成',[],true);
    }
    
    public function notice()
    {
    	if(!$this->loginUser->isLogin){
    		error('请登录后再操作');
    	}
    	$id = input('post.id',0,'intval');
    	$dm = Notice::find($id);
    	if(!$dm){
    		error('消息不存在');
    	}
    	if($dm->status){
    		error('消息已读');
    	}
    	$dm->status = 1;
    	$dm->save();
    	$dm->users->datas()->dec('notices')->update();
    	success('操作完成');
    }
}