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

class Admin extends Base
{
	// 前置处理
	protected $beforeActionList = [
        'bossAction'  =>  ['only'=>'grouplist,groupadd,groupedit,groupdel,login']
    ];
    protected function bossAction()
    {
    	if(!$this->admininfo['isboss']) $this->error(lang('noauth'));
    }
	// 管理员列表
	public function index()
	{
		if(Request::isPost())
		{
			$limit = Request::post('limit/d');
			$data = AdminModel::when(!$this->admininfo['isboss'],function($query){
				$query->whereAdmingroupId($this->admininfo['admingroup_id']);
			},function($query){
				$query->when(Request::post('groupid'),function($query2){
					$query2->whereAdmingroupId(Request::post('groupid'));
				});
			})->withAttr('sitename',function($value,$data){
				return Site::getFieldById($data['siteids'],'title');
			})->hidden(['password','salt'])->with(['admingroup'])->append(['logindata','sitename'])->order('id')->paginate($limit)->toArray();
			// $data = AdminModel::hasWhere('admingroup',function($query){
			// 	$query->whereIn('Admingroup.id',$this->admininfo['mygroupids']);
			// })->when(Request::post('groupid'),function($query){
			// 	$query->where('admingroup_id',Request::post('groupid'));
			// })->hidden(['password','salt'])->with(['admingroup'])->append(['logindata'])->order('order')->paginate($limit)->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();
			if(!$this->admininfo['isboss']) $data['admingroup_id'] = $this->admininfo['admingroup_id'];
			// 数据验证
			$this->checkAdminData($data);
			$data['salt'] = random();
			$data['password'] = md5(trim($data['password']).$data['salt']);
			$result = AdminModel::create($data,true);
			adminlog(2,'新增('.AdminModel::getLastsql().')',$result?1:0);
			if ($result) {
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		return $this->fetch('');
	}

	// 管理员编辑
	public function edit($id)
	{
		$info = AdminModel::when(!$this->admininfo['isboss'],function($query){
			$query->whereAdmingroupId($this->admininfo['admingroup_id']);
		})->hidden(['create_time','update_time','password'])->get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			if(!$this->admininfo['isboss']) $data['admingroup_id'] = $this->admininfo['admingroup_id'];
			if(!isset($data['list_switch'])) {
				$this->checkAdminData($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,'编辑('.AdminModel::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();
            if($data['id'] !== session('adminid')) {
            	$info = AdminModel::get($data['id'],'adminlog');
				$result = $info->together('adminlog')->delete();
				adminlog(2,'删除('.AdminModel::getLastsql().')',$result?1:0);
				if ($result) {
					$this->success(lang('deltrue'));
				} else {
					$this->error(lang('delfalse'));
				}
            } else {
            	$this->error(lang('delfalse'));
            }
		}
	}

	// 角色列表
	public function grouplist()
	{
		if(Request::isPost()) {
			$data = Admingroup::when(!$this->admininfo['isboss'],function($query){
				$query->whereId($this->admininfo['admingroup_id']);
			})->withCount('admin')->order('id asc')->paginate(Request::post('limit/d'))->toArray();
			return json(['code'=>0,'msg'=>lang('getdatatrue'),'data'=>$data['data'],'count'=>$data['total']]);
		}
		return $this->fetch();
	}

	// 角色添加
	public function groupadd()
	{
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkGroupData($data);
            if(isset($data['rules'])) {
				$data['rules'] =implode(',', $data['rules']);
			}
			$data['pid'] = 1;
			$result = Admingroup::create($data,true);
			if ($result) {
				Cache::clear('admininfo');
				$this->success(lang('addtrue'));
			} else {
				$this->error(lang('addfalse'));
			}
		}
		return $this->fetch('');
	}

	// 角色修改
	public function groupedit($id)
	{
		$info = Admingroup::whereId('<>',$this->admininfo['admingroup_id'])->get($id);
		if(empty($info)) $this->error(lang('norecord'));
		if(Request::isPost()) {
			$data = Request::post();
			$this->checkGroupData($data);
            if(isset($data['rules'])) {
				$data['rules'] = implode(',', $data['rules']);
			}
			$result = $info->allowField(true)->save($data);
			if ($result) {
				Cache::clear('admininfo');
				Cache::clear('adminmenu');
				$this->success(lang('edittrue'));
			} else {
				$this->error(lang('editfalse'));
			}
		}
		return $this->fetch('',compact('info'));
	}

	// 角色删除
	public function groupdel()
	{
		if(Request::isPost()) {
			$data = Request::post();
			if($data['id'] == $this->admininfo['admingroup_id'] || $data['id'] == 1) $this->error(lang('delfalse')); 
            $info = Admingroup::withCount('admin')->get($data['id']);
			if($info->admin_count>0) $this->error(lang('delfalse'));
			$result = $info->delete();
			if ($result) {
				Cache::clear('admininfo');
				$this->success(lang('deltrue'));
			} else {
				$this->error(lang('delfalse'));
			}
		}
	}

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

	// 角色数据验证
	private function checkGroupData($data)
	{
		if(!isset($data['list_switch'])) {
			$validate = new \app\admin\validate\Admingroup;
			if(!$validate->check($data)) {
				$this->error($validate->getError());
			}
		}
	}
}