<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/25
 * Time: 14:10
 */

namespace App\Lib\Settlement;
set_time_limit(600);
ini_set('memory_limit', '256M');

use Illuminate\Support\Facades\DB;
use App\Models\Comendnotice as ComendnoticeModel;

use  App\Lib\Settlement\Adapter\ZqRule;
use  App\Lib\Settlement\Adapter\LqRule;
use  App\Lib\Settlement\Adapter\WqRule;
use  App\Lib\Settlement\Adapter\BqRule;

//一场比赛结束，计算出对应 串式单式下单数据的 输赢并更新到money_buy_match对应记录
class SettlementWinFail
{

    //比赛结束消息通知模型
    public $ComendNoticModel = null;


    public $gameType = '';  //类型
    public $match_id = 0;  //比赛ID

    public $resultModel = null; //比赛最终结果对像MODEL
    public $resultRecords = []; //比赛中间结果对像数组;
    public $gjModel = null;  //冠军比赛结果数据

    public $CompostionDatas = null; //赛事数据


    //类型映射
    public $gameAllMap = [
        'zq' => 'ZqRule',
        'lq' => 'LqRule',
        'wq' => 'WqRule',
        'bq' => 'BqRule',
    ];
    private $AdapterObj = null;
    private $RefClass = null;


    //按赛事批量结算
    public function doRun($id = 0)
    {

        try {

            $ComendNoticModel = $this->getComendNoticeModel($id);
            if (!$ComendNoticModel) {
                return $this->makeData(1, '没有要处理的数据,直接退出');
            }


            DB::beginTransaction();

            $this->writeStatusBegin($ComendNoticModel);

            //$allmatchs = DB::table('money_buy_match')->where(['game_code' => $ComendNoticModel->game_code, 'match_id' => $ComendNoticModel->match_id, 'result' => 0])->get();
            $allmatchs = DB::table('money_buy_match')->where(['game_code' => $ComendNoticModel->game_code, 'match_id' => $ComendNoticModel->match_id])->get();
            if (count($allmatchs) == 0) {
                $this->writeStatusEndOk($ComendNoticModel);
                DB::table("st_" . $ComendNoticModel->game_code . "_result")->where(['match_id' => $ComendNoticModel->match_id])->update(['status' => 2]);
                DB::table("st_" . $ComendNoticModel->game_code . "_competition")->where(['match_id' => $ComendNoticModel->match_id])->update(['status' => 2]);
                DB::commit();
                return $this->makeData(1, '本赛事无订单数据，退出');
            }


            $this->gameType = $ComendNoticModel->game_code;
            $this->match_id = $ComendNoticModel->match_id;

            $this->setAdapterObj($ComendNoticModel->game_code);
            $this->RefClass = new  \ReflectionClass($this->AdapterObj);
            $this->getCompResult($ComendNoticModel->game_code, $ComendNoticModel->match_id);

            $this->Settlement_simplex($this->gameType, $this->match_id);
            $this->Settlement_str($this->gameType, $this->match_id);


            $this->writeStatusEndOk($ComendNoticModel);
            DB::commit();
            return $this->makeData(1, 'success-all');

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->makeData(0, 'false', ['msg' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine()]);

        }
    }

