<?php
// 学校model类
namespace app\common\model;
use think\Db;

class RoleModel extends Base{
    protected $table = 'jr_account_role';
    
    protected function initialize(){
        parent::initialize();
    }
    // 根据具体用户
    public function get_role_by_id( $where ){
        $result = $this->get_role_by_where($where);
        return get_info_list($result);
    }
    // 根据具体用户
    public function get_role_by_where( $where ){
        $result = $this->get_all($where);
        return $result;
    }

    // 根据帐号ID获取某个帐号的学生信息
    public function get_by_account_to_role_list($where){
        // $where['account_id'] = $account_id;
        return $this->_get_mapping($where);
    }

    public function Rolelist(){
        return $this->hasMany('RoleListModel','account_id','account_id')->field('id,account_id,account_id,answer_data');
    }

    private function _get_mapping($where){
        // $where['account_id'] = $account_id;
        // $where['role_id'] = $role_id;
        $result = $this->get_all($where,null,null,$this->get_method());
        return get_info_list($result);
    }

    public function rank($where = ['grade' => 7],$account_id){
        $query = Db::table('jr_account a')
                    ->join('jr_account_role b','a.id=b.account_id')
                    ->where('score > 0 and LENGTH(openid) > 10')
                    ->group('a.openid')
                    ->order('b.score desc')
                    ->field('a.id,a.nickname,avatarurl,max(score) score')
                    ->limit(500);
        if($where){
            $list = $query->where($where)->select();
        }else{
            $list = $query->select();
        }

        // echo $query->getlastsql();
        // echo '<br>';
        
        $rank_list = [];
        foreach($list as $item){
            $rank_list[] = $item;
        }
        // 按积分进行排序
        $list = multi_array_sort($rank_list,'score');
        // 找出我的位置
        $my = indexOf($list,$account_id);

        // var_dump($my);
        // die;
        $result['list'] = $list;
        if($my){
            $result['my']['sort'] = $my['sort'];
            $result['my']['info'] = $my['item'];
        }
        return $result;
    }
}