<?php

namespace Server\sso\web;

use Server\sso\SsoService;

class UsersController extends SsoService
{
    public function main(){
        global $_GPC;
        $account_users=pdo_getall('uni_account_users',array('uniacid'=>$this->uniacid));
        $uids=[];
        foreach ($account_users as $user){
            $uids[]=$user['uid'];
        }
        $page=empty($_GPC['page']) ? 1 :$_GPC['page'];
        $pagesize=10;
        $limit = ($page-1)*$pagesize;

        if(!empty($uids)){
            $users=pdo_fetchall("SELECT uid,username FROM ".tablename('users')." WHERE uid in (".implode(',',$uids).") order by uid asc limit {$limit},{$pagesize}");

            $total=pdo_fetchcolumn("SELECT count('id') FROM ".tablename('users')." WHERE uid in (".implode(',',$uids).")");

            $pager = pagination($total, $page, $pagesize);

            $ssoUsersList=pdo_getall('sso_users',array('uniacid'=>$this->uniacid));
            $ssoUsers=[];
            foreach ($ssoUsersList as $value){
                $ssoUsers[$value['uid']]=$value;
            }

            foreach ($users as &$value){
                $value['identity']=!empty($ssoUsers[$value['uid']]['identity'])?$ssoUsers[$value['uid']]['identity']:'';
            }
            unset($value);
        }else{
            $total=0;
            $users=[];
        }

        $results=[
            'title'=>'用户管理',
            'total'=>$total,
            'list'=>$users,
            'pager'=>$pager
        ];

        $this->view($results,'users');
    }
    public function setIdentity(){
        global $_W,$_GPC;

        $uid=intval($_GPC['uid']);

        $ssoUser=pdo_get('sso_users',array('uid'=>$uid,'uniacid'=>$this->uniacid));
        if($_W['ispost']){
            $params=[
                'identity'=>$_GPC['identity']
            ];
            if($ssoUser){
                $params['updatetime']=time();
                $res=pdo_update('sso_users',$params,array('id'=>$ssoUser['id']));
            }else{
                $params['uniacid']=$this->uniacid;
                $params['uid']=$uid;
                $params['createtime']=time();

                $res=pdo_insert('sso_users',$params);
            }
            if($res){
                return $this->success("设置成功", "refresh");
            }else{
                return $this->error('设置失败');
            }
        }else{

            $this->view([
                'info'=>$ssoUser,
                'title'=>'设置身份',
                'uid'=>$uid
            ]);
        }

    }

}