    //单式订单结算处理
    private function Settlement_simplex($game_type, $match_id)
    {
        //$buyModels = DB::table('money_buy_simplex')->where(['match_id' => $match_id, 'game_status' => 0])->get();
        $buyModels = DB::table('money_buy_simplex')->where(['match_id' => $match_id])->get();

        if (count($buyModels) == 0) {
            return true;
        }

        //$buymatchModles = DB::table('money_buy_match')->where(['match_id' => $match_id, 'bet_type' => 1, 'result' => 0, 'game_code' => $game_type])->orderby('batch_id', 'asc')->get();
        $buymatchModles = DB::table('money_buy_match')->where(['match_id' => $match_id, 'bet_type' => 1, 'game_code' => $game_type])->orderby('batch_id', 'asc')->get();
        if (count($buymatchModles) == 0) {
            return true;
        }

        $buyKeyModel = $buymatchKeyModles = [];
        foreach ($buyModels as $val) {
            $batch_id = $val->batch_id;
            $buyKeyModel[$batch_id] = $val;
        }
        foreach ($buymatchModles as $val) {
            $batch_id = $val->batch_id;
            $buymatchKeyModles[$batch_id][] = $val;
        }

        foreach ($buyKeyModel as $batch_id => $val) {
            foreach ($buymatchKeyModles as $sub_batch_id => $fsval) {
                foreach ($fsval as $sval) {
                    $winorfalse = $this->winOrfalseInfo($sval);
                    $wininfo = $winorfalse['result'];
                    $matchinfo = $winorfalse['matchResult'];
                    $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);
                    $gs_val = ($wininfo == 1) ? 1 : ($wininfo == -1 ? 2 : 3);
                    DB::table('money_buy_simplex')->where(['batch_id' => $sval->batch_id, 'game_code' => $sval->game_code])->update(['game_status' => $gs_val]);
                }
            }
        }
        return true;
    }

    //串式订单结算处理
    private function Settlement_str($game_type, $match_id)
    {
        $matchModels = DB::table('money_buy_match')->where(['match_id' => $match_id, 'bet_type' => 2, 'game_code' => $game_type])->get();
        if (count($matchModels) == 0) {
            return true;
        }

        $batch_ids_array = [];
        $matchKeyModels = [];
        foreach ($matchModels as $val) {
            $matchKeyModels[$val->batch_id][] = $val;
            if (!in_array($val->batch_id, $batch_ids_array)) {
                $batch_ids_array[] = $val->batch_id;
            }
        }

        $buyModels = DB::table('money_buy_str')->whereIn('batch_id', $batch_ids_array)->get();
        $buyKeyModels = [];
        if (count($buyModels) == 0) {
            return true;
        }
        foreach ($buyModels as $val) {
            $buyKeyModels[$val->batch_id][] = $val;
        }

        foreach ($matchKeyModels as $key => $sval_2) {
            foreach ($sval_2 as $sval) {
                $thissaisi = $this->getCompostionDatas($sval->game_code, $sval->match_id);
                if ($thissaisi->status == 4) {
                    $this->makesql_up_buymatch_winorfalse($sval->id, 2, date("Y-m-d H:i:s"), '赛事取消[结果和处理]');
                    $sql = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$sval->batch_id' ";
                    DB::update($sql);
                    continue;
                }
                if ($sval->match_id != $this->match_id) {
                    continue;
                }
                $winorfalse = $this->winOrfalseInfo($sval);
                $wininfo = $winorfalse['result'];
                $matchinfo = $winorfalse['matchResult'];
                $this->makesql_up_buymatch_winorfalse($sval->id, $wininfo, date("Y-m-d H:i:s"), $matchinfo);

                $sql = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$sval->batch_id' ";
                DB::update($sql);
            }
        }
    }

    //输赢结果判断 $sval 为 money_buy_match  Model; 结果为  -1输  1赢  2平  3赢半平半  4输半平半
    private function winOrfalseInfo($sval)
    {
        $fun = $sval->odds_code;
        $fun2 = $sval->p_code;

        if ($sval->p_code != 'gj') {

            if (count($this->resultModel) <= 0) {
                throw  new \Exception('非冠军比赛结果数据不能为空');
            }

            if ($this->RefClass->hasMethod($fun)) {
                $winorfalse = $this->AdapterObj->$fun($sval, $this->resultModel, []);
            } elseif ($this->RefClass->hasMethod($fun2)) {
                $winorfalse = $this->AdapterObj->$fun2($sval, $this->resultModel, []);
            } else {
                throw new \Exception('没有找到玩法输赢判断规则-01-' . $sval->id, 40010);
            }
        } else {
            $this->getGjDatas($sval);

            if ($this->RefClass->hasMethod($fun)) {
                $winorfalse = $this->AdapterObj->$fun($sval, $this->gjModel, []);
            } elseif ($this->RefClass->hasMethod($fun2)) {
                $winorfalse = $this->AdapterObj->$fun2($sval, $this->gjModel, []);
            } else {
                throw new \Exception('没有找到玩法输赢判断规则-02-' . $sval->id, 40010);
            }
        }


        if (!isset($winorfalse['result']) || !isset($winorfalse['matchResult'])) {
            throw new \Exception('输赢结果数据结构异常!', 40011);
        }

        if (!in_array($winorfalse['result'], [-1, 1, 2, 3, 4])) {
            throw new \Exception('输赢结果异常!');
        }
        return $winorfalse;
    }


    private function makesql_up_buymatch_winorfalse($id, $result, $utime, $matchResult = '')
    {
        $ret = DB::table('money_buy_match')->where(['id' => $id])->update(['result' => $result, 'utime' => $utime, 'matchResult' => $matchResult]);
        return $ret;
    }

    //设置 输赢 解析规则适配器
    private function setAdapterObj($game_type)
    {
        $game_type = strtolower($game_type);
        if (!isset($this->gameAllMap)) {
            throw  new \Exception('赛事类型错误-' . $game_type, 4002);
            return false;
        }

        switch ($game_type) {
            case 'bq':
                $this->AdapterObj = new BqRule();
                break;
            case  'lq':
                $this->AdapterObj = new LqRule();
                break;
            case  'wq':
                $this->AdapterObj = new WqRule();
                break;
            case  'zq':
                $this->AdapterObj = new ZqRule();
                break;
        }
        return true;
    }


    //返回数据
    private function makeData($status = 1, $message = 'success', $data = '')
    {
        return [
            'status' => $status,
            'message' => $message,
            'data' => $data,
        ];
    }

    //写处理状态
    public function writeStatusBegin($comendnticeModel)
    {

        $comendnticeModel->status = 1;
        $comendnticeModel->done_time = date("Y-m-d H:i:s");
        $comendnticeModel->pcount++;
        $comendnticeModel->logs = 'begin|';
        $ret = $comendnticeModel->save();

        return $ret;
    }

    //写处理状态结束
    public function writeStatusEndOk($comendnticeModel)
    {

        $comendnticeModel->status = 4;
        $comendnticeModel->done_time = date("Y-m-d H:i:s");
        $comendnticeModel->logs = $comendnticeModel->logs . 'end ok';
        $ret = $comendnticeModel->save();

        return $ret;
    }


    //是否有需要进行结果算处理的赛事记录
    public function getComendNoticeModel($id = 0)
    {
        if ($id) {
            $ret = (new ComendnoticeModel())->where(['id' => $id, 'status' => 0])->orderby('id', 'asc')->first();
        } else {
            $ret = (new ComendnoticeModel())->where('status', 0)->orderby('id', 'asc')->first();
        }


        $this->ComendNoticModel = $ret;
        return $ret;
    }


    //得到比赛最终结果记录 和 中间结果记录
    public function getCompResult($type, $match_id)
    {
        $model = null;
        switch ($type) {
            case 'bq':
                $model = DB::table('st_bq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
                $models = DB::table('st_bq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                break;
            case  'lq':
                $model = DB::table('st_lq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
                $models = DB::table('st_lq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                break;
            case  'wq':
                $model = DB::table('st_wq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
                $models = DB::table('st_wq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                break;
            case  'zq':
                $model = DB::table('st_zq_result')->where('match_id', $match_id)->orderby('id', 'asc')->get();
                $models = DB::table('st_zq_result_record')->where('match_id', $match_id)->orderBy('id', 'asc')->get()->toArray();
                break;
        }

        $this->resultModel = $model;
        $this->resultRecords = $models;

        $ret = [
            'result' => $model,
            'records' => $models,
        ];
        return $ret;

    }

    //根据比赛ID，获取赛事数据，主要用于处理是否有作废的情况
    public function getCompostionDatas($game_code, $batch_id)
    {
        $batch_id = intval($batch_id);
        if (isset($this->CompostionDatas[$batch_id])) {
            return $this->getCompostionDatas[$game_code][$batch_id];
        }

        $table = 'st_' . $game_code . '_competition';
        $ret = DB::table($table)->where('match_id', $batch_id)->first();
        if (count($ret) <= 0) {
            throw new  \Exception('根据比赛ID获取赛事数据有误-'.$game_code.'-'.$batch_id);
        }
        $this->CompostionDatas[$game_code][$batch_id] = $ret;
        return $ret;
    }


    //冠军比赛结果
    public function getGjDatas($matchModel)
    {
        if (count($this->gjModel) > 0) {
            return $this->gjModel;
        }
        $table = 'st_' . $matchModel->game_code . '_league_result';
        $where = ['lg_id' => $matchModel->lg_id, 'game_name' => $matchModel->odds_code];
        $model = DB::table($table)->where($where)->get();
        if (count($model) <= 0) {
            throw new  \Exception('冠军数据没找到!');
        }
        $this->gjModel = $model;
        return $model;
    }

}