<?php
namespace App\Lib\Biz\Sport;

use App\Http\Response\Response;
use Log;


use App\Http\Model\StZqMatch;
use App\Http\Model\StZqLeague;
use App\Http\Model\StZqLeagueResult;
use App\Http\Model\StZqLocalLeague;
use App\Http\Model\StZqLocalMatch;
use App\Http\Model\StZqOdds;
use App\Http\Model\StZqOddsRecord;
use App\Http\Model\StZqResult;
use App\Http\Model\StZqResultRecord;
use App\Http\Model\StZqBroadcast;
use App\Http\Model\StZqResultExpress;


use App\Http\Model\StLqMatch;
use App\Http\Model\StLqLeague;
use App\Http\Model\StLqLeagueResult;
use App\Http\Model\StLqLocalLeague;
use App\Http\Model\StLqLocalMatch;
use App\Http\Model\StLqOdds;
use App\Http\Model\StLqOddsRecord;
use App\Http\Model\StLqResult;
use App\Http\Model\StLqResultRecord;
use App\Http\Model\StLqBroadcast;
use App\Http\Model\StLqResultExpress;


use App\Http\Model\StWqResultRecord;
use App\Http\Model\StWqMatch;
use App\Http\Model\StWqLeague;
use App\Http\Model\StWqLeagueResult;
use App\Http\Model\StWqLocalLeague;
use App\Http\Model\StWqLocalMatch;
use App\Http\Model\StWqOdds;
use App\Http\Model\StWqOddsRecord;
use App\Http\Model\StWqResult;
use App\Http\Model\StWqBroadcast;
use App\Http\Model\StWqResultExpress;


use App\Http\Model\StBqResultRecord;
use App\Http\Model\StBqMatch;
use App\Http\Model\StBqLeague;
use App\Http\Model\StBqLeagueResult;
use App\Http\Model\StBqLocalLeague;
use App\Http\Model\StBqLocalMatch;
use App\Http\Model\StBqOdds;
use App\Http\Model\StBqOddsRecord;
use App\Http\Model\StBqResult;
use App\Http\Model\StBqBroadcast;
use App\Http\Model\StBqResultExpress;


class Common
{
    function checkDebug()
    {
        return (isset($_GET['debug']) && intval($_GET['debug']) == -99999) || APP_DEBUG == 1 ? 1 : 0;
    }

    function View($Path = "")
    {
        if (!$Path) {
            global $ViewPath;
            $ViewPath = explode("\\", $ViewPath);
            $ViewPath[3] = explode("Controller", $ViewPath[3]);
            $ViewPath[3] = $ViewPath[3][0];
            return APP_PATH . "/" . $ViewPath[1] . "/View/" . $ViewPath[3] . "/" . $ViewPath[4] . ".blade.php";
        } else {
            return APP_PATH . "/" . $Path . ".blade.php";
        }
    }

    function arrayToOptions($data, $key, $val)
    {
        $options = array();
        if (is_array($data) && count($data)) {
            foreach ($data as $k => $value) {
                $options[$value[$key]] = $value[$val];
            }
        }
        return $options;
    }


    function M($TABLE_NAME = "")
    {
        return new DB($TABLE_NAME);
    }

    function checkClose()
    {
        if (file_exists(ROOT_PATH . '/Cache/system.lock')) {
            if (is_mobile()) {
                return appExec("Mobile", "Weihu", "index");
            } else {
                return appExec("home", "weihu", "index");
            }
        }
    }

    /**
     * 发布消息
     *
     * @param integer $status
     * @param string $msg
     * @param string $data
     * @return void
     */
    function publishNotify($channel, $status = 1, $data = '')
    {
        // toLog('publishNotify-'.$channel.'+++'.$data);
        C()->get('msg')->publish($channel, $data);
    }

    /**
     * 数组分类排序
     * @param [array] $columnsArr [需要进行排序的数组]
     * @param [int] $plmid [所属分类ID]
     */
    function getColumns($columnsArr, $plmid)
    {
        $menu = array();

        foreach ($columnsArr as $v) {
            if ($v['plmid'] == $plmid) {
                $menu[] = $v;

                $a = getColumns($columnsArr, $v['lmid']);
                foreach ($a as $vv) {
                    $menu[] = $vv;
                }
            }
        }
        return $menu;
    }

    /**
     * 获取客户端真实IP
     */
    function GETIP()
    {
        global $ip;

        if (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("REMOTE_ADDR")) {
            $ip = getenv("REMOTE_ADDR");
        } else {
            $ip = "Unknow";
        }

        return $ip;

    }

    function dump($data, $exit = 1)
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
        if ($exit) {
            exit;
        }

    }

    function OrderID($prefix = '')
    {
        $num = mt_rand(100, 999);
        list($s, $m) = explode(' ', microtime());
        $order = date("YmdHis") . ($s * 1000000) . $num;
        return $prefix . $order;
    }

    /**
     * 容器
     */
    function C()
    {
        static $c = array();
        if (!isset($c['container'])) {
            $c['container'] = new \System\Di();
        }
        return $c['container'];
    }

    /**
     * 全局变量快捷操作
     * @param [type] $key   [description]
     * @param [type] $value [description]
     */
    function S($key, $value = null)
    {
        if ($value != null) {
            $GLOBALS[$key] = $value;
        }
        if (isset($GLOBALS[$key])) {
            return $GLOBALS[$key];
        }
    }

    /**
     * 载入模型
     * @param  [type] $name [description]
     * @param  string $proj [description]
     * @return [type]       [description]
     */
    function lm($name, $proj = '')
    {
        $proj = empty($proj) ? S('CUR_PROJECT') : $proj;
        if (empty($proj)) {
            throw new \Exception("项目{$proj}不存在", 1);
        }
        $cls = "\\App\\" . ucfirst($proj) . "\\Model\\" . ucfirst($name);
        if (!class_exists($cls)) {
            return;
        }
        $key = 'model_' . $name . $proj;
        C()->shared($key, $cls);
        return C()->get($key);
    }

    /**
     * 载入语言包
     * @param  string $key 语言项
     * @param  string $file 语言文件名
     * @param  string $proj 项目名称
     * @return [type]       [description]
     */
    function lang($file = '', $proj = '')
    {
        $proj = empty($proj) ? S('CUR_PROJECT') : $proj;
        $file = empty($file) ? S('CUR_CONTROLLER') : $file;
        $ckey = "Lang_{$proj}_{$file}";
        if (C()->has($ckey)) {
            return C()->get($ckey);
        } else {
            C()->shared($ckey, function () use ($proj, $file) {
                $file = ucfirst($file);
                $proj = ucfirst($proj);
                $lang = new \System\Lang();
                $lang_files = array();
                if (S('CUR_PROJECT') == $proj && S('CUR_CONTROLLER') == $file) {
                    $lang_files[] = ROOT_PATH . "/Application/Commons/Lang/Common.php";
                    $lang_files[] = ROOT_PATH . "/Application/{$proj}/Lang/Common.php";
                }
                $lang_files[] = ROOT_PATH . "/Application/{$proj}/Lang/{$file}.php";
                $data = array();
                foreach ($lang_files as $v) {
                    if (file_exists($v)) {
                        $data2 = include $v;
                        if (is_array($data2)) {
                            $data = array_merge($data, $data2);
                        }
                    }
                }
                $lang->load($data);
                return $lang;
            });
            return C()->get($ckey);
        }
    }

    /**
     * 标签替换
     *
     * @param [type] $message
     * @param array $data
     * @param string $tag
     * @return void
     */
    function parseTag($message, $data = array(), $tag = '#')
    {
        if (is_array($data) && count($data) > 0) {
            foreach ($data as $k => $v) {
                $message = str_replace($tag . $k . $tag, $v, $message);
            }
        }

        return $message;
    }

    function appExec($proj, $ctrl, $method, $exec = 0)
    {
        $proj = ucfirst($proj);
        $ctrl = ucfirst($ctrl);
        $method = ucfirst($method);
        S('CUR_PROJECT', $proj);
        S('CUR_CONTROLLER', $ctrl);
        S('CUR_METHOD', $method);
        checkPlatform();
        toDomain();
        //设置REMOTE_KEY
        lm('setinfo', 'commons')->setKey();

        $cls = "\\App\\{$proj}\\Controller\\{$ctrl}";
        C()->set($ctrl, $cls);
        $cls = C()->get($ctrl);
        if (!$cls) {
            exit("404 NOT FOUND");
        }
        if ($exec) {
            $result = $cls->$method();
            if (!empty($result)) {
                Render($result);
            }
        }
        if (method_exists($cls, $method)) {
            $result = $cls->$method();
            if (!empty($result)) {
                Render($result);
            }
        } else {
            exit("404 METHOD NOT FOUND");
        }

    }

    /**
     * UUID 生成
     */
    function UUID()
    {
        $prefix = '';
        $uuid = '';
        $str = md5(uniqid(mt_rand(), true));
        $uuid = substr($str, 0, 8) . '-';
        $uuid .= substr($str, 8, 4) . '-';
        $uuid .= substr($str, 12, 4) . '-';
        $uuid .= substr($str, 16, 4) . '-';
        $uuid .= substr($str, 20, 12);
        return $prefix . $uuid;
    }

    /**
     *密码加密码
     */
    function GenEncryption()
    {
        srand((double)microtime() * 1000000); //create a random number feed.
        $ychar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        $list = explode(",", $ychar);
        $authnum = "";
        for ($i = 0; $i < 6; $i++) {
            $randnum = rand(0, 61); // 10+26;
            $authnum .= $list[$randnum];
        }
        return $authnum;
    }

