<?php
namespace app\common\model;


use think\Db;
use tools\Phptree;

class Org extends Base
{
    public function addSave(){
        $data = request()->post();
        $result = validate('Org')->check($data,[],'add');
        if(true !== $result){
            $this->error = validate('Org')->getError();
            return false;
        }
        if(!empty($data['location'])){
            $location = explode('-',$data['location']);
            $data['lat'] = $location[0];
            $data['lng'] = $location[1];
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        $ret = $this->allowField(true)->save($data);
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        if($data['type'] == 2){
            $this->createWxQrcode($this->id);
        }
        return true;
    }

    public function editSave(){
        $data = request()->post();
        $result = validate('Org')->check($data,[],'edit');
        if(true !== $result){
            $this->error = validate('Org')->getError();
            return false;
        }
        $data['update_time'] = date('Y-m-d H:i:s');
        if(!empty($data['location'])){
            $location = explode('-',$data['location']);
            $data['lat'] = $location[0];
            $data['lng'] = $location[1];
        }
        $id = $data['id'];
        unset($data['id']);

        $info = Db::name('org')->where('id',$id)->find();
        $data['parent_id'] = $info['parent_id'];
        if(isset($data['fpid'])){
            if($data['fpid'] != $info['parent_id']){
                if(isset($data['fpid']) && !empty($data['fpid'])){
                    $data['parent_id'] = $data['fpid'];
                }
            }
        }

        $subIds =  $this->getAllNextId($id);
        if(in_array($data['parent_id'],$subIds)){
            $this->error = '父集不能调整到子集下面';
            return false;
        }

        $ret = $this->allowField(true)->save($data,['id'=>$id]);
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        $info = Db::name('org')->where('id',$id)->find();
        if($info && $info['type'] == 2 && !$info['wxqrcode']){
            $this->createWxQrcode($id);
        }
        return true;
    }

    private function createWxQrcode($orgId){
        try{
            $config = config('app.wx_mini_config');
            $app = \EasyWeChat\Factory::miniProgram($config);

            $dir = '/uploads/qrcode';
            $response = $app->app_code->getUnlimit('org_'.$orgId, [
                'page'  => 'pages/splash/splash',
                'width' => 600,
            ]);
            trace($response);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs('.'.$dir, 'org'.$orgId.'.png');
            }else{
                exception('生成失败');
            }

            $file = $dir.'/org'.$orgId.'.png';
            Db::name('org')->where('id',$orgId)->setField('wxqrcode',$file);

        }catch (\Exception $e){
            trace('小程序码:'.$e->getMessage());
        }
    }

    public function authSave(){
        $orgId = input('orgId/d',0);
        if($orgId <= 0){
            $this->error = '参数错误';
            return false;
        }
        $ids = input('ids/a',[]);
        $appids = input('appids',[]);
        $ids = array_filter($ids,'check_val_empty');
        $appids = array_filter($appids,'check_val_empty');
        $data = [
            'auths' => $ids?implode(',',$ids):'',
            'appauths' => $appids?implode(',',$appids):'',
            'update_time' => date('Y-m-d H:i:s')
        ];
        $ret = Db::name('org')->where('id',$orgId)->update($data);
        if(!$ret){
            $this->error = '参数错误';
            return false;
        }
        return true;
    }

    public function showAllTree(){
        //部门的就不显示了
        $lists = Db::name('org')->where('del',0)->order('sort asc,id asc')->select();
        if (empty($lists)) {
            return array();
        }
        $tree = Phptree::makeTree(($lists), array(
            'primary_key'=>'id',
            'parent_key'=>'parent_id',
            'expanded' => true
        ));
        return $tree;
    }

