<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
namespace app\wendasns\admin;

use app\admin\AdminBaseController;

use app\wendasns\model\Answer as byAnswer;
use app\wendasns\model\User;

class Answer extends AdminBaseController
{

	public function index()
	{
		return view();
	}
	
	public function list()
	{
		$limit = input('get.limit',20,'intval');
		$id = input('get.id',0,'intval');
		$keyword = input('get.keyword','');
		$username = input('get.username','');
		$min_time = input('get.min_time','');
		$max_time = input('get.max_time','');
		$status = input('get.status','');
		
		$sql = [];
		if($keyword){
			$sql[] = ['content','like',"%{$keyword}%"];
		}
		if($username){
			$user = User::where('username',$username)->find();
			if($user){
				$sql[] = ['user_id','=',$user->id];
			}else{
				$sql[] = ['user_id','=',0];
			}
		}

		if($min_time){
			$mintime = strtotime($min_time);
			$sql[] = ['create_time','>',$mintime];
		}
		if($max_time){
			$maxtime = strtotime($max_time);
			$sql[] = ['create_time','<',$maxtime];
		}
		if($status){
			$sql[] = ['status','=',$status];
		}
		if($id){
			$sql[] = ['id','=',$id];
		}
		$dm = byAnswer::where($sql)->order('create_time','desc')->paginate($limit);
		foreach($dm as $k=>$v){
			$dm[$k]->title = isset($v->questions->title)?$v->questions->title:'';
			$dm[$k]->username = isset($v->users->username)?$v->users->username:'';
			$dm[$k]->content = strip_tags($v->content);
		}
        $data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }
    
    //编辑
    public function edit()
	{
		if(!request()->isPost()){
			$id = input('get.id',0,'intval');
			$dm = byAnswer::find($id);
			return view('edit',['data'=>$dm]);
		}
		$post = input('post.');
		$post['create_time'] = strtotime($post['create_time']);
		byAnswer::update($post);
		success('操作完成');
    }
    
    //删除
    public function remove()
	{
		$id = input('post.id', []);
		if(is_array($id)){
			foreach($id as $v){
				byAnswer::update(['remove'=>1, 'id'=>$v]);
			}
		}
		success('操作完成');
    }
    
    //彻底删除
    public function del()
	{
		$id = input('post.id', []);
		if(is_array($id)){
			byAnswer::destroy($id);
		}
		success('操作完成');
    }
    
    //审核通过
    public function check()
	{
		$id = input('post.id', []);
		if(is_array($id)){
			foreach($id as $v){
				byAnswer::update(['status'=>'normal', 'id'=>$v]);
			}
		}
		success('操作完成');
    }
}