<?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 $bet_type = 0;   //1单式  2串式


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

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

    public $buyKeyMatchIdModels = [];   //单式投注里 [手动更改，同一场比赛不同结果的情况]    订单按批次号，比赛号存放，用于查订单的数组

    public $sqlArray = [];


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


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

        try {

            $this->ComendNoticModel = $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])->count();

            if ($allmatchs == 0) {
                $this->writeStatusEndOk($ComendNoticModel);
                $this->cgStatus();
                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->cgStatus();
            $this->writeStatusEndOk($ComendNoticModel);

            $this->RunSql();

            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 cgStatus()
    {
        $this->sqlArray[] = "update  st_" . $this->ComendNoticModel->game_code . "_result set status=2 where  match_id= '" . $this->ComendNoticModel->match_id . "'";
        $this->sqlArray[] = "update  st_" . $this->ComendNoticModel->game_code . "_competition set status=2 where  match_id= '" . $this->ComendNoticModel->match_id . "'";
    }

    //只处理某个订单下面的某场比赛的输赢结果
    public function ProcWinInfoByOneOrder($match_id, $order_id, $bet_type = 1)
    {
        try {
            DB::beginTransaction();

            if ($bet_type == 1) {
                $buyModel = DB::table('money_buy_simplex')->where(['order_id' => $order_id, 'match_id' => $match_id])->first();
                if (empty($buyModel)) {
                    throw  new  \Exception('没找到订单记录.' . $match_id . '-' . $order_id . '-' . $bet_type);
                }
                foreach ($buyModel as $val) {
                    $this->buyKeyMatchIdModels[$val->batch_id][$val->match_id] = $val;
                }

                $matchModes = DB::table('money_buy_match')->where(['batch_id' => $buyModel->batch_id, 'match_id' => $match_id, 'bet_type' => 1])->get();
                if (count($matchModes) <= 0) {
                    throw  new  \Exception('无match记录' . $match_id . '-' . $order_id . '-' . $bet_type);
                }
            } else {
                $buyModel = DB::table('money_buy_str')->where(['order_id' => $order_id])->first();
                if (empty($buyModel)) {
                    throw  new  \Exception('没找到订单记录' . $match_id . '-' . $order_id . '-' . $bet_type);
                }

                $matchModes = DB::table('money_buy_match')->where(['batch_id' => $buyModel->batch_id, 'match_id' => $match_id, 'bet_type' => 2])->get();
                if (count($matchModes) <= 0) {
                    throw  new  \Exception('无match记录' . $match_id . '-' . $order_id . '-' . $bet_type);
                }
            }

            $this->gameType = $matchModes['0']->game_code;
            $this->match_id = $match_id;
            $this->bet_type = $bet_type ;

            $this->setAdapterObj($this->gameType);
            $this->RefClass = new  \ReflectionClass($this->AdapterObj);
            $this->getCompResult($this->gameType, $match_id);
            if (empty($this->resultModel)) {
                throw  new  \Exception("没有比赛记录,操作中止!" . $this->gameType . '-' . $match_id);
            }

            foreach ($matchModes 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);
            }

            $this->doRun();

            DB::commit();
            return $this->makeData();

        } 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_code' => $game_type])->get();
        $this->bet_type = 1 ;

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

        $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;
        }

        $buymatchKeyModles = [];
        foreach ($buyModels as $val) {
            $this->buyKeyMatchIdModels[$val->batch_id][$val->match_id] = $val;
        }

        foreach ($buymatchModles as $val) {
            $batch_id = $val->batch_id;
            $buymatchKeyModles[$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, 'match_id' => $sval->match_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;
        }
        $this->bet_type = 2 ;


        $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', array_map(function ($i) {
            return "'$i'";
        }, $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' ";
                    $this->sqlArray[] = $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);

                $this->sqlArray[] = "update money_buy_str  set  wait_match_num=wait_match_num-1 where  batch_id='$sval->batch_id' ";
            }
        }
    }

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

        if ($sval->bet_type == 1 && !isset($this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id])) {
            throw  new \Exception('单式投注结果和对应订单关联有误!');
        }

        if ($sval->p_code != 'gj') {
            if (count($this->resultModel) <= 0) {
                throw  new \Exception('非冠军比赛结果数据不能为空');
            }
            //如果手动更改了结果，就用更改后的结果,否则用默认的结果
            if ($sval->bet_type == 1 && $this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id]->result_flag == 1) {
                $now_result = json_decode($this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id]->single_result, true);
            } else {
                $now_result = $this->resultModel;
            }

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

            //如果手动更改了结果，就用更改后的结果,否则用默认的结果
            if ($sval->bet_type == 1 && $this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id]->result_flag == 1) {
                $now_result = json_decode($this->buyKeyMatchIdModels[$sval->batch_id][$sval->match_id]->single_result, true);
            } else {
                $now_result = $this->gjModel;
            }

            if ($this->RefClass->hasMethod($fun)) {
                $winorfalse = $this->AdapterObj->$fun($sval, $now_result, []);
            } elseif ($this->RefClass->hasMethod($fun2)) {
                $winorfalse = $this->AdapterObj->$fun2($sval, $now_result, []);
            } 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 = '')
    {
        $matchResult = str_replace(";", "；", $matchResult);
        $sql = "update money_buy_match set result=$result, utime='$utime',matchResult='$matchResult' where   id=$id ";
        $this->sqlArray[] = $sql;
        return true;
    }

    //设置 输赢 解析规则适配器
    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)
    {
        $this->sqlArray[] = "update  comendnotice set status=1,pcount=pcount+1 ,done_time='" . date("Y-m-d H:i:s") . "',logs='begin|'  where id=$comendnticeModel->id";
        return true;
    }

    //写处理状态结束
    public function writeStatusEndOk($comendnticeModel)
    {
        $this->sqlArray[] = "update  comendnotice set status=4,done_time='" . date("Y-m-d H:i:s") . "',logs='" . $comendnticeModel->logs . ' end ok' . "'  where id=$comendnticeModel->id";
        return true;
    }


    //是否有需要进行结果算处理的赛事记录
    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;

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

    }

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

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

    private function RunSql()
    {
        $len = count($this->sqlArray);
        $step = 2000;
        $j = 1;
        $pdo = DB::getPdo();
        $tmp = [];
        for ($i = 0; $i < $len; $i++) {
            if ($j > $step || $i == ($len - 1)) {
                if (empty($tmp)) {
                    return;
                }
                $sqlstr = implode(";", $tmp);
                $pdo->exec($sqlstr);

                $tmp = [];
                $j = 1;
            } else {
                $tmp[] = $this->sqlArray[$i];
                $j++;
            }
        }

        return true;
    }


}