<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller\bbfxshop;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\model\Tree;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use fast\Random;
use think\Validate;


class Auth extends Base
{
    protected $initConfigFlag = false;
    protected $model = null;
    protected $childrenGroupIds = [];
    public function _initialize(){
        parent::_initialize();
        $this->model = model('Admin');
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
    }
    
    public function getAuthList(){
        $uid = $this->auth->id;
        // $uid = 3;
        
        $auths = \app\common\model\bbfxshop\Auth::getAuthList($uid);
        
        __success("操作成功",$auths);
    }
    
    public function list(){
        $params = $this->param();
        
        $where = ['uniacid'=>['in',[UNIACID]]];
        
        if($this->auth->id != 1){
            $where['id'] = $this->auth->id;
        }
        
        $list = Db::name("admin")->where($where)->field(['id','uniacid','username','nickname','role_id','status','dqtime'])->order('id desc')->select();
        
        if(empty($list)){
            $list = [];
        }
        
        $rolelist = Db::name("bbfx_role")->where(['uniacid'=>UNIACID])->order('id desc')->select();
        $rolelist = array_skey($rolelist,"id");
        
        foreach ($list as $key => &$val){
            if($val['uniacid'] == 0){
                $val['role_name'] = "超级管理员";
            }
            else{
                $val['role_name'] = $rolelist[$val['role_id']]['name'];
            }

            if(empty($val['dqtime'])){
                $val['dqtime'] = '';
            }
            else{
                $val['dqtime'] = date('Y-m-d H:i:s',$val['dqtime']);
            }
        }
        unset($val);
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function setStatus(){
        $params = $this->param();
        
        if(empty($params['status'])){
            __error("操作失败");
        }
        
        $res = Db::name("admin")->where(['id'=>$params['id']])->update(['status'=>$params['status']]);
        if(!empty($res)){
            __success("操作成功");
        }
        else{
            __success("操作成功");
        }
    }
    
    public function delete(){
        $params = $this->param();
        
        $id = intval($params['id']);
        if($id == 1){
            __error("主账号不能删除");
        }
        
        if($id == $this->auth->id){
            __error("不可删除本账号");
        }
        
        $res = Db::name("admin")->where(['id'=>$id])->delete();
        if(!empty($res)){
            __success("删除成功");
        }
        else{
            __error("删除失败");
        }
    }
    
    public function detail(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $info = Db::name("admin")->where(['id'=>$id])->field(['id','uniacid','username','nickname','role_id','status','dqtime'])->find();
        
        $list = Db::name("bbfx_role")->where(['uniacid'=>UNIACID])->order('id desc')->select();
        
        if(empty($list)){
            $list = [];
        }
        
        if(!empty($info)){
            $info['password'] = "";
            if(empty($info['dqtime'])){
                $info['dqtime'] = '';
            }
            else{
                $info['dqtime'] = date('Y-m-d H:i:s',$info['dqtime']);
            }
        }
        
        __success("操作成功",['info'=>$info,'rolelist'=>$list]);
    }
    
    
    public function post(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        $username = $params['username'];
        $nickname = $params['nickname'];
        $role_id = intval($params['role_id']);
        $status = trim($params['status']);
        $password = trim($params['password']);
        $dqtime = trim($params['dqtime']);
        
        
        if($this->auth->id != 1 && $id <= 0){
            __error("您没有操作权限");
        }
        
        if(empty($username)){
            __error("请输入账号");
        }
        if($id == 0 && empty($password)){
            __error("请输入密码");
        }
        if(empty($role_id) && $id != 1){
            __error("请选择角色");
        }
        
        $data = array(
            "username"=>$username,
            "nickname"=>$nickname,
            "role_id"=>$role_id,
            "status"=>$status,
        );

        if(!empty($dqtime)){
            $data['dqtime'] = strtotime($dqtime);
        }
        else{
            $data['dqtime'] = 0;
        }
        
        if(!empty($password)){
            $data['password'] = $password;
        }
        
        Db::startTrans();
        try {
            
            if(!empty($data['password'])){
                if (!Validate::is($data['password'], '\S{6,30}')) {
                    exception(__("Please input correct password"));
                } 
                
                $data['salt'] = Random::alnum();
                $data['password'] = $this->auth->getEncryptPassword($data['password'], $data['salt']);
            }
            
            if($id <= 0){
                $data['uniacid'] = UNIACID;
                $data['email'] = $data['username']."@".$data['username'].".com";
                $data['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $result = $this->model->validate('Admin.add')->save($data);
                if ($result === false) {
                    exception($this->model->getError());
                }
                $group = [2];
    
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                if (!$group) {
                    exception(__('The parent group exceeds permission limit'));
                }
    
                $dataset = [];
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
            }
            else{
                
                $row = $this->model->get(['id' => $id]);
                if($row->id == 1){
                    unset($data['role_id']);
                }
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,30}|unique:admin,username,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);
                $result = $row->validate('Admin.edit')->save($data);
                if ($result === false) {
                    exception($row->getError());
                }
                
                if($row->id != 1){
                    // 先移除所有权限
                    model('AuthGroupAccess')->where('uid', $row->id)->delete();
                    $group = [2];
                    // 过滤不允许的组别,避免越权
                    $group = array_intersect($this->childrenGroupIds, $group);
                    if (!$group) {
                        exception(__('The parent group exceeds permission limit'));
                    }
                    $dataset = [];
                    foreach ($group as $value) {
                        $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                    }
                }
                
                model('AuthGroupAccess')->saveAll($dataset);
            }
            
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            __error($e->getMessage(),$data);
        }
        __success("操作成功");
    }
    
