<?php

namespace xmvc;

// @codingStandardsIgnoreStart
if (empty($error)) return '';
$error['typeName'] = ErrorClass::errorTypeName($error['type']);
if (!function_exists('xmvc\backtraceFormat')) require __DIR__ . '/backtraceFormat.php';
if (!function_exists('xmvc\getPhpCodeHtml')) {
    function getPhpCodeHtml($file, $line, $begin = 12, $end = 10, $isShowFilename = false)
    {
        $cmd = new \xmvc\core\Cmd();
        $r = $cmd->showPhpCode($file, $line, $begin = 12, $end = 10, true);
        return $r->data;
    }
}
$contents = '';
//trace
$backtrace = isset($error['backtrace']) ? $error['backtrace'] : debug_backtrace(DEBUG_BACKTRACE);
list($callerFile, $callerLine, $traceTable) = backtraceFormat($backtrace);
if (empty($error['file']) && $callerFile && $callerLine) {
    $error['file'] = $callerFile;
    $error['line'] = $callerLine;
}
if (in_array($error['type'], [E_USER_WARNING, E_USER_NOTICE])) {
    $contents = json_encode(['code' => E_USER_WARNING, 'message' => $error['message']], JSON_UNESCAPED_UNICODE);
} elseif (in_array($error['type'], [
    MVC::$cfg['error']['e_notice'] ? E_NOTICE : E_ERROR,
    MVC::$cfg['error']['e_warning'] ? E_WARNING : E_ERROR,
    E_ERROR, E_WARNING, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_DEPRECATED
])) {
    $error['file'] = fdir($error['file']);
    $errFileInfo = pathinfo($error['file']);
    $errFileInfo['dirname'] = relDir($errFileInfo['dirname']);
    //code 
    $code_string = '';
    $code_more_string = '';
    if (MVC::$cfg['error']['fileCode']) {
        $code_string = getPhpCodeHtml($error['file'], $error['line'], 12, 10, true);
        if (isset($error['files']) && !empty($error['files'])) {
            foreach ($error['files'] as $item) {
                if (relDir($item['file']) != relDir($error['file'])) {
                    $code_more_string .= getPhpCodeHtml($item['file'], $item['line'], 12, 10, true);
                }
            }
        }
    }

    //request
    if (MVC::$cfg['error']['request']) {
        $reqJson = json_encode(MVC::$req);
        if($reqJson != '{}'){
            if (strlen($reqJson) > 1024) {
                $request = '在console查看完整信息, ' . substr($reqJson, 0, 300) . '......';
            } else {
                $request = var_export(MVC::$req, true);
                $request = preg_replace("/'([^']+)'\s+=>/s", '$$1 = ', $request);
                $request = substr($request, 7, -3);
                $request = '';
                foreach (MVC::$req as $k => $v) {
                    $request .= qgprintf('<strong>{:1}</strong> = {:2}<br>', $k, escape($v));
                }
            }
            $request .= '<script>console.log("请求参数",' . $reqJson . ')</script>';
        }
    }

    //cmd
    $cmd = '';
    if (IS_DEVELOP && isset($error['cmd'])) {
        $error['cmd']['newClassFile'] = Encoder::encode($error['cmd']['newClassFile']);
        $cmd = qgprintf('&nbsp;<a href="{:1}/xmvc/core/cmd-{:cmdFunction}'
                . '~newClassName-{:newClassName}'
                . '~newClassFunction-{:newClassFunction}'
                . '~newClassFile-{:newClassFile}'
                . '" target="_blank" onclick="return confirm(\'确认要执行此操作吗\');"
                >{:title}</a>', HOST, $error['cmd']);
    }

    //msg
    $msg = '';
    $msg .= "<div style='color:#069;font-size:14px;word-break: break-all;'>控制器: " . MVC::$method ."</div>";
    //message & cmd
    $msg .= '<div style="width:100%;font-weight:300;font-size:16px;width:100%;border: 1px solid #ddd;background-color:#FEE;
                white-space:pre-wrap;word-break:break-word;"><div style="padding:.3em 1em;">' . $error['message'] . $cmd . '</div></div>';
    //sql
    if (isset($error['sql']) && $error['sql']) {
        $msg .= '<div style="color:#C0C;font-size:16px;word-break: break-all; border-left: 1px solid #ddd;
                background-color:#FFF;padding: 0.5em 1em" id="mvcCopySql" onDblclick="mvcCopySql()" title="双击复制">' . sqlFormatter::format($error['sql']) . '</div>';
    }
    //traceTable
    if ($traceTable) {
        $msg .= '<div style="width:100%;overflow:auto;">' . $traceTable . '</div>';
    }
    //request
    if (MVC::$cfg['error']['request'] && isset($request)) {
        $msg .= "<div style=background:#F6F6F6;border:1px solid #000;overflow:auto;'>
        <div style='padding: 0.5em 1em;font-size:14px;color:515151;white-space:nowrap; border: 1px solid #ddd;border-top:none'>
        <span style='color:#069;font-size:16px;'>请求参数: </span><br />" . $request . "</div></div>";
    }
    //file & line
    if ($code_string == '') {
        $msg .= '<div style="font-size:16px;padding: 0.5em 1em;word-break:reak-all;white-space:pre-wrap;">'
            . $errFileInfo['dirname'] . '/<span style="color:red">' . $errFileInfo['basename'] . '</span>'
            . '  Line: <span style="color:red">' . $error['line'] . '</span></div>';
    }

    //code
    $msg .= $code_string;
    $msg .= $code_more_string;

    //contents
    $contents = '
        <script>function mvcCopySql(){
            var contents = document.getElementById("mvcCopySql").innerText;
            var textarea = document.createElement("textarea");
            textarea.value = contents;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand("copy");
            document.body.removeChild(textarea);
            alert("SQL 已复制");
        }</script>
        <style>pre{font-size:16px;margin:0}</style>
        <h1>DEBUG <span style="font-size:13px;color:#A66">' . $error['typeName']
        . ' <span style="font-size:13px;color:#008">' . date('Y-m-d H:i:s') . '</span>'
        . ' <span style="font-size:13px;color:#ccc">from ' . $function . '</span>'
        . '</h1>
        <div style="clear:both;word-wrap: break-word;
            font-family: monaco, Consolas, Menlo, Courier, monospace;
            font-size: 14px;border: 1px #c66 dashed;border-radius: 5px;
            margin:0px;padding:5px;background-color:#FFFFE1" class="rare_shutdown_catch_error">';
    $contents .=  $msg;
    $contents .= '</div>';
} else if ($error['type'] == E_NOTICE) {
    //not do
} else {
    $contents = Dump::dumpResult(true, $error);
}
return $contents;
