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

use app\admin\AdminBaseController;
use app\wendasns\model\Notice as byNotice;
use app\wendasns\model\Group;
use app\wendasns\model\Member;
use app\wendasns\model\User;
use think\facade\Request;

class Notice extends AdminBaseController
{
	
    public function index()
    {
    	$dm = Group::select();
		return view('index',['group'=>$dm]);
    }

    public function list()
    {
    	$limit = input('get.limit',20,'intval');
    	$dm = byNotice::order('create_time','desc')->paginate($limit);
    	foreach($dm as $k=>$v){
    		$dm[$k]->username = $v->users->username;
    	}
		$data = $dm->toArray();
		success('ok', $data['data'], ['count'=>$data['total']]);
    }

	public function add()
	{
		$type = input('post.type',0,'intval');
		$groupid = input('post.group',0,'intval');
		$username = input('post.username','');
		$title = input('post.title','');
		$content = input('post.content','');

    	if($type){
    		$group = Group::find($groupid);
    		if(!$group){
    			error('用户组不存在');
    		}
    		$dm = Member::where('group_id',$group)->field('user_id')->select();
    	}else{
    		$ar = explode(' ',$username);
    		$dm = User::where('username','in',$ar)->field('id as user_id')->select();
    	}
		$dm->append(['title','content']);
		$dm->withAttr('title',function($value, $data)use($title){
			return $title;
		});
		$dm->withAttr('content',function($value, $data)use($content){
			return $content;
		});
		$list = $dm->toArray();
		if($list){
			$notice = new byNotice;
			$notice->saveAll($list);
		}
		success('操作成功');
    }
    
	public function edit()
	{
		$id = input('post.id',0,'intval');
		
    	$dm = byNotice::find($id);
		if(!$dm){
			error('通知不存在');
		}
		$data = Request::only(['title','content','create_time','status']);
		isset($data['create_time']) && $data['create_time'] = strtotime($data['create_time']);
		$dm->save($data);
		success('操作成功');
    }
    
    public function remove()
    {
    	$id = input('post.id',[]);
    	if(is_array($id)){
    		byNotice::destroy($id);
    	}
    	success('操作成功');
    }
}