    public function role(){
        $params = $this->param();
        
        
        $list = Db::name("bbfx_role")->where(['uniacid'=>UNIACID])->order('id desc')->select();
        
        if(empty($list)){
            $list = [];
        }
        
        __success("操作成功",['list'=>$list]);
    }
    
    public function roleDel(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $res = Db::name("bbfx_role")->where(['id'=>$id])->delete();
        if(!empty($res)){
            
            __success("删除成功");
        }
        else{
            __error("删除失败");
        }
    }
    
    public function roleDetail(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $info = Db::name("bbfx_role")->where(['id'=>$id])->find();
        
        $list = \app\common\model\bbfxshop\Auth::getAllAuthList();
        
        if(empty($list)){
            $list = [];
        }

        
        $tree = new Tree();
        $tree->instance()->init($list);
        
        $authlist = $tree->instance()->getTreeArray(0);

        if(!empty($info)){
            $info['auth_content'] = iunserializer($info['auth_content']);
        }
        
        __success("操作成功",['info'=>$info,'authlist'=>$authlist]);
    }
    
    
    public function rolePost(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $data = array(
            "uniacid"=>UNIACID,
            "name"=>$params['name'],
            "auth_content"=>iserializer($params['auth_content']),
            "content"=>$params['content'],
        );
        
        if(empty($data['name'])){
            __error("请输入角色名称");
        }
        
        if($id > 0){
            $res = Db::name("bbfx_role")->where(['id'=>$id])->update($data);
        }
        else{
            $res = Db::name("bbfx_role")->insert($data);
        }
        
        if($res){
            __success("编辑成功");
        }
        else{
            __success("操作成功");
        }
    }
    
    public function auth(){
        $params = $this->param();
        
        $list = Db::name("bbfx_auth")->order('sort desc')->select();
        
        if(empty($list)){
            $list = [];
        }
        $tree = new Tree();
        $tree->instance()->init($list);
        $rulelist = $tree->instance()->getTreeList($tree->instance()->getTreeArray(0), 'name');
        
        __success("操作成功",['list'=>$rulelist]);
    }
    
    public function authDel(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $res = Db::name("bbfx_auth")->where(['id'=>$id])->delete();
        if(!empty($res)){
            
            Db::name("bbfx_auth")->where(['pid'=>$id])->update(['pid'=>0]);    
            
            __success("删除成功");
        }
        else{
            __error("删除失败");
        }
    }
    
