<?php
/**
 * Created by PhpStorm.
 * User: guanxl
 * Date: 2018/3/31
 * Time: 15:56
 */

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\BrainstormingService;
use App\Services\CmbcService;
use App\Services\DepartmentService;
use App\Services\TopService;
use App\Services\UserService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ApiTopController extends Controller
{
    public function joinRate()
    {
        try{
            $myDepartmentId = $this->user["department_id"];

            $data = TopService::getInstance()->departmentJoinRateTop($this->activityId);
            $myRateRank = TopService::getInstance()->departmentJoinRateRank($this->activityId,$myDepartmentId);
            $myAvgRank = TopService::getInstance()->departmentKmAvgRank($this->activityId,$myDepartmentId);
            $joinCounts = TopService::getInstance()->departmentJoinTop($this->activityId);
            $top = [];
            foreach ($data as $key => $value) {
                $joinCount = isset($joinCounts[$key]) ? $joinCounts[$key] : 0;
                $top[] = [
                    "department_id" => $key,
                    "department_name" => DepartmentService::getInstance()->getDepartmentName($key),
                    "join_count" => $joinCount,
                    "join_rate" => $this->roundRate($value)
                ];
            }

            if(count($top)>1){
                foreach ($top as $value){
                    $arrJoinRate[] = $value["join_rate"];
                    $arrJoinCount[] = $value["join_count"];
                }
                array_multisort($arrJoinRate,SORT_DESC,$arrJoinCount,SORT_DESC,$top);
            }

            $joinCount = isset($joinCounts[$myDepartmentId]) ? $joinCounts[$myDepartmentId] : 0;
            $my = [
                "index_rate" => $myRateRank["index"],
                "index_avg" => $myAvgRank["index"],
                "department_id" => $myDepartmentId,
                "department_name" => DepartmentService::getInstance()->getDepartmentName($myDepartmentId),
                "join_count" => $joinCount,
                "join_rate" => $this->roundRate($myRateRank["rate"]),
                "avg_knowledge_money" => round($myAvgRank["avg_knowledge_money"], 1)
            ];

            return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my]]);
        }catch (\Exception $exception){
            Log::info("joinRate:exception ".$exception->getMessage());
            return response()->json(["error"=>config("errorcode.server_error"),"message"=>config("errmsg.")]);
        }

    }

    public function departmentKmAvg()
    {
        $myDepartmentId = $this->user["department_id"];
        $data = TopService::getInstance()->departmentKmAvgTop($this->activityId);
        $myRateRank = TopService::getInstance()->departmentJoinRateRank($this->activityId,$myDepartmentId);
        $myAvgRank = TopService::getInstance()->departmentKmAvgRank($this->activityId,$myDepartmentId);
        $joinCounts = TopService::getInstance()->departmentJoinTop($this->activityId);
        $top = [];
        foreach ($data as $key => $value) {
            $joinCount = isset($joinCounts[$key]) ? $joinCounts[$key] : 0;
            $top[] = [
                "department_id" => $key,
                "department_name" => DepartmentService::getInstance()->getDepartmentName($key),
                "join_count" => $joinCount,
                "avg_knowledge_money" => round($value, 1)
            ];
        }

        if(count($top)>1){
            foreach ($top as $value){
                $arrAvgKm[] = $value["avg_knowledge_money"];
                $arrJoinCount[] = $value["join_count"];
            }
            array_multisort($arrAvgKm,SORT_DESC,$arrJoinCount,SORT_DESC,$top);
        }

        $joinCount = isset($joinCounts[$myDepartmentId]) ? $joinCounts[$myDepartmentId] : 0;
        $my = [
            "index_rate" => $myRateRank["index"],
            "index_avg" => $myAvgRank["index"],
            "department_id" => $myDepartmentId,
            "department_name" => DepartmentService::getInstance()->getDepartmentName($myDepartmentId),
            "join_count" => $joinCount,
            "join_rate" => $this->roundRate($myRateRank["rate"]),
            "avg_knowledge_money" => round($myAvgRank["avg_knowledge_money"], 1)
        ];

        return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my]]);
    }

    public function personKm()
    {

        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
        $data = TopService::getInstance()->personKmTop($this->activityId,100);
        $myRank = TopService::getInstance()->personKmRank($this->activityId,$this->userId);
        $top = [];
        foreach ($data as $key => $value) {
            $top[] = [
                "user_id" => $key,
                "name" => self::getName($brainstorming,$value["name"]),
                "headpic_url" => $value["avatar"],
                "department_id" => $value["department_id"],
                "department_name" => DepartmentService::getInstance()->getDepartmentName($value["department_id"]),
                "knowledge_money" => $value["knowledge_money"]
            ];
        }
        $my = [
            "index" => $myRank,
            "user_id" => $this->user["user_id"],
            "name" => $this->user["name"],
            "headpic_url" => $this->user["avatar"],
            "department_id" => $this->user["department_id"],
            "department_name" => $this->user["department_name"],
            "knowledge_money" => $this->user["knowledge_money"]
        ];

        $requirementIndex = isset($brainstorming["top_prize_num"])? intval($brainstorming["top_prize_num"]):1000;

        $prizeKnowledgeMoney = TopService::getInstance()->prizeKmRank($this->activityId,$requirementIndex);
        $prizeRequirement = [
            "index" => $requirementIndex,
            "knowledge_money" => $prizeKnowledgeMoney
        ];

        return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my,"prize_requirement" => $prizeRequirement]]);
    }

    public function personDepartmentKm()
    {
        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
        $myDepartmentId = $this->user["department_id"];
        $data = TopService::getInstance()->personKmDepartmentTop($this->activityId,$myDepartmentId, 100);
        $myRank = TopService::getInstance()->personKmDepartmentRank($this->activityId,$this->userId, $myDepartmentId);
        $departmentName = DepartmentService::getInstance()->getDepartmentName($myDepartmentId);
        $top = [];
        foreach ($data as $key => $value) {
            $top[] = [
                "user_id" => $key,
                "name" => self::getName($brainstorming,$value["name"]),
                "headpic_url" => $value["avatar"],
                "department_id" => $value["department_id"],
                "department_name" => $departmentName,
                "knowledge_money" => $value["knowledge_money"]
            ];
        }
        $my = [
            "index" => $myRank,
            "user_id" => $this->user["user_id"],
            "name" => $this->user["name"],
            "headpic_url" => $this->user["avatar"],
            "department_id" => $this->user["department_id"],
            "department_name" => $this->user["department_name"],
            "knowledge_money" => $this->user["knowledge_money"]
        ];

        return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my]]);
    }

    /**
     * 炫耀
     * @return \Illuminate\Http\JsonResponse
     */
    public function mark()
    {
        $myDepartmentId = $this->user["department_id"];
        $myRank = TopService::getInstance()->personKmRank($this->activityId,$this->userId);
        $myDepartmentRank = TopService::getInstance()->personKmDepartmentRank($this->activityId,$this->userId, $myDepartmentId);
        $userCount = User::where("activity_id",$this->activityId)
                            ->where("status",1)->count();
        $departmentCount = User::where("activity_id",$this->activityId)
                                ->where("department_id",$myDepartmentId)
                                ->where("status",1)->count();

        $pkWin = intval($this->user["pk_win_count"]);
        $pkLost = intval($this->user["pk_lost_count"]);
        $pkDraw = intval($this->user["pk_draw_count"]);
        $pkCount = $pkWin + $pkLost + $pkDraw;
        $pkWinRate = 0;
        if ($pkWin > 0 && $pkCount > 0) {
            $pkWinRate = round(($pkWin/$pkCount)*100,2);
        }
        $topWinRate=0;
        $topWinDepartmentRate = 0;
        if($userCount>0){
            $topWinRate = $myRank==1? 100:$this->roundRate((1-$myRank/$userCount)*100);
        }
        if($departmentCount>0){
            $topWinDepartmentRate = $myDepartmentRank==1? 100:$this->roundRate((1-$myDepartmentRank/$departmentCount)*100);
        }

        $activityInfo = BrainstormingService::getInstance()->get($this->activityId);
        $levelStarConfig = json_decode($activityInfo['level_star_config'], true);

        $data = [
            "index_all" => $myRank,
            "user_id" => $this->user["user_id"],
            "name" => $this->user["name"],
            "headpic_url" => $this->user["name"],
            "department_id" => $this->user["department_id"],
            "department_name" => DepartmentService::getInstance()->getDepartmentName($myDepartmentId),
            "knowledge_money" => $this->user["knowledge_money"],
            "index_department" => $myDepartmentRank,
            "top_win_rate" => $topWinRate,
            "top_win_department_rate" => $topWinDepartmentRate,
            "pk_count" => $pkCount,
            "pk_win" => $pkWin,
            "pk_lost" => $pkLost,
            "pk_draw" => $pkDraw,
            "pk_win_rate" => $pkWinRate,
            "user_level" => intval($this->user['user_level']),
            "user_star" => intval($this->user['user_star']),
            "win_continuity" => intval($this->user['win_continuity']),
            "user_level_name" => $levelStarConfig[$this->user['user_level']]['name'],
            "level_need_star" => intval($levelStarConfig[$this->user['user_level']]['star']),
            "index" => intval(TopService::getInstance()->personPkRank($this->activityId, $this->userId)),
        ];
        return response()->json(["error" => 0, "data" => $data]);
    }

    protected function roundRate($rate)
    {
        if(is_int($rate)){
            return $rate;
        }else{
            if ($rate > 10) {
                return substr(sprintf("%.3f",$rate),0,-1);
            } else {
                return substr(sprintf("%.2f",$rate),0,-1);
            }
        }

    }

    /**
     * @param $activity
     * @param $name
     * @return string
     */
    function getName($activity,$name){
        if($activity["client_type"]=="yunzhijia"){
            return self::hidestr($name,1,1,1);
        }else{
            return $name;
        }

    }

    /**
    +----------------------------------------------------------
     * 将一个字符串部分字符用*替代隐藏
    +----------------------------------------------------------
     * @param string    $string   待转换的字符串
     * @param int       $bengin   起始位置，从0开始计数，当$type=4时，表示左侧保留长度
     * @param int       $len      需要转换成*的字符个数，当$type=4时，表示右侧保留长度
     * @param int       $type     转换类型：0，从左向右隐藏；1，从右向左隐藏；2，从指定字符位置分割前由右向左隐藏；3，从指定字符位置分割后由左向右隐藏；4，保留首末指定字符串
     * @param string    $glue     分割符
    +----------------------------------------------------------
     * @return string   处理后的字符串
    +----------------------------------------------------------
     */
    function hideStr($string, $bengin=0, $len = 4, $type = 0, $glue = "@") {
        if (empty($string))
            return false;
        $array = array();
        if ($type == 0 || $type == 1 || $type == 4) {
            $strlen = $length = mb_strlen($string);
            while ($strlen) {
                $array[] = mb_substr($string, 0, 1, "utf8");
                $string = mb_substr($string, 1, $strlen, "utf8");
                $strlen = mb_strlen($string);
            }
        }
        if ($type == 0) {
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", $array);
        }else if ($type == 1) {
            $array = array_reverse($array);
            for ($i = $bengin; $i < ($bengin + $len); $i++) {
                if (isset($array[$i]))
                    $array[$i] = "*";
            }
            $string = implode("", array_reverse($array));
        }else if ($type == 2) {
            $array = explode($glue, $string);
            $array[0] = self::hideStr($array[0], $bengin, $len, 1);
            $string = implode($glue, $array);
        } else if ($type == 3) {
            $array = explode($glue, $string);
            $array[1] = self::hideStr($array[1], $bengin, $len, 0);
            $string = implode($glue, $array);
        } else if ($type == 4) {
            $left = $bengin;
            $right = $len;
            $tem = array();
            for ($i = 0; $i < ($length - $right); $i++) {
                if (isset($array[$i]))
                    $tem[] = $i >= $left ? "*" : $array[$i];
            }
            $array = array_chunk(array_reverse($array), $right);
            $array = array_reverse($array[0]);
            for ($i = 0; $i < $right; $i++) {
                $tem[] = $array[$i];
            }
            $string = implode("", $tem);
        }
        return $string;
    }
}