<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 答题机构管理
 *
 * @icon fa fa-circle-o
 */
class Votejigou extends Backend
{

    /**
     * Votejigou模型对象
     * @var \app\admin\model\Votejigou
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Votejigou;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
//                ->order($sort, $order)
                ->order('score desc,id desc')
                ->paginate(10000);

            $lists = collection($list->items())->toArray();

            //各机构的绑定人数
            $user_jigou = Db::name('user')->where('status',1)->where('bind_jigou_id','NEQ',0)->column('bind_jigou_id');
            $user_jigou = array_count_values($user_jigou);

            //根据公式，重新计算排名分数
            foreach($lists as $key => $jigou){
                $jigou['newscore'] = 0;
                if(isset($user_jigou[$jigou['id']])){
                    $usernumber = $user_jigou[$jigou['id']];  //机构人数
                    $jigou['newscore'] = ($usernumber * 0.7) + ($jigou['score'] / $usernumber * 0.3); //公式
                    $jigou['newscore'] = intval(round($jigou['newscore'],0)); //四舍五入
                    $jigou['usernumber'] = $usernumber;
                }

                $lists[$key] = $jigou;
            }

            $lists = $this->mingci_score($lists);


            $result = array("total" => $list->total(), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }


    //获得我的名次,分数导向
    private function mingci_score($list){

        if(empty($list)){
            return $list;
        }
        //准备数据

        foreach($list as $key => $row){
            $field[$key] = $row['newscore'];
        }
//dump($field);
        array_multisort($field,SORT_DESC,$list);
//dump($list);

        foreach($list as $key => $val)
        {
            //赋值名次
            $val['mingci'] = $key + 1;
//            $val['score']  = $val['newscore'];
//            unset($val['newscore']);

            $list[$key] = $val;
        }

        return $list;
    }


}
