<?php
namespace app\admin\controller;

use think\Db;
use think\Exception;

class Org extends Auth
{

    public function index(){
        $tree = model('Org')->showAllTree();
        $this->assign('tree',$tree);
        return $this->fetch();
    }

    /**
     * 新增
     */
    public function add($pid=0,$t=0){
        if(request()->isPost()){
            $res = model('Org')->addSave();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('Org')->getError());
            }
        }else{
            $fpid = Db::name('org')->where('id',$pid)->value('parent_id');

            $flist = Db::name('org')->where('del',0)->where('type',1)->select();
            foreach ($flist as $k=>$v){
                $flist[$k]['title'] = $v['name'];
            }
            $city = Db::name('city')->select();

            $this->assign('city',$city);
            $this->assign('flist',$flist);
            $this->assign('fpid',$fpid);
            $this->assign('pid',$pid);
            $this->assign('t',$t);
            return $this->fetch();
        }
    }

    /**
     * 编辑
     */
    public function edit($id=0){
        if(request()->isPost()){
            $res = model('Org')->editSave();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('Org')->getError());
            }
        }else{
            $info = db('org')->where('id',$id)->find();
            $info['location'] = '';
            if($info && $info['lat'] && $info['lng']){
                $info['location'] = $info['lat'].'-'.$info['lng'];
            }

            $orgList = Db::name('org')
                ->where('del',0)
                ->where('type',1)
                ->select();
            $this->assign('orgList',$orgList);

            $flist = Db::name('org')->where('del',0)->where('type',1)->where('id','<>',$id)->select();
            foreach ($flist as $k=>$v){
                $flist[$k]['title'] = $v['name'];
            }


            $this->assign('flist',$flist);


            $city = Db::name('city')->select();
            $this->assign('city',$city);
            $pid = $info['parent_id'];
            $this->assign('pid',$pid);
            $this->assign('info',$info);
            $this->assign('t',$info['type']);
            $this->assign('fpid',$info['parent_id']);
            return $this->fetch();
        }
    }

    public function changeEnable($id=0,$enable=0){
        if($id <= 0){
            $this->error('参数错误');
        }
        $ret = Db::name('org')->where('id',$id)->setField('enable',$enable);
        if(!$ret){
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        // 检查是否有子级
        $ret = Db::name('org')->where('parent_id',$id)->where('del',0)->find();
        if($ret){
            $this->error('有子级不能删除');
        }
        $res = Db::name('org')->where('id',$id)->setField('del',1);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * 授权
     */
    public function auth(){
        if(request()->isPost()){
            $res = model('Org')->authSave();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('Org')->getError());
            }
        }else{

            $orgId = input('id/d',0);
            $meuns = model('Menu')->getAllMenuTree();

            $this->assign('menus',$meuns);
            $sauth = model('Org')->getOrgAuths($orgId,1);
            $this->assign('sauth',$sauth);

            $appauths = model('AppIcon')->getAllIconTree();
            $this->assign('appauths',$appauths);
            $sappauth = model('Org')->getOrgAuths($orgId,2);
            $this->assign('sappauth',$sappauth);

            $this->assign('orgId',$orgId);
            return $this->fetch();
        }
    }

    public function copyAuth($id){
        if(request()->isPost()){
            $id = input('id',0);
            $orgId = input('orgId',0);
            if($id <1){
                $this->error('参数错误');
            }
            if($orgId < 1 ){
                $this->error('请选择复制的项目');
            }
            $oinfo = Db::name('org')->where('id',$orgId)->find();
            $data = [
                'auths'=>$oinfo['auths'],
                'appauths'=>$oinfo['appauths'],
                'update_time'=>getTime()
            ];

            $res = Db::name('org')->where('id',$id)->update($data);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error('操作失败');
            }
        }else{

            $orgList = Db::name('org')
                ->where('del',0)
                ->where('type',2)
                ->select();
            foreach ($orgList as $k=>$v){
                $orgList[$k]['title'] = $v['name'];
            }
            $this->assign('id',$id);
            $this->assign('orgList',$orgList);


            return $this->fetch();
        }
    }

    public function orgBatchAuth(){
        if(request()->isPost()){
            $ids = input('ids',[]);
            $appids = input('appids',[]);
            $orgs = input('orgs',[]);

            if(!$orgs){
                $this->error('请选择组织');
            }
            if(!$ids && !$appids){
                $this->error('请勾选权限');
            }

            Db::startTrans();
            try {
                foreach ($orgs as $k=>$v){
                    $info = Db::name('org')
                        ->where('id',$v)
                        ->where('type',2)
                        ->where('del',0)
                        ->find();
                    $auths = $info['auths'] ? explode(',',$info['auths']):[];

                    if($ids){
                        $diff = array_diff($ids,$auths);
                        $newAuths = array_merge($diff,$auths);
                        $data['auths'] = implode(',',$newAuths);
                    }

                    if($appids){
                        $appauths = $info['appauths'] ? explode(',',$info['appauths']):[];
                        $appdiff = array_diff($appids,$appauths);
                        $newAppauths = array_merge($appdiff,$appauths);
                        $data['appauths'] = implode(',',$newAppauths);
                    }
                    $data['update_time'] = getTime();

                    Db::name('org')->where('id',$v)->update($data);

                }

                Db::commit();
                $this->success('操作成功',url('orgBatchAuth'));
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }else{

            $rolesId = input('id/d',0);

            $meuns = model('Menu')->getOrgAllMenuTree($this->orgId);

            $this->assign('menus',$meuns);

//            $sauth = model('Roles')->getRolesAuths($rolesId,1);
//            $this->assign('sauth',$sauth);
            $appauths = model('AppIcon')->getOrgAllIconTree($this->orgId);
            $this->assign('appauths',$appauths);
//            $sappauth = model('Roles')->getRolesAuths($rolesId,2);
//            $this->assign('sappauth',$sappauth);

            $orgList = Db::name('org')->where('del',0)->where('type',2)->select();


            $this->assign('orgList',$orgList);

            $this->assign('rolesId',$rolesId);
            return $this->fetch();

        }
    }
    //报单权限
    public function bdauth($id=0){
        if(request()->isPost()){
            $data = request()->post();
            if($data['id'] < 1){
                $this->error('参数错误');
            }
            $db_auth = isset($data['appids'])?implode(',',$data['appids']):'';
            $odt = [
                'bd_auth'=>$db_auth,
            ];

            Db::name('org')->where('id',$data['id'])->update($odt);

            $this->success('操作成功',url('index'));

        }else{
            $mapMenu[] = ['enable','=',1];
            $mapMenu[] = ['del','=',0];
            $mapMenu[] = ['is_btn','=',0];
            $mapMenu[] = ['id','in',[148,149,150,151,257]];

            $menus = Db::name('menu')
                ->where($mapMenu)
                ->field('id,title,url,icons,pid')
                ->order('sort asc,id asc')
                ->select();

            $dbauth = Db::name('org')->where('id',$id)->value('bd_auth');
            $selectIds = $dbauth ? explode(',',$dbauth):[];

            $this->assign('appauths',$menus);
            $this->assign('select',$selectIds);
            $this->assign('id',$id);
        }

        return $this->fetch();

    }

}