    public function authDetail(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $info = Db::name("bbfx_auth")->where(['id'=>$id])->find();
        
        $where = ['type'=>0];
        if(!empty($info)){
            $where['id'] = ['neq',$id];
        }
        
        $plist = Db::name("bbfx_auth")->where($where)->order('sort desc')->select();
        $tree = new Tree();
        $tree->instance()->init($plist);
        $rulelist = $tree->instance()->getTreeList($tree->instance()->getTreeArray(0), 'name');
        
        $result = ['plist'=>$rulelist];
        
        if(!empty($info)){
            $result['info'] = $info;
        }
        
        __success("操作成功",$result);
    }
    
    
    public function authPost(){
        $params = $this->param();
        
        
        $id = intval($params['id']);
        
        $data = array(
            "name"=>$params['name'],
            "rule"=>$params['rule'],
            "pid"=>intval($params['pid']),
            "type"=>intval($params['type']),
        );
        
        if(empty($data['name'])){
            __error("请输入权限名称");
        }
        if(empty($data['rule'])){
            __error("请输入权限规则");
        }
        
        if($id > 0){
            $res = Db::name("bbfx_auth")->where(['id'=>$id])->update($data);
        }
        else{
            $res = Db::name("bbfx_auth")->insert($data);
        }
        
        if($res){
            __success("编辑成功");
        }
        else{
            __success("操作成功");
        }
    }

    public function restoreOper(){
        $id = $this->param('id/d');
        if($this->auth->id != 1){
            __error("您没有权限操作");
        }

        $log = Db::name("admin_log")->where(['id'=>$id])->find();
        if(empty($log)){
            __error("日志不存在");
        }

        if($log['is_restore'] == -1){
            __error("该操作不可恢复");
        }

        if($log['is_restore'] == 1){
            __error("该操作已恢复");
        }

        $json = json_decode($log['info'],true);

        $table = $json['table'];
        $data = $json['data'];
        $correlation_tables = $json['correlation_tables'];

        $url = $log['url'];

        if(strstr($url,'agent/user/delete') || strstr($url,'fenxiao/user/delete') || strstr($url,'store/dealer/delete')){
            unset($data['id']);
            $res = Db::name($table)->where($data)->update($data);
        }
        else{
            if($table == 'bbfx_order'){
                unset($data['order_trade_no']);
            }
            $res = Db::name($table)->insert($data);
            
            if(!empty($correlation_tables)){
                foreach($correlation_tables as $item){
                    if(!empty($item['data'])){
                        Db::name($item['table'])->insertAll($item['data']);
                    }
                }
            }
        }
        
        if($res){
            __success("恢复成功");
        }
        else{
            __error("恢复失败");
        }
        
    }

    public function getOperLog(){
        $params = $this->param();
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):20;
        
        $where = ['uniacid'=>UNIACID,'createtime'=>['>=',1727517116]];
        if($this->auth->id != 1){
            $where['admin_id'] = $this->auth->id;
        }
        $type = intval($params['type']);
        $keyword = $params['keyword'];
        $where_search = [];
        if(!empty($keyword)){
            
            if($type == 1){
                // 用户ID
                $where_search['search'] = ['like','%_user_id='.$keyword.'%'];
            }
            else if($type == 2){
                // 订单ID
                $where_search['search'] = ['like','%bbfx_order_id='.$keyword.'%'];
            }
            else if($type == 3){
                // 订单编号
                $where_search['search'] = ['like','%bbfx_order_order_no='.$keyword.'%'];
            }
            else if($type == 4){
                // 交易单号
                $where_search['search'] = ['like','%bbfx_order_order_trade_no='.$keyword.'%'];
            }
            else if($type == 5){
                // 商品ID
                $where_search['search'] = ['like','%_goods_id='.$keyword.'%'];
            }
        }

        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);

        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
        } 
        else{
            $startTime = 0;
        }
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
        }
        else{
            $endTime = strtotime("2099-12-31 23:59:59");;
        }

        $where['createtime'] = ['between',[$startTime,$endTime]];
        
        $list = Db::name("admin_log")->where($where)->where($where_search)->order('createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
    	$total = Db::name("admin_log")->where($where)->where($where_search)->count();
    	foreach ($list as $key => &$val) { 
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	}
    	unset($val);
      	
        __success('操作成功',['total'=>$total,'list'=>$list]);
    }
}