<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\cache;
use app\utils\RedisKeyEnum;
use app\utils\RedisUtil;
use Exception;
/**
 * 投票
 */
class Subject extends Api
{
    protected $noNeedLogin = ['info','playerlist','playerinfo','playerlist_votes','jigoulist_score'];
    protected $noNeedRight = ['*'];


    //进行中的唯一一个投票活动
    public function info(){

        $find = Db::name('vote_subject')->where('id',1)->find();
        if(!$find){
            $this->error('没有进行中的投票活动');
        }
        $find = info_domain_image($find,['image','paihang_image']);

        $this->success(1,$find);
    }

    //作品页，选手列表
    public function playerlist(){
        $subject_id = 1;

        $map = [
            'subject_id' => $subject_id,
            'status' => 1,
        ];

        //搜索
        $keyword = input('keyword','');
        if($keyword){
            $map['title|suozaidanwei|tuijiangonghui'] = ['LIKE','%'.$keyword.'%'];
        }

        //选手列表
        $lists = Db::name('vote_player')
            ->where($map)->order('weigh asc,id asc')->select();
        $lists = list_domain_image($lists,['thumb_image']);



        $this->success(1,$lists);
    }

    //选手详情
    public function playerinfo(){
        $player_id = input('player_id','');
        if(!$player_id){
            $this->error();
        }

        $map = [
            'id' => $player_id,
        ];

        $info = Db::name('vote_player')->where($map)->find();
        $info = info_domain_image($info,['thumb_image']);
        /*$info['thumb_image'] = '';
        if(!empty($info['video_file'])){
            $info['video_file']  = localpath_to_netpath($info['video_file']);
            $info['thumb_image'] = $info['video_file'].'?x-oss-process=video/snapshot,t_0,m_fast,f_jpg';
        }*/

        //获取播放地址和秒数
        $info['video_file']    = '';
        $info['video_seconds'] = 0;

        if(!empty($info['vodid'])){
            try{
                $videoVod = new \app\common\library\Video();
                $video_PlayInfo = $videoVod->getPlayInfo($info['vodid']);
                $video_PlayInfo = $video_PlayInfo->PlayInfoList->PlayInfo;

                $info['video_file'] = $video_PlayInfo[0]->PlayURL;
                $info['video_seconds'] = ceil($video_PlayInfo[0]->Duration);
            }catch(Exception $e){

            }
        }

        //名次
        /*$players = Db::name('vote_player')->where(['subject_id'=>$info['subject_id'],'status'=>1])->order('votes desc,id desc')->column('id,votes');
        $id_arr = array_keys($players);
        $mingci = 1;  //名次
        $mingci = array_search($info['id'],$id_arr);
        $mingci++;
        $info['mingci'] = $mingci;*/

        $this->success(1,$info);
    }

    //用户详细资料
    public function getuserinfo(){
        $info = $this->auth->getUserinfo();

        //今天,投了几票
        $today_record = RedisUtil::getInstance(RedisKeyEnum::VOTE_RECORD.date('Y-m-d').':'.$this->auth->id)->get();
        //今天,免费的的票
        $gift_votes = config('site.gift_votes_user_eday');
        //今天，用户答对的次数
        $question_vote  = RedisUtil::getInstance(RedisKeyEnum::EAXM_RIGHT.date('Y-m-d').':'.$this->auth->id)->get();
        $question_vote  = intval(bcmul($question_vote,config('site.question_right_getvotenum'),0));//乘以基数，也就是答题获得的票数
        //今天，总答题次数
        $gift_question = config('site.exam_times_user_eday');
        //今天，已答题次数
        $submit_question = RedisUtil::getInstance(RedisKeyEnum::EAXM_TIMES.date('Y-m-d').':'.$this->auth->id)->get();

        //基础票数
        $jcps = $gift_votes - $today_record;
        if($jcps < 0){
            $jcps = 0;
        }

        //答题票数
        $dtps = $question_vote - ( ($today_record - $gift_votes) <= 0 ? 0 : ($today_record - $gift_votes) );
        if($dtps < 0){
            $dtps = 0;
        }

        //今日剩余票数
        $today_my_vote = $gift_votes + $question_vote - $today_record;
        if($today_my_vote < 0){
            $today_my_vote = 0;
        }

        //今日剩余答题次数
        $today_my_question = $gift_question - $submit_question;
        if($today_my_question < 0){
            $today_my_question = 0;
        }


        //
        $result = [
            'info' => $info,
            'jcps' => $jcps,
            'dtps' => $dtps,
            'today_my_vote' => $today_my_vote,
            'today_my_question' => $today_my_question,
        ];

        $this->success(1,$result);
    }