    // 获取org有效权限 type 1=后台权限 2=app权限
    public function getOrgAuths($orgId,$type=1){
        if($type == 1){
            $auths = db('org')->where('id',$orgId)->value('auths');
            $auths = $auths?explode(',',$auths):[];
            if($auths){
                $auths = Db::name('menu')->where('id','in',$auths)->where('del',0)->where('enable',1)->column('id');
            }
        }else{
            $auths = db('org')->where('id',$orgId)->value('appauths');
            $auths = $auths?explode(',',$auths):[];
            if($auths){
                $auths = Db::name('app_icon')->where('id','in',$auths)->where('del',0)->where('enable',1)->column('id');
            }
        }

        return $auths?$auths:[];
    }

    // 获取系统内未删除的所有项目
    public function getAllOrgs(){
        $lists = Db::name('org')
            ->where('type',2)
            ->where('del',0)
            ->field('id,name as title')
            ->select();
        return $lists?$lists:[];
    }

    // 根据角色获取组织列表
    public function getListByRoles($userId){
        $rolesId = Db::name('user_roles')
            ->where('user_id',$userId)
            ->value('roles_id');
        if($rolesId == 1){ // 超级管理员

        }else if($rolesId == 2){ // 总公司管理员
            $orgs = Db::name('user')->where('id',$userId)->value('orgs');
            $orgs = $orgs?explode(',',$orgs):[];
            if($orgs){
                $map[] = ['id','in',$orgs];
            }else{
                $map[] = ['id','=',0];
            }
        }else{ // 组织管理员
            $orgId = Db::name('user_org')->where('user_id',$userId)->value('org_id');
            if($orgId){
                $map[] = ['id','=',$orgId];
            }else{
                $map[] = ['id','=',0];
            }
        }
        $map[] = ['type','=',2];
        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];
        $lists = Db::name('org')
              ->where($map)
            ->field('id,name')
            ->select();
        return $lists?$lists:[];
    }

    // 根据角色获取组织tree
    public function getTreeByRoles($rolesId,$userId){
        if($rolesId == 1){ // 超级管理员

        }else if($rolesId == 2){ // 总公司管理员
            $orgs = Db::name('user')->where('id',$userId)->value('orgs');
            $orgs = $orgs?explode(',',$orgs):[];
            if($orgs){
                $map[] = ['id','in',$orgs];
            }else{
                $map[] = ['id','=',0];
            }
        }else{ // 组织管理员
            $orgId = Db::name('user_org')->where('user_id',$userId)->value('org_id');
            if($orgId){
                $map[] = ['id','=',$orgId];
            }else{
                $map[] = ['id','=',0];
            }
        }
        $map[] = ['type','=',2];
        $map[] = ['del','=',0];
        $map[] = ['enable','=',1];

        $ids = Db::name('org')
            ->where($map)
            ->column('id');
        $alls = $ids?$ids:[];
        foreach ($ids as $v){
            $pids = $this->getParentIds($v);
            $alls = array_unique(array_merge($alls,$pids));
        }
        if($alls){
            $lists = Db::name('org')->where('del',0)->where('enable',1)->where('id','in',$alls)->order('sort asc,id asc')->select();
            if (!empty($lists)) {
                $tree = Phptree::makeTree(($lists), array(
                    'primary_key'=>'id',
                    'parent_key'=>'parent_id',
                    'expanded' => true
                ));
                return $tree;
            }
        }
        return [];
    }

    private function getParentIds($id,&$result=[]){
        $pid = Db::name('org')->where('id',$id)->value('parent_id');
        if($pid > 0){
            $result[] = $pid;
            $this->getParentIds($pid,$result);
        }
        return $result;
    }
    public function getInfo($id){
        $info = $this->where('id',$id)
            ->find()->toArray();
        return $info;
    }

    // 获取所有下级的id集合
    public function getAllNextId($id,$data=[]){
        $pids = DB::name('org')->where('parent_id',$id)->column('id');
        if(count($pids)>0){
            foreach($pids as $v){
                $data[] = $v;
                $data = $this->getAllNextId($v,$data); //注意写$data 返回给上级
            }
        }
        return isset($data) && !empty($data) ? $data : [];
    }


}