//密码加密
    function GenPassword($password)
    {
        $Enc = GenEncryption();
        $Pwd = md5(md5($Enc . $password));
        return array("encryption" => $Enc, "password" => $Pwd);

    }

//密码验证
    function VerPassword($identity, $password)
    {
        $account = M("account_password")->where("account_identity = '$identity' and", "status = ", '1')->select("encryption,account_password")->find();
        $VerPwd = md5(md5($account["encryption"] . $password));
        if ($VerPwd == $account["account_password"]) {
            unset($account);
            unset($VerPwd);
            return true;
        } else {
            unset($account);
            unset($VerPwd);
            return false;
        }

    }

    /**
     * Json return
     * @param string $data [description]
     * @param string $status [description]
     * @param string $msg [description]
     * @param string $method [description]
     */
    function JsonReturn($data = "", $status = "200", $msg = "", $method = "")
    {
        // header("Content-type:application/json;charset:utf-8");
        // header('content-type:text/html; charset=utf-8');
        if (isset($_REQUEST['crossdomain']) && !empty($_REQUEST['crossdomain'])) {
            header("Access-Control-Allow-Origin:{$_REQUEST['crossdomain']}");
        } else {
            header("Access-Control-Allow-Origin:*");
        }
        header('Access-Control-Allow-Methods:POST,GET,PUT,DELETE,OPTIONS');
        header('Access-Control-Allow-Credentials:true');
        $retdata = array("status" => $status, "msg" => $msg, "data" => $data);

        $devicetype = isset($_REQUEST['devicetype']) ? trim($_REQUEST['devicetype']) : '';
        if (!empty($devicetype) && in_array($devicetype, array('ios', 'android'))) {
            $path = S('CUR_PROJECT') . '/' . S('CUR_CONTROLLER') . '/' . S('CUR_METHOD');
            $retdata = C()->get($devicetype . "Result")->update($path, $retdata);
        }

        if ($method == '') {
            //dump($devicetype);
            echo(json_encode($retdata, JSON_UNESCAPED_UNICODE));
        } else {
            echo($method . "(" . json_encode($retdata, JSON_UNESCAPED_UNICODE) . ")");
        }
    }

    function XmlReturn($data = "", $status = 200, $msg = '')
    {
        // header("Content-type:text/xml;charset:utf-8");
        $xml = '<?xml version="1.0" encoding="utf-8"?>';
        $xml .= "<root>";
        $xml .= '<status>' . $status . '</status>';
        $xml .= '<msg>' . $msg . '</msg>';
        $xml .= "<rows>";
        $xml .= toXml($data);
        $xml .= "</rows>";
        $xml .= "</root>";
        echo($xml);
    }

    function toXml($data)
    {
        // print_r($data);
        $xml = '';
        if (is_array($data) && count($data) > 0) {
            foreach ($data as $k => $v) {
                $key = $k;
                if (is_numeric($k)) {
                    $key = 'data';
                }
                if (is_array($v)) {
                    $xml .= "<{$key}>" . toXml($v) . "</{$key}>";
                    continue;
                }
                if (is_string($v)) {
                    $xml .= "<{$key}>{$v}</{$key}>";
                }
            }
        }
        return $xml;
    }

    function WriteLog($Log)
    {
        $logger = new Logger('LOGGS');
        $logURI = "Cache/log/" . date("Y-m-d-H-i") . ".log";
        $logger->pushHandler(new StreamHandler($logURI, Logger::DEBUG));
        $logger->pushHandler(new FirePHPHandler());
        $logger->addInfo(var_export($Log, 1));

    }

    /**
     * 计算当前用时
     *
     * @param string $runName
     * @param integer $return
     * @return void
     */
    function computeTime($runName = '', $return = 0, $start = 1)
    {
        $curTime = get_millisecond();
        $numTime = $curTime - (intval($GLOBALS['startTime']) * 1000);
        if ($return) {
            return array('curTime' => $curTime, 'numTime' => $numTime, 'runName' => $runName);
        } else {
            echo "<pre>执行{$runName} 功能,当前时间为:{$curTime},累积用时: {$numTime}</pre>";
            return;
        }

    }

    function get_millisecond()
    {
        list($usec, $sec) = explode(" ", microtime());
        $msec = round($usec * 1000);
        return $sec . $msec;

    }

    function toLog($text, $rewrite = 0)
    {
        $data = "=============" . date("Y-m-d H:i", time()) . "==========================================" . chr(13);
        $data .= var_export($text, 1) . chr(13);
        $data .= "======================================================================================" . chr(13);
        $data = iconv('utf-8', 'gb2312', $data);
        if ($rewrite) {
            file_put_contents(ROOT_PATH . '/logs.txt', $data);
        } else {
            file_put_contents(ROOT_PATH . '/logs.txt', $data, FILE_APPEND);
        }
    }

    /**
     * 发送数据到前台，根据请求的数据格式返回相应的数据
     * @param [type] $data   [description]
     * @param string $status [description]
     * @param string $msg [description]
     */
    function Render($data, $status = "1", $msg = "", $method = '')
    {
        $format = S('CUR_RETURN_FORMAT');
        $msg = empty($msg) ? lang('errors', 'api')->get('error' . $status) : $msg;

        if (empty($format) || $format == 'json') {
            JsonReturn($data, $status, $msg);
        }
        if ($format == 'xml') {
            XmlReturn($data, $status, $msg);
        }
        exit;
    }


    function _beginTransaction()
    {
        S('DB')->beginTransaction();
    }

    function _rollBack()
    {
        S('DB')->rollBack();
    }

    function _commit()
    {
        S('DB')->commit();
    }

    /**
     * 服务
     *
     * @param string 服务名称
     * @param array $params
     * @return void
     */
    function SRV($name, $params = array())
    {
        return C()->get($name)->update($params);
    }

    /**
     * 是否验证token过期
     *
     * @return bool
     */
    function isCheckToken()
    {
        $result = true;
        $allowMethod = include ROOT_PATH . "/Config/AllowMethod.php";
        $key = S('CUR_PROJECT') . '/' . S('CUR_CONTROLLER') . '/' . S('CUR_METHOD');
        if ($allowMethod[$key] == 1) {
            $result = false;
        }
        return $result;
    }

    function checkPlatform()
    {

        if (isset($_GET['platform'])) {
            $_SESSION['platform'] = $_GET['platform'] == 'wap' ? 1 : 0;
        }
        if (isset($_GET['clearPlatform']) && intval($_GET['clearPlatform']) == 1) {
            $_SESSION['platform'] = null;
        }

    }

    function is_mobile()
    {
        if (isset($_SESSION['platform']) && $mobile = intval($_SESSION['platform']) > 0) {
            return $mobile == 1 ? true : false;
        }
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = Array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");
        $is_mobile = false;
        foreach ($mobile_agents as $device) {
            if (stristr($user_agent, $device)) {
                $is_mobile = true;
                break;
            }
        }
        return $is_mobile;
    }

    function toDomain()
    {

        $domain = $_SERVER['HTTP_HOST'];
        $config = include ROOT_PATH . '/Config/Domain.php';
        $is_mobile = is_mobile();
        $curDomain = $old_domain = $domain;
        if (is_array($config) && count($config) > 0) {
            $domains = array();
            $domains[] = $domain;
            if ($is_mobile) {
                $domains[] = str_replace('www.', 'm.', $domain);
                $domains[] = 'm.' . $domain;
            } else {
                $domains[] = str_replace('m.', '', $domain);
                $domains[] = str_replace('m.', 'www.', $domain);
            }
            foreach ($domains as $key => $value) {
                if (isset($config[$value])) {
                    $v = $config[$value];
                    if ($v == 'pay') {
                        return;
                    }
                    if ($is_mobile) {
                        if ($v == 'pc') {
                            continue;
                        }
                    } else {
                        if ($v != 'pc') {
                            continue;
                        }
                    }

                    $curDomain = $value;
                    // $_SESSION['domain']=$value;
                }
            }
        }
        // echo $curDomain;
        if ($is_mobile) {
            if (S('CUR_PROJECT') == 'Home') {
                header("Location:http://" . $curDomain . "/m");
                //header("Location:http://" . $curDomain . "/mobile-index/index");
            }
        } else {
            if (S('CUR_PROJECT') == 'Mobile') {
                header("Location:http://" . $curDomain . "/home-index/index");
            }
        }
        /**
         * 数据签名认证
         * @param  array $data 被认证的数据
         * @return string       签名
         */
        function data_auth_sign($data)
        {
            //数据类型检测
            if (!is_array($data)) {
                $data = (array)$data;
            }
            ksort($data); //排序
            $code = http_build_query($data); //url编码并生成query字符串
            $sign = sha1($code); //生成签名
            return $sign;
        }

        /*
         * 判断用户是否登录
         * */
        function isLogin($str = '', $type = 'agent')
        {
            $session = $_SESSION[$type . 'Info'];
            if (empty($session)) {
                return null;
            }
            if ($type == 'agent') {
                if ($str == 'name') {
                    return $session['agent_user'];
                }
                if ($str == 'uid') {
                    return $session['user_identity'];
                }
            }
        }
    }

    function jump($url)
    {
        header('Location:' . $url);
    }

