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

class User extends Base
{
	// 会员列表
	public function index()
	{
		if(Request::isPost())
		{
			$searchtype = Request::post('searchtype');
			$searchkey = Request::post('searchkey');
			$data = UserModel::when((!empty($searchtype) || $searchtype === '0'),function($query) use($searchtype){
				$query->whereUsergroupId($searchtype);
			})->where(function($query) use($searchkey){
				if($searchkey) {
					$query->whereUsername($searchkey)->whereOrMobile('=',$searchkey);
				}
			})->hidden(['password','salt'])->order('id desc')->append(['usergroup'])->paginate(input('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);
			$data['salt'] = random();
			$data['password'] = md5(trim($data['password']).$data['salt']);
			$result = UserModel::create($data,true);
			adminlog(2,'新增('.UserModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		return $this->fetch();
	}

	// 编辑会员
	public function edit($id)
	{
		$info = UserModel::get($id)->hidden(['create_time','update_time','password']);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkData($data);
			if(!isset($data['password']) || !trim($data['password'])) {
				unset($data['password']); // 密码留空不修改
			} else {
				$salt = $info['salt'];
				$data['password'] = md5(trim($data['password']).$salt);
			}
			$result = $info->allowField(true)->save($data);
			adminlog(2,'编辑('.UserModel::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();
			$result = UserModel::destroy($data['id']);
			adminlog(2,'删除('.UserModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

	// 数据验证
	private function checkData($data)
	{
		if(!isset($data['list_switch'])) { // 如果不是switch开关操作
			$validate = new \app\admin\validate\User;
			if(isset($data['id'])) { // 如果是修改 用编辑场景
				if(!$validate->scene('edit')->check($data)) {
					$this->error($validate->getError());
				}
			} else {
				if(!$validate->check($data)) {
					$this->error($validate->getError());
				}
			}
		}
	}
}