<?php

/**
 * PK记录
*/

class pkLogModule extends commonModule
{
    public function __construct()
    {
        parent::__construct("sl_pk_log");
    }

    //根据发起人查询历史战绩
    public function getInfoByUser($user_number){
        $data = $this->where(["user_number"=>$user_number])->orderBy("end_time desc")->all();
        return $data;
    }

    //根据接收人查询历史战绩
    public function getInfoByUsered($usered_number){
        $data = $this->where(["usered_number"=>$usered_number])->orderBy("end_time desc")->all();
        return $data;
    }

    //计算战绩总场次
    public function getUserPkTotal($user_number){
        $user = $this->getInfoByUser($user_number);
        $usered = $this->getInfoByUsered($user_number);
        $data = count($user) + count($usered);
        return $data;
    }

    //计算用户胜场
    public function getUserVictory($user_number){
        //计算发起时
        $user = $this->where(["user_number" => $user_number,"results" => 1])->count();
        $usered = $this->where(["usered_number" => $user_number,"results" => 2])->count();
        $data = $user + $usered;
        return $data;
    }

    //计算总收益
    public function totalProfit($user_info){

        //查询作为发起人
        $user = $this->getInfoByUser($user_info["number"]);
        $total_profit_user = 0;
        $userModule = new userModule();
        foreach ($user as &$v){
            $total_profit_user += $v["money"];
            $v["user_head"] = $user_info["avatar"];
            $v["usered_head"] = $userModule->getUserInfoByNumber($v["usered_number"])["avatar"];
        }

        //作为接收人
        $usered = $this->getInfoByUsered($user_info["number"]);
        $total_profit_usered = 0;
        foreach ($usered as &$val){
            $total_profit_usered += $val["receive_money"];
            $val["user_head"] = $userModule->getUserInfoByNumber($val["usered_number"])["avatar"];
            $val["usered_head"] = $user_info["avatar"];
            switch ($val["results"]){
                case 1:
                    $val["results"] = 2;
                    break;
                case 2:
                    $val["results"] = 1;
                    break;
                default:
                    $val["results"] = 3;
                    break;
            }
        }

        //整理数据
        $total_profit = (double)$total_profit_user + (double)$total_profit_usered;
        $pk_log = array_merge($user,$usered);
        array_multisort(array_column($pk_log,'end_time'),SORT_DESC,$pk_log);

        $total = [
            "total_profit" => $total_profit,
            "pk_log" => $pk_log,
        ];

        return $total;
    }

}