<?php
require '../zciyphp/comm.php'; //需要全局函数
function matchroute($str, $webpoint) {
    $pathsplits = explode('/', $str);
    $pathsplits = array_values(array_filter($pathsplits, 'strlen'));
    $pathcount = count($pathsplits);
    foreach ($webpoint as $key => $value) {
        $keysplits = explode('/', $key);
        $n = count($keysplits);
        if ($n != $pathcount)
            continue;
        $macth = true;
        for ($i = 0; $i < $n; $i++) {
            if ($keysplits[$i][0] === '{') {
                $_GET[substr($keysplits[$i], 1, -1)] = $pathsplits[$i];
            } else if ($keysplits[$i] != $pathsplits[$i]) {
                $macth = false;
                break;
            }
        }
        if (!$macth)
            continue;
        $idx = strpos($value, '?');
        if ($idx !== false) {
            $params = substr($value, $idx + 1);
            $value = substr($value, 0, $idx);
            parse_str($params, $paramsarr);
            foreach ($paramsarr as $k => $v) {
                $_GET[$k] = $v;
            }
        }
        return $value;
    }
    return $str;
}

if (!isset($_SERVER['REQUEST_URI']))
    die('nginx配置错误，REQUEST_URI未设置');
$qstr = $_SERVER['REQUEST_URI'];  //   例: admin/rig/user.list
$qstrarr = explode('.', $qstr);
$ms = timems();
if (count($qstrarr) < 2) {
    if (!file_exists(PATH_ROOT . 'webpoint.php'))
        die('无/webpoint.php文件');
    $phpfile = $qstrarr[0];
    $idx = strpos($phpfile, '?');
    if ($idx !== false)
        $phpfile = substr($phpfile, 0, $idx);
    $phpfile = trim($phpfile, '/');
    if (strtolower(substr($phpfile, 0, 3)) === 'www')
        die('预留www开头目录，不能使用');
    $_webpoint_config = require PATH_ROOT . 'webpoint.php';
    $phpfile = matchroute($phpfile, $_webpoint_config);
    $phprequi = PATH_WEB . $phpfile . '.php';
    if (!file_exists($phprequi)) {
        $phprequi = PATH_WEB . $phpfile . '/index.php';
        if (!file_exists($phprequi))
            die('/web/' . $phpfile . '.php' . '文件不存在!');
    }
    if (strpos($phprequi, '..') !== false)
        die('路径错误!');
    $db = new ciy\db(); //默认数据库全局变量
    require $phprequi;
    die;
}

$qs0 = $qstrarr[0];
$qstrarr[0] = str_replace('\\\\', '\\', 'web\\' . str_replace('/', '\\', $qstrarr[0]));
if (!class_exists($qstrarr[0])){
    $retarr = array('code' => 9, 'errmsg' => $qstrarr[0] . '无效类');
    ciy_ouputJSON($retarr, timems() - $ms, $_SERVER['REQUEST_URI']);
}
$idx = strpos($qstrarr[1], '?');
if ($idx !== false)
    $qstrarr[1] = substr($qstrarr[1], 0, $idx);
$db = new ciy\db(); //默认数据库全局变量
if (method_exists($qstrarr[0], 'json_' . $qstrarr[1])) {
    $qs0 = substr($qs0, 0, strpos($qs0, '/', 1));
    if (file_exists(PATH_WEB . $qs0 . '/common.php'))
        require PATH_WEB . $qs0 . '/common.php'; //需要全局业务函数和全局变量
    // $dbrd1 = new ciy\db('rd1');//读库  可实现注册中心取一个空闲实例  业务端判断
    // $dbag = new ciy\db('ag');//独立ag库
    // web\admin\autotask\task::json_run
    $retarr = call_user_func($qstrarr[0] . '::json_' . $qstrarr[1]);
    if (!is_array($retarr))
        die('{"errmsg":"无succ返回值"}');
    if ($retarr['code'] == 302) {
        header('Location: ' . $retarr['redirect']);
        die;
    }
    ciy_ouputJSON($retarr, timems() - $ms, $_SERVER['REQUEST_URI']);
} else if (method_exists($qstrarr[0], 'sse_' . $qstrarr[1])) {
    //https://html.spec.whatwg.org/multipage/server-sent-events.html
    $qs0 = substr($qs0, 1, strpos($qs0, '/', 1));
    if (file_exists(PATH_WEB . $qs0 . '/common.php'))
        require PATH_WEB . $qs0 . '/common.php'; //需要全局业务函数和全局变量

    if (get('debug') == 'yes') {
        call_user_func($qstrarr[0] . '::sse_' . $qstrarr[1], function ($data, $type = '') {
            if ($type === true)
                return;
            //$data = '<code style="color:#199d01;">' . $data . '</code>';
            else if ($type != '')
                $data = '<kbd style="color:#ffffff;background:#000000;margin:0.2em 0.5em; padding:0.2em;">' . $type . '</kbd>' . $data;
            echo $data . '<br/>';
        });
    } else {
        set_time_limit(0);
        ini_set('output_buffering', 'off');
        ini_set('zlib.output_compression', false);
        while (@ob_end_flush()) {
        }
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no');
        ob_start();
        $retarr = call_user_func($qstrarr[0] . '::sse_' . $qstrarr[1], function ($data, $id = '') {
            if (is_object($data) || is_array($data))
                $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            // if (strpos($data, "\n") !== false)
            //     $data = 'base64,' . base64_encode($data);
            if (empty($id))
                echo 'data: ' . $data . "\n\n";
            else
                echo 'data: ' . $data . "\n" . 'id: ' . $id . "\n\n";
            ob_flush();
            flush();
        }, function ($data, $event = '_t_') {
            echo 'data: ' . $data . "\n" . 'event: ' . $event . "\n\n";
            ob_flush();
            flush();
        });
    }
} else {
    $csql = new \ciy\sql('zc_ymock');
    $csql->where('ufunc', $qstr);
    $csql->order('id desc');
    $mockrow = $db->getone($csql);
    if (!is_array($mockrow))
        die('{"code":9,"errmsg":"' . $qstrarr[0] . '::' . $qstrarr[1] . '无效函数"}');
    $updata = array();
    $updata['lastrequest'] = $_SERVER['REQUEST_URI'] . '<br/>' . file_get_contents('php://input');
    $updata['lasttimes'] = time();
    $csql = new \ciy\sql('zc_ymock');
    $csql->where('id', $mockrow['id']);
    $db->update($csql, $updata);
    echo $mockrow['mockjson'];
}