//手机中间星号
    function phoneHide($phone)
    {
        if (!empty($phone)) {
            $phone = substr_replace($phone, '****', 3, 4);
        }
        return $phone;
    }

    /**
     * @param $game_code 球类代码
     * @param int $isJoin 是否用于join
     * @return array
     * @throws Exception
     * 根据球类代码 定义相关model
     */
    static function getModels($game_code, $isJoin = 1)
    {
        // 获取不同球类model
        if ($isJoin == 1) {
            switch ($game_code) {
                case 'zq':
                    $model_league = new StZqLeague;
                    $model_match = new StZqMatch;
                    $model_odds = new StZqOdds;
                    $model_odds_record = new StZqOddsRecord;
                    $model_result = new StZqResult;
                    $model_result_record = new StZqResultRecord;
                    $model_league_result = new StZqLeagueResult;
                    $model_local_league = new StZqLocalLeague;
                    $model_local_match = new StZqLocalMatch;
                    $model_broadcast = new StZqBroadcast;
                    $model_result_express = new StZqResultExpress;

                    break;
                case 'lq':
                    $model_league = new StLqLeague;
                    $model_match = new StLqMatch;
                    $model_odds = new StLqOdds;
                    $model_odds_record = new StLqOddsRecord;
                    $model_result = new StLqResult;
                    $model_result_record = new StLqResultRecord;
                    $model_league_result = new StLqLeagueResult;
                    $model_local_league = new StLqLocalLeague;
                    $model_local_match = new StLqLocalMatch;
                    $model_broadcast = new StLqBroadcast;
                    $model_result_express = new StLqResultExpress;
                    break;
                case 'wq':
                    $model_league = new StWqLeague;
                    $model_match = new StWqMatch;
                    $model_odds = new StWqOdds;
                    $model_odds_record = new StWqOddsRecord;
                    $model_result = new StWqResult;
                    $model_result_record = new StWqResultRecord;
                    $model_league_result = new StWqLeagueResult;
                    $model_local_league = new StWqLocalLeague;
                    $model_local_match = new StWqLocalMatch;
                    $model_broadcast = new StWqBroadcast;
                    $model_result_express = new StWqResultExpress;
                    break;
                case 'bq':
                    $model_league = new StBqLeague;
                    $model_match = new StBqMatch;
                    $model_odds = new StBqOdds;
                    $model_odds_record = new StBqOddsRecord;
                    $model_result = new StBqResult;
                    $model_result_record = new StBqResultRecord;
                    $model_league_result = new StBqLeagueResult;
                    $model_local_league = new StBqLocalLeague;
                    $model_local_match = new StBqLocalMatch;
                    $model_broadcast = new StBqBroadcast;
                    $model_result_express = new StBqResultExpress;
                    break;
                default:
                    throw new \Exception(Response::generate(Response::ABNORMAL));
            }
        }
        $data = [
            'model_league' => $model_league,//联赛
            'model_match' => $model_match,//赛事
            'model_odds' => $model_odds,//赔率
            'model_result' => $model_result,//赛事结果
            'model_odds_record' => $model_odds_record,//赔率记录
            'model_result_record' => $model_result_record,//赛事结果记录
            'model_league_result' => $model_league_result,//联赛结果
            'model_local_league' => $model_local_league,//本地关联联赛
            'model_local_match' => $model_local_match,//本地关联赛事
            'model_broadcast' => $model_broadcast, //直播数据接口
            'model_result_express' => $model_result_express,//赛果数据
        ];
        return $data;
    }

    /**
     * @param $type_code
     * @return array
     * @throws \Exception
     * 获取不同状态下的 查询条件
     */
    function getState($type_code, $model_match = '')
    {
        if ($model_match == '') {
            switch ($type_code) {
                case 'StRollBall'://滚球 正在进行
                    $where = [
                        ['status', '=', '1'],
                    ];
                    break;
                case 'StSoon'://即将 今日两小时内开始
                    $where = [
                        ['status', '=', '0'],
                        ['match_date', '=', date("Y-m-d")],
                        ['match_time', '<', date("H:i:s", strtotime("+2 hour"))],
                        ['match_time', '>', date("H:i:s", time())]
                    ];
                    break;
                case 'StToday'://今日 今日未开始未结束
                    $where = [
                        ['match_date', '=', date("Y-m-d")],
                        ['match_time', '>', date("H:i:s", time())],
                    ];
                    break;
                case 'StMorningPlate'://早盘
                    $where = [
                        ['is_morningplate', '=', 1],
                        ['us_time', '>', $this->qgmdate('Y-m-d H:i:s', '', -4)],
                    ];
                    break;
                case 'StStringScene'://串场
                    $where = [
                        ['is_stringscene', '=', 1],
                        ['us_time', '>', $this->qgmdate('Y-m-d H:i:s', '', -4)],
                    ];
                    break;
                case 'StChampion'://冠军
                    $where = [
                        'type' => 1
                    ];
                    break;
                default:
                    throw new \Exception(Render([], '10002', lang('Tips', 'Sports')->get('PARAM_ERROR')));
            }
        } else {
            switch ($type_code) {
                case 'StRollBall'://滚球 正在进行
                    $where = [
                        [$model_match . '.status', '=', '1'],
                    ];
                    break;
                case 'StSoon'://即将 今日两小时内开始
                    $where = [
                        [$model_match . '.status', '=', '0'],
                        [$model_match . '.match_date', '=', date("Y-m-d")],
                        [$model_match . '.match_time', '<', date("H:i:s", strtotime("+2 hour"))],
                        [$model_match . '.match_time', '>', date("H:i:s", time())]
                    ];
                    break;
                case 'StToday'://今日 今日未开始未结束
                    $where = [
                        [$model_match . '.match_date', '=', date("Y-m-d")],
                        [$model_match . '.match_time', '>', date("H:i:s", time())],
                    ];
                    break;
                case 'all'://所有赛事
                    $where = [
                        [$model_match . '.status', '<', '2'],
                    ];
                    break;
                case 'StMorningPlate'://早盘
                    $where = [
                        [$model_match . '.is_morningplate', '=', 1],
                        [$model_match . '.us_time', '>', self::qgmdate('Y-m-d H:i:s', '', -4)],
                    ];
                    break;
                case 'StStringScene'://串场 查询串场状态为1 开赛时间大于当前时间
                    $where = [
                        [$model_match . '.is_stringscene', '=', 1],
                        [$model_match . '.us_time', '>', self::qgmdate('Y-m-d H:i:s', '', -4)],
                    ];
                    break;
                case 'StChampion'://冠军
                    $where = [
                        'type' => 1
                    ];
                    break;
                default:
                    throw new \Exception(Render([], '10002', lang('Tips', 'Sports')->get('PARAM_ERROR')));
            }
        }

        return $where;
    }

    /**
     * @param $data
     * @return array
     * 处理当国家下无联赛数据 删除该数组
     */
    function handleArr($data)
    {
        $hData = [];
        foreach ($data as $key => $v) {
            if (empty($v['league_count'])) {
                $v = [];
            }
            $hData[] = $v;
        }
        foreach ($hData as $k => $v) {
            if (empty($v)) {
                unset($hData[$k]);
            }
        }
        foreach ($hData as $k => $v) {
            $v['league_count'] = array_values($v['league_count']);
            $hData[$k] = $v;
        }

        return array_values($hData);
    }


    /**
     * @param $arr
     * @param $key
     * @return array
     * 去除二维数组重复项
     */
    function array_unset_tt($arr, $key)
    {
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if (isset($res[$value[$key]])) {
                unset($value[$key]);  //有：销毁
            } else {
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }

    /**
     * 处理冠军盘口 数组结构
     */
    function array_gj_tt($data, $oddsData)
    {
        foreach ($data as $k => &$v) {
            foreach ($v['league_count'] as $kk => &$vv) {
                foreach ($oddsData as $kkk => $vvv) {
                    if ($vv['lg_id'] == $vvv['lg_id']) {
                        $vv['oddsData'][] = $vvv;
                    }
                }

                if ($vv['oddsData']) {
                    $vv['oddsData'] = $this->array_unset_tt($vv['oddsData'], 'p_code');
                    $vv['count'] = count($vv['oddsData']);
                    unset($vv['oddsData']);
                }

                if (count($vv) == 5) {
                    unset($v['league_count'][$kk]);
                }
            }
            $v['league_count'] = array_values($v['league_count']);
            if (empty($v['league_count'])) {
                unset($data[$k]);
            }
        }

        return array_values($data);
    }

    /**
     * 处理冠军以外 数组结构
     */
    function array_other_tt($data, $matchData)
    {
        foreach ($data as $k => &$v) {
            foreach ($v['league_count'] as $kk => &$vv) {
                foreach ($matchData as $kkk => $vvv) {
                    if ($vv['lg_id'] == $vvv['lg_id']) {
                        $vv['matchData'][] = $vvv;
                    }
                }

                if ($vv['matchData']) {
                    $vv['matchData'] = $this->array_unset_tt($vv['matchData'], 'match_id');
                    $vv['count'] = count($vv['matchData']);
                    unset($vv['matchData']);
                }

                if (count($vv) == 5) {
                    unset($v['league_count'][$kk]);
                }
            }
            $v['league_count'] = array_values($v['league_count']);
            if (empty($v['league_count'])) {
                unset($data[$k]);
            }
        }

        return array_values($data);
    }

    /**
     * 时间格式化
     * @param string $dateformat 时间格式
     * @param int $timestamp 时间戳
     * @param int $timeoffset 时区偏差 默认8 北京时间 -4美东时间
     * @return string
     */
    public static function qgmdate($dateformat = 'Y-m-d H:i:s', $timestamp = '', $timeoffset = 8, $type = '')
    {
        if (empty($timestamp)) {
            $timestamp = time();
        }
        $result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
        return $result;
    }

    /**
     * 判断二维数组是否包含一维数组
     * @param mixed $arr 查询条件
     * @param mixed $arrs 运动类型
     * @return string
     */
    function judgeEqual($arr, $arrs)
    {
        foreach ($arrs as $value) {
            if (count($value) === count($arr)) {
                $a = 0;
                foreach ($value as $key => $v) {
                    $a++;
                    if ($v != $arr[$key]) {
                        break;
                    }
                    if ($a == count($key)) {    // 到最后一个元素都没有出现不相等，就说明这两个数组相等。
                        return true;
                    }
                }
            }
        }
        return false;
    }

// 排列
    function arrangement($a, $m)
    {
        $r = array();

        $n = count($a);
        if ($m <= 0 || $m > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; $i++) {
            $b = $a;
            $t = array_splice($b, $i, 1);
            if ($m == 1) {
                $r[] = $t;
            } else {
                $c = $this->arrangement($b, $m - 1);
                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }

// 组合
    function combination($a, $m)
    {
        $r = array();

        $n = count($a);
        if ($m <= 0 || $m > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; $i++) {
            $t = array($a[$i]);
            if ($m == 1) {
                $r[] = $t;
            } else {
                $b = array_slice($a, $i + 1);
                $c = $this->combination($b, $m - 1);
                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }

// 阶乘
    function factorial($n)
    {
        return array_product(range(1, $n));
    }

// 排列数
    function A1($n, $m)
    {
        return factorial($n) / factorial($n - $m);
    }

// 组合数
    function C1($n, $m)
    {
        return A1($n, $m) / factorial($m);
    }

    /**
     * @param $lg_id 数据源 联赛id
     * @param $source 数据源
     * @param $lg_data 本地关联记录
     * @return bool|mixed  成功 返回本地联赛id
     *
     * 验证本地联赛中是否存在 用于写入联赛/赛事数据验证
     */
    static function ver_league($lg_id, $source, $lg_data)
    {
        foreach ($lg_data as $item) {
            if (!is_array($item)) return false;
            if ($item['others_lg_id'] == $lg_id and $item['source'] == $source) return $item['lg_id'];
        }
        return false;
    }

    /**
     * @param $match_id 数据源 赛事id
     * @param $source 数据源
     * @param $match_data 本地赛事记录
     * @return bool|mixed 成功返回本地赛事id
     * 验证本地赛事记录是否存在
     */
    static function ver_match($match_id, $source, $match_data)
    {
        foreach ($match_data as $item) {
            if (!is_array($item)) return false;
            if ($item['others_match_id'] == $match_id and $item['source'] == $source) return $item['match_id'];
        }
        return false;
    }


    /**
     * @param $sole 唯一标识
     * @param $source 数据源
     * @param $odds_data 赔率数据
     * @return bool|mixed 成功返回 赔率id
     * 验证赔率
     */
    static function ver_odds($sole, $source, $odds_data)
    {
        foreach ($odds_data as $item) {
            if (!is_array($item)) return false;
            if ($item['sole'] == $sole and $item['source'] == $source) return $item['id'];
        }
        return false;
    }

    /**
     * @param $odds_only 匹配更新
     * @param $source 数据源
     * @param $odds_record_data 赔率记录数据
     * @return bool|mixed 成功返回 赔率记录id
     * 验证赔率记录
     */
    static function ver_odds_record($odds_only, $source, $odds_record_data)
    {
        foreach ($odds_record_data as $item) {
            if (!is_array($item)) return false;
            if ($item['odds_only'] == $odds_only and $item['source'] == $source) return $item['id'];
        }
        return false;
    }

    /**
     * 二维数组根据某个字段去重
     * @param array $array 二维数组
     * @para array  去重后的数组
     */
    static function uniquArr($array, $key)
    {
        $result = array();
        foreach ($array as $k => $val) {
            $code = false;
            foreach ($result as $_val) {
                if ($_val[$key] == $val[$key]) {
                    $code = true;
                    break;
                }
            }
            if (!$code) {
                $result[] = $val;
            }
        }
        return $result;
    }

    /**
     * 二维数组 按指定键去重
     */
    static function uniquArrV2($array, $key)
    {
        $result = [];
        foreach ($array as $val) {
            $keyval = $val[$key];
            if (!isset($result[$keyval])) {
                $result[$keyval] = $val;
            }
        }
        return array_values($result);
    }


    /**
     * 按字段 搜索 二维数组
     */
    static function searcharray($value, $key, $array, $r_key = '')
    {
        foreach ($array as $k => $val) {
            if ($val[$key] == $value) {
                return $val[$r_key];
            }
        }
        return null;
    }

    /**
     * 滚球投注 危险球审核
     * $bet_match 投注赛事数据
     * $result_match_r 投注赛事结果记录
     */
    static function WARN_CHECK($bet_match = '', $result_match = [])
    {
        /*
        危险球定义：
            1.角球
            2. 12码罚球
            3.自由球(攻方在守方禁区附近的自由球)
            4.掷入球(攻方靠近守方禁区的掷入球)
            5.一队向另一队禁区附近进攻
            ...
        危险球审核时间：
            下注成功后60~90秒
        */

        $defdata = [
            'code' => 1,
            'warn_more' => '',
        ];

        if (!empty($bet_match) and !empty($result_match)) {
            //获取投注时间  时间戳
            $bet_time = strtotime($bet_match->ctime);
            //取出所有有危险球的数据
            $warn_more = trim($result_match[0]->warn_more);

            //当值为默认值时，表示没有危险球，不用再作判断了
            if ($warn_more == '[{"timei":"1970-1-1 0:0:1","rtype":0}]' || $warn_more == '' || $warn_more == '[]') {
                return $defdata;
            }

            //json转数组
            $warn_more = json_decode($warn_more, true);
            foreach ($warn_more as $k => $v) {
                //获取危险球出现时间 转时间戳
                $warn_time = strtotime($v['timei']);

                if (($warn_time - $bet_time) < 90 && ($warn_time - $bet_time) >= 0) {
                    $data = [
                        'code' => -1,
                        'warn_more' => $v
                    ];
                    return $data;
                }
            }

            return $defdata;
        }
    }


    //写入赛事数据日志文件
    static function SET_SPORTS_RECORD($game_code, $getData = [], $title, $msg)
    {
        //中文不转义
        $json_data = json_encode($getData, JSON_UNESCAPED_UNICODE);
        Log::getMonolog()->popHandler();
        Log::useFiles(storage_path('logs/set_sports_record/' . date('Y-m-d', time()) . '/' . $game_code . '/' . $title . '.log'), 'info');
        Log::info('--->msg:' . $msg . ';data:' . $json_data);
    }

    //写入赛事数据日志文件
    static function SET_NOMAM_RECORD($msg, $getData = [], $fileName = '')
    {
        $json_data = json_encode($getData, JSON_UNESCAPED_UNICODE);
        Log::getMonolog()->popHandler();
        if ($fileName) {
            $lastfileName = date('Y-m', time()) . '_' . $fileName . '.log';
        } else {
            $lastfileName = date('Y-m', time()) . '.log';
        }
        Log::useFiles(storage_path('logs/' . $lastfileName), 'info');
        Log::info($msg . ' -- ' . $json_data);
    }


    /*
     * 根据二维数组某个字段的值查找数组
     * $array 数组
     * 查询字段
     * $value 字段值
    */
    static function filter_by_value($array_l, $index, $value)
    {
        $data_json = json_encode($array_l);
        $array = json_decode($data_json, true);
        if (is_array($array) && count($array) > 0) {
            foreach (array_keys($array) as $key) {
                $temp[$key] = $array[$key][$index];

                if ($temp[$key] == $value) {
                    $newarray = $array[$key];
                    return $newarray;

                }
            }
        }
        return [];
    }


    //http 请求
    public static function https_request($curl, $data=null, $https=true, $method='post'){
        $ch = curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL, $curl);//设置访问的URL
        curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
        if($https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
        }
        if($method == 'post'){
            curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
        }
        $str = curl_exec($ch);//执行访问，返回结果
        curl_close($ch);//关闭curl，释放资源
        return $str;
    }


     //根据球类追加限定玩法
     public static function getOddsPcode($game_code = 'zq'){

        $p_code = [];

        if($game_code == 'zq'){
            $p_code = ['C','B','TG','CB','TB','GS','CO','TS'];
        }
        if($game_code == 'lq'){
            $p_code = ['LN','C','TN','TS','TB','CO'];
        }
        if($game_code == 'wq'){
            $p_code = ['LB','TN','TS','B','LD','C'];
        }
        if($game_code == 'bq'){
            $p_code = ['CO','C','TN','TS'];
        }

        return $p_code;
    }

    /**
	 * 赛事下注单作废处理
	 */
	public static function HandleInvalid($data=[],$match_id='',$match_status='',$game_code='',$process){
		//===作废处理===
		$moneyBuyMatch = new \App\Models\MoneyBuyMatch();

		//获取赛事下所有单式注单
		$select = ['money_buy_simplex.order_id', 'money_buy_simplex.match_id', 'money_buy_simplex.account_identity', 'money_buy_simplex.account_name','money_buy_simplex.money', 'money_buy_simplex.gain_money', 'money_buy_simplex.status', 'money_buy_simplex.settle_status', 'money_buy_simplex.game_status', 'money_buy_simplex.batch_id','money_buy_match.odds_code','money_buy_match.result','st_odds_code.odds_name'];
		//obj
        $match_order_sim_obj = $moneyBuyMatch->allsimplexorder($match_id,$game_code,$select);

		//获取赛事下所有串式注单
		$select = ['money_buy_str.order_id', 'money_buy_match.match_id', 'money_buy_str.account_identity', 'money_buy_str.account_name','money_buy_str.money', 'money_buy_str.gain_money','money_buy_str.status','money_buy_str.settle_status','money_buy_str.game_status','money_buy_str.str_type','st_odds_code.odds_name','money_buy_match.odds_code','money_buy_match.result',];
		//obj
		$match_order_str_obj = $moneyBuyMatch->allstrorder($match_id,$game_code,$select);

        //如果赛事下有 单式 注单
        $oddsData_sim = [];
        $oddsData_sim_settle = [];
		if(count($match_order_sim_obj) > 0 ){
			//获取单式注单中 待处理注单
			$oddsData_sim = self::getOrderData($data,$match_order_sim_obj,$game_code,$process);
            $oddsData_sim_settle = $oddsData_sim['settle'];
            $oddsData_sim = $oddsData_sim['invalid'];
		}

        //如果赛事下有 串式 注单
        $oddsData_str = [];
        $oddsData_str_settle = [];
		if(count($match_order_str_obj) > 0){
			//获取串式注单中 待处理注单
			$oddsData_str = self::getOrderData($data,$match_order_str_obj,$game_code,$process);
            $oddsData_str_settle = $oddsData_str['settle'];
            $oddsData_str = $oddsData_str['invalid'];
		}

        //修改赛事结果后注单状态修改为未结算
        $upapp = new \App\Models\SportsNoteList();
        $upapp->settleorder($match_id,$oddsData_sim_settle,$oddsData_str_settle,$game_code);

		//如果是已结算赛事
//		if($match_status == 3){
			//合并上半场/全场 待处理 单式+串式订单
			$oddsData = array_merge($oddsData_sim,$oddsData_str);
			//去重
            $oddsData = self::uniquArrV2($oddsData,'order_id');

            if(count($oddsData) > 0){
                $url = 'http://stadmin.bocai108.com:9094/UnsetOneOrder';
                $data_up = [
                    'token'=>session('adminInfo.token'),
                    'game_code'=>$game_code,
                    'match_id'=>$match_id,
                ];

                //返回请求状态码
                $set_status = [];
                foreach($oddsData as $k=>$v){
                    $data_up['order_id'] = $v['order_id'];
                    $ret_json = self::https_request($url,$data_up);
                    $ret_arr = json_decode($ret_json,true);
                    $set_status[] = $ret_arr['status'];
                }
                //如果返回结果中有 0,则返回失败
                if(in_array(0,$set_status)){
                    return responseToJson(-20003);
                }
            }
//		}else{
            //赛事 处理 下单式注单作废，串关注单下此赛事按平局处理
//            if(count($oddsData_str) > 0){
//                $oddsData_str = $oddsData_str;
//            }
//            $type = 1;
//			$upapp->delorder($match_id,$game_code,$oddsData_sim,$oddsData_str,$type);
		//}
		//=== end ===
	}
	/**
	 * 获取赛事下 符合条件 待处理注单
	 */
	public static function getOrderData($data,$match_order,$game_code,$process){
		//===足球===
		if($game_code == 'zq'){
            //主队上半场角球(作废)
            $matchOdds_hch = [];
            //主队上半场角球(待结算)
            $matchOdds_halfch = [];
            //客队上半场角球(作废)
            $matchOdds_hcg = [];
            //客队上半场角球(待结算)
            $matchOdds_halfcg = [];
            //主队全场角球(作废)
            $matchOdds_fch = [];
            //主队全场角球(待结算)
            $matchOdds_fallch = [];
            //客队全场角球(作废)
            $matchOdds_fcg = [];
            //客队全场角球(待结算)
            $matchOdds_fallcg = [];
            //主队上半场罚牌(作废)
            $matchOdds_hph = [];
            //主队上半场罚牌(待结算)
            $matchOdds_halfph = [];
            //客队上半场罚牌(作废)
            $matchOdds_hpg = [];
            //客队上半场罚牌(待结算)
            $matchOdds_halfpg = [];
            //主队全场罚牌(作废)
            $matchOdds_fph = [];
            //主队全场罚牌(待结算)
            $matchOdds_fallph = [];
            //客队全场罚牌(作废)
            $matchOdds_fpg = [];
            //客队全场罚牌(待结算)
            $matchOdds_fallpg = [];
            //上半场(作废)
            $matchOdds_h = [];
            //上半场(待结算)
            $matchOdds_half = [];
            //全场(作废)
            $matchOdds_f = [];
            //全场(待结算)
            $matchOdds_fall = [];
            foreach($match_order as $k=>$v){
                //主队上半场角球条件
                if($data != [] and $data['half_corner']['home'] == -1){
                    if($v->status == 1){
                        $matchOdds_hch[] = self::getOrderJC('角球|上半场|主队',$v);
                    }
                }else{
                    $matchOdds_halfch[] = self::getOrderJC('角球|上半场|主队',$v);
                }
                //客队上半场角球条件
                if($data != [] and $data['half_corner']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_hcg[] = self::getOrderJC('角球|上半场|客队',$v);
                    }
                }else{
                    $matchOdds_halfcg[] = self::getOrderJC('角球|上半场|客队',$v);
                }
                //主队全场角球条件
                if($data != [] and $data['all_corner']['home'] == -1){
                    if($v->status == 1){
                        $matchOdds_fch[] = self::getOrderJC('角球|全场|主队',$v);
                    }
                }else{
                    $matchOdds_fallch[] = self::getOrderJC('角球|全场|主队',$v);
                }
                //客队全场角球条件
                if($data != [] and $data['all_corner']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_fcg[] = self::getOrderJC('角球|全场|客队',$v);
                    }
                }else{
                    $matchOdds_fallcg[] = self::getOrderJC('角球|全场|客队',$v);
                }
                //主队上半场罚牌条件
                if($data != [] and $data['half_penalty']['home'] == -1){
                    if($v->status == 1){
                        $matchOdds_hph[] = self::getOrderJC('罚牌数|上半场|主队',$v);
                    }
                }else{
                    $matchOdds_halfph[] = self::getOrderJC('罚牌数|上半场|主队',$v);
                }
                //客队上半场罚牌条件
                if($data != [] and $data['half_penalty']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_hpg[] = self::getOrderJC('罚牌数|上半场|客队',$v);
                    }
                }else{
                    $matchOdds_halfpg[] = self::getOrderJC('罚牌数|上半场|客队',$v);
                }
                //主队全场罚牌条件
                if($data != [] and $data['all_penalty']['home'] == -1){
                    if($v->status == 1){
                        $matchOdds_fph[] = self::getOrderJC('罚牌数|全场|主队',$v);
                    }
                }else{
                    $matchOdds_fallph[] = self::getOrderJC('罚牌数|全场|主队',$v);
                }
                //客队全场罚牌条件
                if($data != [] and $data['all_penalty']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_fpg[] = self::getOrderJC('罚牌数|全场|客队',$v);
                    }
                }else{
                    $matchOdds_fallpg[] = self::getOrderJC('罚牌数|全场|客队',$v);
                }

                //上半场条件
                if($data != [] and $data['half']['home'] == -1 and $data['half']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_h[] = self::getOrderJC('上半场',$v);
                    }
                }else{
                    $matchOdds_half[] = self::getOrderJC('上半场',$v);
                }
                //全场条件
                if($data != [] and $data['all']['home'] == -1 and $data['all']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_f[] = self::getOrderJC('全场',$v);
                        $matchOdds_f[] = self::getOrderJC('净胜',$v);
                    }
                }
                else{
                    $matchOdds_fall[] = self::getOrderJC('全场',$v);
                    $matchOdds_fall[] = self::getOrderJC('净胜',$v);
                }
            }

            //合并待处理 注单
            $orderData['invalid'] = array();
            $orderData['settle'] = array();
            if(in_array('half_corner_home',$process) || in_array('half_corner',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_hch);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_halfch);
            }
            if(in_array('half_corner_guest',$process) || in_array('half_corner',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_hcg);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_halfcg);
            }
            if(in_array('all_corner_home',$process) || in_array('all_corner',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fch);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fallch);
            }
            if(in_array('all_corner_guest',$process) || in_array('all_corner',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fcg);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fallcg);
            }
            if(in_array('half_penalty_home',$process) || in_array('half_penalty',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_hph);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_halfph);
            }
            if(in_array('half_penalty_guest',$process) || in_array('half_penalty',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_hpg);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_halfpg);
            }
            if(in_array('all_penalty_home',$process) || in_array('all_penalty',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fph);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fallph);
            }
            if(in_array('all_penalty_guest',$process) || in_array('all_penalty',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fpg);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fallpg);
            }
            if(in_array('half',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_h);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_half);
            }
            if(in_array('all',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_f);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fall);
            }
        }
        //====end===

        //==篮球===
        if($game_code == 'lq'){

            //第一节(作废)
            $matchOdds_o = [];
            //第一节(待结算)
            $matchOdds_one = [];
            //第二节(作废)
            $matchOdds_t = [];
            //第二节(待结算)
            $matchOdds_two = [];
            //第三节(作废)
            $matchOdds_s = [];
            //第三节(待结算)
            $matchOdds_three = [];
            //第四节(作废)
            $matchOdds_f = [];
            //第四节(待结算)
            $matchOdds_four = [];
            //上半场(作废)
            $matchOdds_hh = [];
            //上半场(待结算)
            $matchOdds_half = [];
            //下半场(作废)
            $matchOdds_ll = [];
            //下半场(待结算)
            $matchOdds_next = [];
            //全场(作废)
			$matchOdds_ff = [];
            //全场(待结算)
            $matchOdds_fall = [];
            
            foreach($match_order as $k=>$v){
                //第一节条件
                if($data != [] and $data[1]['home'] == -1 and $data[1]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_o[] = self::getOrderJC('一节',$v);
                    }
                }else{
                    $matchOdds_one[] = self::getOrderJC('一节',$v);
                }
                //第二节条件
                if($data != [] and $data[2]['home'] == -1 and $data[2]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_t[] = self::getOrderJC('二节',$v);
                    }
                }else{
                    $matchOdds_two[] = self::getOrderJC('二节',$v);
                }
                //第三节条件
                if($data != [] and $data[3]['home'] == -1 and $data[3]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_s[] = self::getOrderJC('三节',$v);
                    }
                }else{
                    $matchOdds_three[] = self::getOrderJC('三节',$v);
                }
                //第四节条件
                if($data != [] and $data[4]['home'] == -1 and $data[4]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_f[] = self::getOrderJC('四节',$v);
                    }
                }else{
                    $matchOdds_four[] = self::getOrderJC('四节',$v);
                }
                //上半场条件
                if($data != [] and $data[5]['home'] == -1 and $data[5]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_hh[] = self::getOrderJC('上半场',$v);
                    }
                }else{
                    $matchOdds_half[] = self::getOrderJC('上半场',$v);
                }
                //下半场条件
                if($data != [] and $data[6]['home'] == -1 and $data[6]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_ll[] = self::getOrderJC('下半场',$v);
                    }
                }else{
                    $matchOdds_next[] = self::getOrderJC('下半场',$v);
                }
                //全场条件
                if($data != [] and $data['all']['home'] == -1 and $data['all']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_ff[] = self::getOrderJC('全场',$v);
                        $matchOdds_ff[] = self::getOrderJC('最后一位数',$v);
                    }
                }else{
                    $matchOdds_fall[] = self::getOrderJC('全场',$v);
                    $matchOdds_fall[] = self::getOrderJC('最后一位数',$v);
                }

            }
            //合并待处理 注单
            $orderData['invalid'] = array();
            $orderData['settle'] = array();
            if(in_array('one',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_o);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_one);
            }
            if(in_array('two',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_t);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_two);
            }
            if(in_array('three',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_s);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_three);
            }
            if(in_array('four',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_f);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_four);
            }
            if(in_array('uhalf',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_hh);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_half);
            }
            if(in_array('dhalf',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_ll);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_next);
            }
            if(in_array('all',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_ff);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fall);
            }
        }
        //===end===

        //===网球===
        if($game_code == 'wq'){
            //第一盘(作废)
            $matchOdds_o = [];
            //第一盘(待结算)
            $matchOdds_one = [];
            //第二盘(作废)
            $matchOdds_t = [];
            //第二盘(待结算)
            $matchOdds_two = [];
            //第三盘(作废)
            $matchOdds_s = [];
            //第三盘(待结算)
            $matchOdds_three = [];
            //第四盘(作废)
            $matchOdds_fo = [];
            //第四盘(待结算)
            $matchOdds_four = [];
            //第五盘(作废)
            $matchOdds_fi = [];
            //第五盘(待结算)
            $matchOdds_five = [];
            //全场(作废)
            $matchOdds_ff = [];
            //全场(待结算)
            $matchOdds_fall = [];

            foreach($match_order as $k=>$v){
                //第一盘条件
                if($data != [] and $data[1]['home'] == -1 and $data[1]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_o[] = self::getOrderJC('一盘',$v);
                    }
                }else{
                    $matchOdds_one[] = self::getOrderJC('一盘',$v);
                }
                //第二盘条件
                if($data != [] and $data[2]['home'] == -1 and $data[2]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_t[] = self::getOrderJC('二盘',$v);
                    }
                }else{
                    $matchOdds_two[] = self::getOrderJC('二盘',$v);
                }
                //第三盘条件
                if($data != [] and $data[3]['home'] == -1 and $data[3]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_s[] = self::getOrderJC('三盘',$v);
                    }
                }else{
                    $matchOdds_three[] = self::getOrderJC('三盘',$v);
                }
                //第四盘条件
                if($data != [] and $data[4]['home'] == -1 and $data[4]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_fo[] = self::getOrderJC('四盘',$v);
                    }
                }else{
                    $matchOdds_four[] = self::getOrderJC('四盘',$v);
                }
                //第五盘条件
                if($data != [] and $data[5]['home'] == -1 and $data[5]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_fi[] = self::getOrderJC('五盘',$v);
                    }
                }else{
                    $matchOdds_five[] = self::getOrderJC('五盘',$v);
                }
                //全场条件
                if($data != [] and $data['all']['home'] == -1 and $data['all']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_ff[] = self::getOrderJC('让盘',$v);
                        $matchOdds_ff[] = self::getOrderJC('让局',$v);
                        $matchOdds_ff[] = self::getOrderJC('总局数',$v);
                        $matchOdds_ff[] = self::getOrderJC('冠军',$v);
                    }
                }else{
                    $matchOdds_fall[] = self::getOrderJC('让盘',$v);
                    $matchOdds_fall[] = self::getOrderJC('让局',$v);
                    $matchOdds_fall[] = self::getOrderJC('总局数',$v);
                    $matchOdds_fall[] = self::getOrderJC('冠军',$v);
                }
            }
            //合并待处理 注单
            //合并待处理 注单
            $orderData['invalid'] = array();
            $orderData['settle'] = array();
            if(in_array('one',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_o);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_one);
            }
            if(in_array('two',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_t);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_two);
            }
            if(in_array('three',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_s);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_three);
            }
            if(in_array('four',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fo);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_four);
            }
            if(in_array('five',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fi);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_five);
            }
            if(in_array('all',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_ff);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fall);
            }
        }
        //===end===

        //===棒球===
        if($game_code == 'bq'){
            //第一局(作废)
            $matchOdds_o = [];
            //第一局(待结算)
            $matchOdds_one = [];
            //第二局(作废)
            $matchOdds_t = [];
            //第二局(待结算)
            $matchOdds_two = [];
            //第三局(作废)
            $matchOdds_th = [];
            //第三局(待结算)
            $matchOdds_three = [];
            //第四局(作废)
            $matchOdds_fo = [];
            //第四局(待结算)
            $matchOdds_four = [];
            //第五局(作废)
            $matchOdds_fi = [];
            //第五局(待结算)
            $matchOdds_five = [];
            //第六局(作废)
            $matchOdds_si = [];
            //第六局(待结算)
            $matchOdds_six = [];
            //第七局(作废)
            $matchOdds_se = [];
            //第七局(待结算)
            $matchOdds_seven = [];
            //第八局(作废)
            $matchOdds_e = [];
            //第八局(待结算)
            $matchOdds_eight = [];
            //第九局(作废)
            $matchOdds_n = [];
            //第九局(待结算)
            $matchOdds_nine = [];
            //其他(作废)
            $matchOdds_ot = [];
            //其他(待结算)
            $matchOdds_other = [];
            //前五局(作废)
            $matchOdds_five = [];
            //前五局(待结算)
            $matchOdds_fives = [];
            //全场(作废)
            $matchOdds_ff = [];
            //全场(待结算)
            $matchOdds_fall = [];

            foreach($match_order as $k=>$v){
                //第一局条件
                if($data != [] and $data[1]['home'] == -1 and $data[1]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_o[] = self::getOrderJC('第一局',$v);
                    }
                }else{
                    $matchOdds_one[] = self::getOrderJC('第一局',$v);
                }
                //第二局条件
                if($data != [] and $data[2]['home'] == -1 and $data[2]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_t[] = self::getOrderJC('第二局',$v);
                    }
                }else{
                    $matchOdds_two[] = self::getOrderJC('第二局',$v);
                }
                //第三局条件
                if($data != [] and $data[3]['home'] == -1 and $data[3]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_th[] = self::getOrderJC('第三局',$v);
                    }
                }else{
                    $matchOdds_three[] = self::getOrderJC('第三局',$v);
                }
                //第四局条件
                if($data != [] and $data[4]['home'] == -1 and $data[4]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_fo[] = self::getOrderJC('第四局',$v);
                    }
                }else{
                    $matchOdds_four[] = self::getOrderJC('第四局',$v);
                }
                //第五局条件
                if($data != [] and $data[5]['home'] == -1 and $data[5]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_fi[] = self::getOrderJC('第五局',$v);
                    }
                }else{
                    $matchOdds_five[] = self::getOrderJC('第五局',$v);
                }
                //第六局条件
                if($data != [] and $data[6]['home'] == -1 and $data[6]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_si[] = self::getOrderJC('第六局',$v);
                    }
                }else{
                    $matchOdds_six[] = self::getOrderJC('第六局',$v);
                }
                //第七局条件
                if($data != [] and $data[7]['home'] == -1 and $data[7]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_se[] = self::getOrderJC('第七局',$v);
                    }
                }else{
                    $matchOdds_seven[] = self::getOrderJC('第七局',$v);
                }
                //第八局条件
                if($data != [] and $data[8]['home'] == -1 and $data[8]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_e[] = self::getOrderJC('第八局',$v);
                    }
                }else{
                    $matchOdds_eight[] = self::getOrderJC('第八局',$v);
                }
                //第九局条件
                if($data != [] and $data[9]['home'] == -1 and $data[9]['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_n[] = self::getOrderJC('第九局',$v);
                    }
                }else{
                    $matchOdds_nine[] = self::getOrderJC('第九局',$v);
                }
                //其他条件
                if($data != [] and $data['other']['home'] == -1 and $data['other']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_ot[] = self::getOrderJC('其他',$v);
                    }
                }else{
                    $matchOdds_other[] = self::getOrderJC('其他',$v);
                }
                //前五局条件
                if($data != [] and $data['five']['home'] == -1 and $data['five']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_five[] = self::getOrderJC('前5局',$v);
                    }
                }else{
                    $matchOdds_fives[] = self::getOrderJC('前5局',$v);
                }
                //全场条件
                if($data != [] and $data['all']['home'] == -1 and $data['all']['guest'] == -1){
                    if($v->status == 1){
                        $matchOdds_ff[] = self::getOrderJC('全场',$v);
                    }
                }else{
                    $matchOdds_fall[] = self::getOrderJC('全场',$v);
                }

            }
            //合并待处理 注单
            $orderData['invalid'] = array();
            $orderData['settle'] = array();
            if(in_array('one',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_o);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_one);
            }
            if(in_array('two',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_t);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_two);
            }
            if(in_array('three',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_th);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_three);
            }
            if(in_array('four',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fo);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_four);
            }
            if(in_array('five',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_fi);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_five);
            }
            if(in_array('six',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_si);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_six);
            }
            if(in_array('seven',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_se);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_seven);
            }
            if(in_array('eight',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_e);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_eight);
            }
            if(in_array('nine',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_n);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_nine);
            }
            if(in_array('other',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_ot);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_other);
            }
            if(in_array('sfive',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_five);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fives);
            }
            if(in_array('all',$process)){
                $orderData['invalid'] = array_merge($orderData['invalid'],$matchOdds_ff);
                $orderData['settle'] = array_merge($orderData['settle'],$matchOdds_fall);
            }
        }
        //===end===
		
		return $orderData;
    }
    
    /**
     * 匹配各进程注单
     * $str str 搜索关键字
     * $v arr 注单数据
     */
    public static function getOrderJC($str,$v){
        $tmparray = explode($str,$v['odds_name']);
        if(count($tmparray) > 1){
            return  $v;
        }
    }

    /**
     * 匹配字符串中 是否包含某个字符串
     * $strAll str 目标字符串
     * $needle str 搜索字符串
     */
    public static function checkstr($strAll,$needle){
        $tmparray = explode($needle,$strAll);
        if(count($tmparray)>1){
         return 1;
        } else{
         return 0;
        }
    }

    //根据球类返回赛事进程数据
    public static function getprocess($game_code = 'zq'){

        $process = [];

        if($game_code == 'zq'){
            $process[] = ['process'=>'half_corner','name'=>'结算上半场角球'];
            $process[] = ['process'=>'all_corner','name'=>'结算全场角球'];
            $process[] = ['process'=>'half','name'=>'结算上半场'];
            $process[] = ['process'=>'all','name'=>'结算全场'];
        }
        if($game_code == 'lq'){
            $process[] = ['process'=>'one','name'=>'结算第一节'];
            $process[] = ['process'=>'two','name'=>'结算第二节'];
            $process[] = ['process'=>'three','name'=>'结算第三节'];
            $process[] = ['process'=>'four','name'=>'结算第四节'];
            $process[] = ['process'=>'uhalf','name'=>'结算上半场'];
            $process[] = ['process'=>'dhalf','name'=>'结算下半场'];
            $process[] = ['process'=>'all','name'=>'结算全场'];
        }
        if($game_code == 'wq'){
            $process[] = ['process'=>'one','name'=>'结算第一盘'];
            $process[] = ['process'=>'two','name'=>'结算第二盘'];
            $process[] = ['process'=>'three','name'=>'结算第三盘'];
            $process[] = ['process'=>'four','name'=>'结算第四盘'];
            $process[] = ['process'=>'five','name'=>'结算第五盘'];
            $process[] = ['process'=>'all','name'=>'结算全场'];
        }
        if($game_code == 'bq'){
            $process[] = ['process'=>'one','name'=>'结算第一局'];
            $process[] = ['process'=>'two','name'=>'结算第二局'];
            $process[] = ['process'=>'three','name'=>'结算第三局'];
            $process[] = ['process'=>'four','name'=>'结算第四局'];
            $process[] = ['process'=>'five','name'=>'结算第五局'];
            $process[] = ['process'=>'six','name'=>'结算第六局'];
            $process[] = ['process'=>'seven','name'=>'结算第七局'];
            $process[] = ['process'=>'eight','name'=>'结算第八局'];
            $process[] = ['process'=>'nine','name'=>'结算第九局'];
            $process[] = ['process'=>'other','name'=>'结算第十局'];
            $process[] = ['process'=>'sfive','name'=>'结算前五局'];
            $process[] = ['process'=>'all','name'=>'结算全场'];
        }

        return $process;
    }

     /**
     * 处理 拼接手动结果数据
     * $manual_result_data arr 多个赛事手动结果数据
     * $match_id int 赛事id
     * $auto_result arr 自动结果
     */
    public static function getManual_result($manual_result_data,$auto_result,$match_id){
        $resultData = self::filter_by_value($manual_result_data,'match_id',$match_id);
        //手动结果数据 json
        $manual_result_json = $resultData['manual_result'];
        //手动结果数据 arr
        $manual_result_arr = json_decode($manual_result_json,true);

        //拼接手动数据
        foreach($manual_result_arr as $k=>$v){
            foreach($auto_result as $kk=>$vv){
                //赋值 
                if($k == $kk){
                    if(empty($v['home']) || empty($v['guest'])){
                        $v['home'] = $vv['home']?:0;
                        $v['guest'] = $vv['guest']?:0;
                    }
                }
            }
           
            $manual_result_arr[$k] =$v;
        }
        //转回json
        $manual_result_json = json_encode($manual_result_arr);

        return $manual_result_json;
    }
}

?>
