<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-06-28
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use think\Controller;
use app\common\model\Usergroup as UsergroupModel;
use Request;

class Usergroup extends Base
{
	// 会员组列表
	public function index()
	{
		if(Request::isPost())
		{
			$data = UsergroupModel::withCount('user')->order('point')->hidden(['create_time','update_time'])->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
		return $this->fetch();
	}

	// 添加会员组
	public function add()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			$result = UsergroupModel::create($data,true);
			adminlog(2,'新增('.UsergroupModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		return $this->fetch();
	}

	// 编辑会员组
	public function edit($id)
	{
		$info = UsergroupModel::get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			$result = $info->allowField(true)->save($data);
			adminlog(2,'编辑('.UsergroupModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
		return $this->fetch('',compact('info'));
	}

	// 删除会员组
	public function del()
	{
		if(Request::isPost()) {
			$data = Request::post();
            $group = UsergroupModel::with('user')->get($data['id']);
            if($group->user->isEmpty()) {
            	$result = $group->delete();
            	adminlog(2,'删除('.UsergroupModel::getLastsql().')',$result?1:0);
				if ($result) {
					$this->success(lang('deltrue'));
				} else {
					$this->error(lang('delfalse'));
				}
            } else {
            	$this->error(lang('delfalse'));
            }
		}
	}

	// 数据验证
	private function checkData($data)
	{
		if(!isset($data['list_switch'])) { // 如果不是switch开关操作
			$validate = new \app\admin\validate\Usergroup;
			if(!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}
}