<?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\Lib\Settlement\SettlementBase;

use App\Models\MoneyBuyMatch as MoneyBuyMatchModel;
use App\Models\Comendnotice as ComendnoticeModel;
use App\Lib\Biz\Sport\Common;


/**
 * 自动结算相关功能
 */
class SettlementAuto
{
    public function doAddNotie()
    {
        $model = new ComendnoticeModel();
        $ret = $model->InsertEndGame();
        return $ret;
    }


    public function doAutoSett($token = '')
    {
        $ccmodel = new ComendnoticeModel();
        $model = $ccmodel->getNeedSettelent();
        if (empty($model)) {
            return 0;
        }
        Common::SET_NOMAM_RECORD('开始自动结算! ', ['id' => $model->id, 'match_id' => $model->match_id, 'game_code' => $model->game_code]);

        $model->pcount = 1;
        $model->start_time = date('Y-m-d H:i:s', time());
        $model->logs = '开始自动结算-' . date('Y-m-d H:i:s', time());
        $model->done_time = date('Y-m-d H:i:s', time());
        $model->status = 1;
        $model->save();

        $mbmm = (new MoneyBuyMatchModel())->countByMatch($model->match_id, $model->game_code);
        $count = $mbmm['count'];
        if (!$count) {
            $model->status = 4;
            $model->logs = $model->logs . ' 自动结算完成(无match)-' . date('Y-m-d H:i:s', time());
            $model->save();
            $this->cgStatus($model->game_code, $model->match_id);
            Common::SET_NOMAM_RECORD('结束自动结算(v1)! ', ['id' => $model->id, 'match_id' => $model->match_id]);
            return 0;
        }

        $winret = $this->SubmitSettelement('w', ['noticeid' => $model->id, 'token' => $token]);
        if ($winret) {
            $dataComm = [
                'match_id' => $model->match_id,
                'game_code' => $model->game_code,
                'change_status' => 1,
                'settype' => 2,
                'is_manaue' => 0,
                'order_ids' => '',
                'token' => $token
            ];
            $ret1 = $ret2 = 0;
            if ($mbmm['bet1'] > 0) {
                $ret1 = $this->SubmitSettelement('s', array_merge($dataComm, ['bettype' => 1]));
            }
            if ($mbmm['bet2'] > 0) {
                $ret2 = $this->SubmitSettelement('s', array_merge($dataComm, ['bettype' => 2]));
            }
            $this->cgStatus($model->game_code, $model->match_id);

            $model->logs = $model->logs . '  自动完成v2-' . date('Y-m-d H:i:s', time()) . " ret1: $ret1  ret2: $ret2 ";
            $model->save();

            return true;
        }
        return false;
    }


    //提交结算

    /****
     *参数说明
     *
     * 结算接口
     * Settelement - Array
     * (
     * [match_id] => 1934   赛事id
     * [game_code] => zq    赛事代码
     * [change_status] => 1   是否更改赛事结果及赛事状态
     * [bettype] => 1        1单式  2串式
     * [settype] => 2         统一为2
     * [is_manaue] => 0      是否手动（全赛事是为0）,手动单个手动更改结果订单处理时为1
     * [order_ids] =>       订单号，单一订单写单订单号， 也可能同一赛事的多个订单是以用半角逗号分开，为空则为单式全部订单或串式全部订单
     * [token] => oclatv15689731035d84a12f550df            //管理叫id ,后台可用    session('adminInfo.token') 直接获取
     * )
     *
     * 输赢接口
     * WinFail - Array
     * (
     * [noticeid] => 1514   comendnotice表的ID
     * [token] => oclatv15689731035d84a12f550df
     * )
     */
    public function SubmitSettelement($type, $datas)
    {
        $url = config('sconstant.url');
        $wsurls = ['w' => '/WinFail', 's' => '/Settelement'];

        //$token = 'oclatv15689731035d84a12f550df';
        //$datas = array_merge(['token' => $token], $datas);

        $fullurl = $url . $wsurls[$type];
        $ret = request_post($fullurl, $datas);
        if (!empty($ret)) {
            $retarr = json_decode($ret, true);
            Common::SET_NOMAM_RECORD('自动结算返回： ', ['type' => $type, 'req' => $datas, 'rt' => $retarr]);
            if (isset($retarr['status']) && $retarr['status'] == 1) {
                return true;
            }
        } else {
            Common::SET_NOMAM_RECORD('自动结算返回-2-Error： ', ['type' => $type, 'req' => $datas, 'ret' => $ret]);
        }
        return false;
    }

    function cgStatus($game_code, $match_id)
    {
        $table1 = "st_" . $game_code . "_result";
        $table2 = "st_" . $game_code . "_competition";

        $ret1 = DB::update("update $table1 set  status=3  where   match_id=$match_id ");
        $ret2 = DB::update("update $table2 set  status=3  where   id=$match_id ");

        Common::SET_NOMAM_RECORD('更赛事和结果改状态为3： ', ['game_code' => $game_code, 'match_id' => $match_id, 'ret1' => $ret1, 'ret2' => $ret2]);

        return true;
    }


}