    //今日投票记录
    public function my_vote_history(){
        //今日投票记录
        $player_votes = Db::name('vote_record')
            ->where('user_id',$this->auth->id)
            ->where('createdate',strtotime(date('Y-m-d')))
            ->group('player_id')
            ->field('player_id,sum(vote) as votes')
            ->order('votes desc')
            ->select();

        $player_ids = array_column($player_votes,'player_id');
        $map = [
            'status' => 1,
            'id' => ['IN',$player_ids]
        ];
        $players = Db::name('vote_player')->field('id,title')->where($map)->column('title','id');

        foreach($player_votes as $key => $val){
            $val['id'] = $val['player_id'];
            $val['title'] = isset($players[$val['player_id']]) ? $players[$val['player_id']] : '';
            unset($val['player_id']);

            $player_votes[$key] = $val;
        }

        $this->success(1,$player_votes);
    }

    //选手票数排行榜，按票
    public function playerlist_votes(){
        $subject_id = 1;

        $map = [
            'subject_id' => $subject_id,
            'status'     => 1,
        ];

        $lists = Db::name('vote_player')->field('id,title,votes')
            ->where($map)->order('votes desc,id desc')->autopage()->select();

        $lists = $this->mingci_vote($subject_id,$lists);

        $this->success(1,$lists);
    }

    //机构答题分排行榜，按分
    //机构参与人数×0.7+平均分（机构总得分÷机构参与总人次）×0.3
    public function jigoulist_score(){
        $subject_id = 1;

        //各机构的绑定人数
        $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);
//dump($user_jigou);
        //各个机构
        $map = [
            'subject_id' => $subject_id,
            'status'     => 1,
        ];

        //vote_jigou表的score需要做一个纠正
        $lists = Db::name('vote_jigou')->field('id,title,score')->where($map)->order('score desc,id desc')->select();
//dump($lists);
        //根据公式，重新计算排名分数
        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)); //四舍五入
            }

            $lists[$key] = $jigou;
        }
//dump($lists);
        $lists = $this->mingci_score($lists);

        $this->success(1,$lists);
    }

    //oss视频截贞 https://www.alibabacloud.com/help/zh/oss/user-guide/video-snapshots?spm=a2c63.p38356.0.0.6aaa4b78aOSpJH
    //使用fast模式截取视频7s处的内容，输出为JPG格式的图片，宽度为800，高度为600。
    //处理后的URL为：https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/video.mp4?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast


    //获得我的名次,票数导向
    private function mingci_vote($subject_id,$list){

        if(empty($list)){
            return $list;
        }
        //准备数据
        $players = Db::name('vote_player')->where(['subject_id'=>$subject_id,'status'=>1])->order('votes desc,id desc')->column('id,votes');
        $id_arr = array_keys($players);

        foreach($list as $key => $val)
        {
            $mingci = 1;  //名次
            $mingci = array_search($val['id'],$id_arr);
            $mingci++;

            //赋值名次
            $list[$key]['mingci'] = $mingci;
        }

        return $list;
    }

    //获得我的名次,分数导向
    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;
    }
}
