<style>
  .hljs,.ui.attached:not(.message)+.ui.attached.segment:not(.top){
    background:#fff!important;
  }
  body{
    background:#FCFCFC!important;
  }
  .ui.message:last-child{
    box-shadow: none;
    height:217px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
  }
  .ui.message>:first-child{
    border: none;
  }
  .ui.segment{
    background:none!important;
    padding: 0!important;
  }
  .ui.floating.message{
    box-shadow: none!important;
    background: none;
  }
  .ui.raised.segment{
    box-shadow: none!important;
  }
  .ui.message p{
    margin-bottom: 0!important;
    opacity: 1!important;
  }
  .newDesc__link{
    font-size:16px;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(51,51,51,1);
    margin-bottom: 10px;
  }
  .newDesc__desc{
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(102,102,102,1);
  }
  .ui.ordered.steps{
    margin-top: 30px;
    width: 100%;
    height:90px;
    background:rgba(250,250,250,1);
    border-radius:10px;
    border:1px solid rgba(233,233,233,1);
    overflow: hidden;
  }
  /* 头标题 */
  .newDescTitle{
    /* height:101px; */
    padding: 10px 0;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    display: flex;
    align-items: center;
  }
  .newDescTitle__box{
    padding: 0 30px;
  }
  .newDescTitle__box__nav{
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(153,153,153,1);
  }
  .newDescTitle__box__t{
    font-size:20px!important;
    font-family:PingFangSC-Semibold,PingFang SC!important;
    font-weight:600!important;
    color:rgba(51,51,51,1)!important;
    margin: 15px!important 0;
  }
  /* biaoge */
  .ui.steps .step:after, .ui.ordered.steps .step.completed:before{
    display: none!important;
  }
  .ui.steps .step .description{
    font-size:14px!important;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(102,102,102,1)!important;
    margin-bottom: 4px;
    text-align: center;
  }
  .ui.steps .step .title{
    font-size:18px!important;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400!important;
    color:rgba(51,51,51,1)!important;
    text-align: center;
  }
  /* biaoge e */
  /* 接口参数 */
  .parameter, .parameterName, .testing, .clientCode, .errorList{
    padding-bottom: 20px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    margin-bottom: 20px;
  }
  .clientCode{
    margin-bottom: 0px;
    padding-bottom: 0px;
  }
  .parameter__title, .parameterName__title, .testing__title, .clientCode__title, .errorList__title{
    padding: 0 30px;
    height: 55px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #E9E9E9;
  }
  .parameter__title p, .parameterName__title p, .testing__title p,  .clientCode__title p, .errorList__title p{
    font-size:16px;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(51,51,51,1);
  }
  .ui.red.table, .ui.green.table{
    border-top: none!important;
    margin-top: 20px!important;
    border-bottom: none;
    border-left: none;
    border-right: none;
    padding: 0 32px;
  }
  .ui.table:last-child tbody tr td,.ui.table:last-child thead tr th, .ui.green.table thead tr th, .ui.green.table tbody tr td{
    border: none;
    height: 53px;
  }
  .ui.table:last-child tbody tr,.ui.table:last-child thead tr, .ui.green.table thead tr th, .ui.green.table tbody tr td{
    border-bottom: 1px solid #E9E9E9;
  }
  .ui.table:last-child thead tr th, .ui.green.table thead tr th{
    font-size:14px;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    border-bottom: 1px solid #E9E9E9;
    color:rgba(51,51,51,1);
  }
  .ui.table:last-child tbody tr td{
    font-size:14px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(102,102,102,1);
    border-bottom: 1px solid #E9E9E9;
  }
  .signRed{
    width:7px;
    height:7px;
    background:rgba(245,34,45,1);
    display: inline-block;
    border-radius: 50%;
    margin-right: 7px;
  }
  .signGreen{
    width:7px;
    height:7px;
    background:rgba(82,196,26,1);
    display: inline-block;
    border-radius: 50%;
    margin-right: 7px;
  }
  /* 接口参数 e */
  /* 客户示例 */
  .ui.tab.active{
    margin-top: 0!important;
    box-shadow: none;
    margin-bottom: 20px;
    border: none;
    padding-bottom: 20px!important;
  }
  pre{
    margin-top: 0px;
  }
  /* 底部时间 */
  .generatedTime{
    display: flex;
    height: 80px;
    align-items: center;
    justify-content: center!important;
  }
  .generatedTime small{
    font-size:12px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(153,153,153,1);
  }
</style>
<?php
//  ---------------------------------------------------------------------------------
//    _____   _             _                   _   _____
//   |  __ \ | |           | |    /\           (_) |  __ \
//   | |__) || |__    __ _ | |   /  \    _ __   _  | |__) |_ __  ___
//   |  ___/ | '_ \  / _` || |  / /\ \  | '_ \ | | |  ___/| '__|/ _ \
//   | |     | | | || (_| || | / ____ \ | |_) || | | |    | |  | (_) |
//   |_|     |_| |_| \__,_||_|/_/    \_\| .__/ |_| |_|    |_|   \___/
//                                      | |
//                                      |_|
//   PhalApi Pro 专业版
//   广州果创网络科技有限公司
//
//  ---------------------------------------------------------------------------------
//
//   一、协议的许可和权利
//    1. 您可以在完全遵守本协议的基础上，将本软件应用于商业用途；
//    2. 您可以在协议规定的约束和限制范围内修改本产品源代码或界面风格以适应您的要求；
//    3. 您拥有使用本产品中的全部内容资料、商品信息及其他信息的所有权，并独立承担与其内容相关的
//       法律义务；
//    4. 获得商业授权之后，您可以将本软件应用于商业用途，自授权时刻起，在技术支持期限内拥有通过
//       指定的方式获得指定范围内的技术支持服务；
//
//   二、协议的约束和限制
//    1. 未获商业授权之前，禁止将本软件用于商业用途（包括但不限于企业法人经营的产品、经营性产品
//       以及以盈利为目的或实现盈利产品）；
//    2. 未获商业授权之前，禁止在本产品的整体或在任何部分基础上发展任何派生版本、修改版本或第三
//       方版本用于重新开发；
//    3. 如果您未能遵守本协议的条款，您的授权将被终止，所被许可的权利将被收回并承担相应法律责任；
//
//   三、有限担保和免责声明
//    1. 本软件及所附带的文件是作为不提供任何明确的或隐含的赔偿或担保的形式提供的；
//    2. 用户出于自愿而使用本软件，您必须了解使用本软件的风险，在尚未获得商业授权之前，我们不承
//       诺提供任何形式的技术支持、使用担保，也不承担任何因使用本软件而产生问题的相关责任；
//    3. 广州果创网络科技有限公司不对使用本产品构建的商城中的内容信息承担责任，但在不侵犯用户隐
//       私信息的前提下，保留以任何方式获取用户信息及商品信息的权利；
//
//   有关本产品最终用户授权协议、商业授权与技术服务的详细内容，均由广州果创网络科技有限公司独家
//   提供。广州果创网络科技有限公司拥有在不事先通知的情况下，修改授权协议的权力，修改后的协议对
//   改变之日起的新授权用户生效。电子文本形式的授权协议如同双方书面签署的协议一样，具有完全的和
//   等同的法律效力。您一旦开始修改、安装或使用本产品，即被视为完全理解并接受本协议的各项条款，
//   在享有上述条款授予的权力的同时，受到相关的约束和限制。协议许可范围以外的行为，将直接违反本
//   授权协议并构成侵权，我们有权随时终止授权，责令停止损害，并保留追究相关责任的权力。
//
//  ---------------------------------------------------------------------------------

// 搜索关键字
$keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';

$semanticHost = '/semantic'; // 本地
if (substr(PHP_SAPI, 0, 3) == 'cli') {
    $semanticHost = 'https://cdn.bootcss.com/semantic-ui/2.2.2'; // CDN
}

$suffixTitle = \PhalApi\T('Online API Docs');

echo <<<EOT
<!DOCTYPE html>
<html lang="en">
<!-- 

  _____   _             _                   _   _____             
 |  __ \ | |           | |    /\           (_) |  __ \            
 | |__) || |__    __ _ | |   /  \    _ __   _  | |__) |_ __  ___  
 |  ___/ | '_ \  / _` || |  / /\ \  | '_ \ | | |  ___/| '__|/ _ \ 
 | |     | | | || (_| || | / ____ \ | |_) || | | |    | |  | (_) |
 |_|     |_| |_| \__,_||_|/_/    \_\| .__/ |_| |_|    |_|   \___/ 
                                    | |                           
                                    |_|                           
 -->

<head>
    <meta charset="utf-8">
    <title>{$description} - {$service} - {$projectName} - {$suffixTitle}</title>

    <link rel="stylesheet" href="{$semanticHost}/semantic.min.css">
    <link rel="stylesheet" href="{$semanticHost}/components/table.min.css">
    <link rel="stylesheet" href="{$semanticHost}/components/container.min.css">
    <link rel="stylesheet" href="{$semanticHost}/components/message.min.css">
    <link rel="stylesheet" href="{$semanticHost}/components/label.min.css">
    <link rel="icon" href="/favicon.ico" type="image/x-icon" />

    <script src="/static/jquery.min.js"></script>
    <script src="/static/jquery.cookie.min.js"></script>
</head>

<body>
EOT;


include dirname(__FILE__) . '/api_menu.php';

echo <<<EOT

    <div class="ui text container" style="max-width: none !important;padding-top: 70px;">
        <div class="ui floating message">

EOT;

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) ? 'https://' : 'http://';
$url = $url . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost');
$url .= trim(substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/') + 1), '.');

$uriMap = array(
    'Admin' => '/api/admin.php',
    'App' => '/api/app.php',
    'Platform' => '/api/platform.php',
    'Task' => '/api/task.php',
);
list($ns) = explode('.', $service);
$namespaceStr = \PhalApi\T($ns . '\\');
$url = rtrim($url, '/') . (isset($uriMap[$ns]) ? $uriMap[$ns] : '/api/app.php');

/**
 * 接口说明 & 接口参数
 */
?>
            <div class="ui raised segment">
                <!-- <span class="ui red ribbon label"> 
                  #<?php echo \PhalApi\T('API Docs'); ?>
                </span> -->
                <div class="newDescTitle">
                  <div class="newDescTitle__box">
                    <p class="newDescTitle__box__nav"><?php echo $projectName; ?> / <?php echo $namespaceStr; ?> / <span style="color:#333;"><?php echo $description; ?></span> </p>
                    <p class="ui header newDescTitle__box__t" style="padding: 10px 0;">
                        <?php echo $description; ?>
                    </p>

                    <?php $flowProducts = \Mall\Domain\Product::getFlowProducts($service); ?>
                    <?php foreach ($flowProducts as $pItem) { ?>
                        <?php if ($pItem['product_type'] == \Mall\Model\Mall\Product::PRODUCT_TYPE_API_FREE) { ?>
                    <div class="ui labeled button" tabindex="0">
                            <div class="ui basic blue button"><i class=""></i> 
                                <?php echo $pItem['amount'], \PhalApi\T('time_unit'); ?>
                            </div>
                            <a class="ui basic left pointing blue label">
                                <?php echo \PhalApi\T('free'); ?>
                            </a>
                    </div>
                        <?php } else { ?>

                        <div class="ui labeled button" tabindex="0">
                            <div class="ui red button">
                                <?php echo $pItem['amount'], \PhalApi\T('time_unit'); ?>
                            </div>
                            <a href="/platform/place-an-order/index?product_id=<?php echo $pItem['id']; ?>" target="_blank" class="ui basic red left pointing label">
                                <?php echo $pItem['price'], \PhalApi\T('money_unit'); ?>
                            </a>
                        </div>
                        <?php } ?>
                    <?php } ?>


                  </div>
                  
                </div>
                <div class="ui message newDesc">
                    <p class="newDesc__link"><?php echo \PhalApi\T('API Url'); ?>：<?php echo $url; ?>?s=<?php echo $service; ?></p>
                    <p class="newDesc__desc"><?php echo \PhalApi\T('API Description'); ?>：<?php echo $descComment; ?></p>

                     <div class="ui ordered steps">
                      <div class="completed step">
                        <div class="content">
                          <div class="description">HTTP/HTTPS</div>
                          <div class="title"><?php echo \PhalApi\T('Protocol'); ?></div>
                        </div>
                      </div>
                      <div class="completed step"> 
                        <div class="content">
                          <div class="description">GET/POST</div>
                          <div class="title"><?php echo \PhalApi\T('Method'); ?></div>
                        </div>
                      </div>
                      <div class="completed step">
                        <div class="content">
                          <div class="description">UTF-8</div>
                          <div class="title"><?php echo \PhalApi\T('Charset'); ?></div>
                        </div>
                      </div>
                      <div class="completed step">
                        <div class="content">
                          <div class="description">JSON</div>
                          <div class="title"><?php echo \PhalApi\T('Format'); ?></div>
                        </div>
                      </div>
                    </div>
                </div>
            </div>
            <!-- 接口参数 -->
            <div class="parameter">
              <div class="parameter__title">
                <p><?php echo \PhalApi\T('API Parameters'); ?></p>
              </div>
              <table class="ui red celled striped table" >
                <thead>
                    <tr><th><?php echo \PhalApi\T('Parameter Name'); ?></th><th><?php echo \PhalApi\T('Type'); ?></th><th><?php echo \PhalApi\T('Is Required'); ?></th><th><?php echo \PhalApi\T('Default'); ?></th><th><?php echo \PhalApi\T('Note'); ?></th><th><?php echo \PhalApi\T('Description'); ?></th></tr>
                </thead>
                <tbody>
<?php 

$typeMaps = array(
    'string' => '字符串',
    'int' => '整型',
    'float' => '浮点型',
    'boolean' => '布尔型',
    'date' => '日期',
    'array' => '字符串', // 转换成客户端看到的参数类型
    'fixed' => '固定值',
    'enum' => '枚举类型',
    'object' => '对象',
);
foreach ($typeMaps as $key => &$tmRef) {
    $tmRef = \PhalApi\T($key);
}

foreach ($rules as $key => $rule) {
    // 接口文档不显示
    if (!empty($rule['is_doc_hide'])) {
        continue;
    }

    $name = $rule['name'];
    if (!isset($rule['type'])) {
        $rule['type'] = 'string';
    }
    $type = isset($typeMaps[$rule['type']]) ? $typeMaps[$rule['type']] : $rule['type'];
    $require = isset($rule['require']) && $rule['require'] ? '<span class="signRed"></span><font color="red">'.\PhalApi\T('Required').'</font>' : '<span class="signGreen"></span><font color="#52C41A">'.\PhalApi\T('Optional').'</font>';
    $default = isset($rule['default']) ? $rule['default'] : '-';
    if ($default === NULL) {
        $default = 'NULL';
    } else if (is_array($default)) {
        // @dogstar 20190120 默认值，反序列
        $ruleFormat = !empty($rule['format']) ? strtolower($rule['format']) : '-';
        if ($ruleFormat == 'explode') {
            $default = implode(isset($rule['separator']) ? $rule['separator'] : ',', $default);
        } else {
            $default = json_encode($default);
        }
    } else if (!is_string($default)) {
        $default = var_export($default, true);
    }

    // 数组类型的格式说明
    if ($rule['type'] == 'array' && in_array($rule['format'], array('json', 'explode'))) {
        $type .= sprintf(
            '<span class="ui label blue small">%s</span>',
            $rule['format'] == 'json'
            ? \PhalApi\T('json')
            : sprintf(\PhalApi\T('seperated by %s'), isset($rule['separator']) ? $rule['separator'] : ',')
        );
    }

    $other = array();
    if (isset($rule['min'])) {
        $other[] = \PhalApi\T('min: ') . $rule['min'];
    }
    if (isset($rule['max'])) {
        $other[] = \PhalApi\T('max: ') . $rule['max'];
    }
    if (isset($rule['range'])) {
        $other[] = \PhalApi\T('range: ') . implode('/', $rule['range']);
    }
    if (isset($rule['source'])) {
        $other[] = \PhalApi\T('source: ') . strtoupper($rule['source']);
    }
    $other = implode('；', $other);

    $desc = isset($rule['desc']) ? trim($rule['desc']) : '';

    echo "<tr><td>$name</td><td>$type</td><td>$require</td><td>$default</td><td>$other</td><td>$desc</td></tr>\n";
}

// 返回-数组
$typeMaps['array'] = '数组';
/**
 * 返回结果
 */
?>
                </tbody>
              </table>
            </div>
            <!-- 参数名字 -->
            <div class="parameterName">
              <div class="parameterName__title">
                <p><?php echo \PhalApi\T('Return Field'); ?></p>
              </div>
                <table class="ui green celled striped table" >
                  <thead>
                    <tr><th><?php echo \PhalApi\T('Response Result'); ?></th><th><?php echo \PhalApi\T('Type'); ?></th><th><?php echo \PhalApi\T('Description'); ?></th></tr>
                  </thead>
                  <tbody>
                    <tr><td>ret</td><td><?php echo \PhalApi\T('int'); ?></td><td><?php echo \PhalApi\T('status code, 200 is ok, 4xx is bad request, 5xx is server inside error'); ?></td></tr>
                    <tr><td>data</td><td><?php echo \PhalApi\T('object/mixed'); ?></td><td><?php echo \PhalApi\T('business data, decided by API implementation'); ?></td></tr>
                    <?php
                    foreach ($returns as $item) {
                        $name = $item[1];
                        $type = isset($typeMaps[$item[0]]) ? $typeMaps[$item[0]] : $item[0];
                        $detail = $item[2];
                        echo "<tr><td>data.{$name}</td><td>$type</td><td>$detail</td></tr>";
                    }
                    ?>
                      <tr><td>msg</td><td><?php echo \PhalApi\T('string'); ?></td><td><?php echo \PhalApi\T('message, usually error message'); ?></td></tr>
                    </tbody>
                  </table>
            </div>
            <!-- 在线测试 -->
            <div class="testing">
              <div class="testing__title">
                <p><?php echo \PhalApi\T('Test Online'); ?> &nbsp;&nbsp;</p>
              </div>
              <table class="ui green celled striped table" >
                  <thead>
                    <tr><th width="25%"><?php echo \PhalApi\T('Parameter'); ?></th><th width="10%"><?php echo \PhalApi\T('Is Required'); ?></th><th width="65%"><?php echo \PhalApi\T('Value'); ?></th></tr>
                  </thead>
                  <tbody id="params">
                    <tr>
                      <td>service</td>
                      <td><span class="signRed"></span><font color="red"><?php echo \PhalApi\T('Required'); ?></font></td>
                      <td><div class="ui fluid input disabled"><input name="service" data-source="get" value="<?php echo $service; ?>" style="width:100%;" class="C_input" /></div></td>
                    </tr>
                  <?php
                  $selectIdsArr = array(); // 下拉框
                  foreach ($rules as $key => $rule){
                      // 接口文档不显示
                      if (!empty($rule['is_doc_hide'])) {
                          continue;
                      }

                      $source = isset($rule['source']) ? $rule['source'] : '';
                      //数据源为server和header时该参数不需要提供
                      if ($source == 'server' || $source == 'header') {
                          continue;
                      }
                      $name = $rule['name'];
                      $require = isset($rule['require']) && $rule['require'] ? '<span class="signRed"></span><font color="red">'.\PhalApi\T('Required').'</font>' : '<span class="signGreen"></span><font color="#52C41A">'.\PhalApi\T('Optional').'</font>';
                      // 提供给表单的默认值
                      $default = isset($rule['default'])
                          ? (is_array($rule['default']) // 针对数组，进行反序列化
                              ? (!empty($rule['format']) && $rule['format'] == 'explode' 
                                  ? implode(isset($rule['separator']) ? $rule['separator'] : ',', $rule['default']) 
                                  : json_encode($rule['default'])) 
                              : $rule['default'])
                          : '';
                      $default = htmlspecialchars($default);
                      $desc = isset($rule['desc']) ? htmlspecialchars(trim($rule['desc'])) : '';
                      $inputType = (isset($rule['type']) && $rule['type'] == 'file') ? 'file' : 'text';

                      $multiple = '';
                      if ($inputType == 'file') {
                          $multiple = 'multiple="multiple"';
                      }

                      // 辅助的枚举类型
                      $selectInput = '';
                      if (isset($rule['type']) && $rule['type'] == 'enum' && !empty($rule['range'])) {
                          $selectInput .= '<select style="width: 30%;" id="'.$name.'_select_ipt_id">';
                          $selectInput .= '<option value="">-- '.\PhalApi\T('Select').' --</option>';
                          foreach ($rule['range'] as $it) {
                              $selectInput .= sprintf('<option value="%s">%s</option>', $it, $it);
                          }
                          $selectInput .= '</select>';

                          $selectIdsArr[] = $name;
                      }

                      echo <<<EOT
                        <tr>
                            <td>{$name}</td>
                            <td>{$require}</td>
                            <td><div class="ui fluid input"><input name="{$name}" id="{$name}_ipt_id" value="{$default}" data-source="{$source}" placeholder="{$desc}" style="width:100%;" class="C_input" type="$inputType" $multiple/> {$selectInput} </div></td>
                        </tr>
EOT;
                  }
                  ?>
                  </tbody>
              </table>
              <div class="ui fluid action input">
                <input placeholder="请求的接口链接" type="text" name="request_url" value="<?php echo $url; ?>" >
                <button class="ui button green" id="submit" ><?php echo \PhalApi\T('Request API'); ?></button>
              </div>
            </div>

<div style="display: flex;align-items:center;">
    <!--<select name="request_type" style="font-size: 14px; padding: 2px;">
        <option value="POST">POST</option>
        <option value="GET">GET</option>
    </select>-->
</div>
<div class="ui message blue" id="json_output">
</div>
<div class="ui message blue" id="json_output_api_result" style="overflow: auto;">
</div>

<?php
foreach ($selectIdsArr as $id) {
    echo <<<EOT
<script type="text/javascript">
$("#{$id}_select_ipt_id").on('change', function(){
    var p1=$(this).children('option:selected').val();//这就是selected的值
    $("#{$id}_ipt_id").val(p1);
});
</script>
EOT;
}
    
/**
 * 动态生成客户端代码示例
 */
?>

<div class="clientCode">
  <div class="clientCode__title">
    <p><?php echo \PhalApi\T('Client Request Demo'); ?></p>
  </div>
  
</div>



<?php
$demoCodes = array();
$demoPath = dirname(__FILE__) . '/demos';
foreach (array(
    'json', 'curl', 'js', 'php', 'py', 'java', 'cs', 'go', 'oc',
) as $whatCode) {
    // 公共前缀部分
    $prefixCode = '';
    $prefixFile = $demoPath . '/_prefix.' . $whatCode;
    if (file_exists($prefixFile)) {
        $prefixCode = htmlspecialchars(file_get_contents($prefixFile));
    }

    $codeFile = $demoPath . '/' . $service . '.' . $whatCode;
    if (file_exists($codeFile)) {
        $demoCodes[$whatCode] = $prefixCode . htmlspecialchars(file_get_contents($codeFile));
        
        // 公共后缀部分
        $suffixCode = '';
        $suffixFile = $demoPath . '/_suffix.' . $whatCode;
        if (file_exists($suffixFile)) {
            $suffixCode = htmlspecialchars(file_get_contents($suffixFile));
            $demoCodes[$whatCode] .= $suffixCode;
        }
        
        $demoCodes[$whatCode] = str_replace(array('{url}', '{s}'), array($url, $service), $demoCodes[$whatCode]);
    }
}

if (empty($demoCodes)) {
    $demoCodes['json'] = '# 暂无示例，可添加示例文件：./src/view/docs/demos/' . $service . '.json';
}

$codeName = array(
    'json' => 'HTTP通用示例',
    'js' => 'Javascript示例',
    'oc' => 'Object-C示例',
    'java' => 'Java示例',
    'curl' => 'CURL示例',
    'php' => 'PHP示例',
    'py' => 'Python示例',
    'go' => 'Golang示例',
    'cs' => 'C#示例',
);
foreach ($codeName as $key => &$cnRef) {
    $cnRef = \PhalApi\T($key . ' demo');
}

if (!empty($demoCodes)) {
    $allKeys = array_keys($demoCodes);
    $firstLan = $allKeys[0]; // 第一个标签的语言

    $itemHtml = '';
    $segmentHtml = '';

    foreach ($demoCodes as $code => $codeStr) {
        $itemHtml .= sprintf('<a class="%s item" data-tab="%s">%s</a>', ($firstLan == $code ? 'active ' : ''), 'datatab' . $code, $codeName[$code]);
        $segmentHtml .= sprintf('<div class="ui bottom attached %s tab segment" data-tab="%s"><pre><code>%s</code></pre></div>', ($firstLan == $code ? 'active ' : ''), 'datatab' . $code, $codeStr);
    }

    echo <<<EOT

<div class="ui tab segment active" data-tab="{$firstLan}">
    <div class="ui top attached tabular menu">
        {$itemHtml}
    </div>

    {$segmentHtml}
</div>

<!-- 代码高亮 -->
<!--
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>
-->
<link rel="stylesheet" href="./static/highlight.min.css">
<script src="./static/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

EOT;
}


/**
 * 异常情况
 */
if (!empty($exceptions)) {
    $elt = \PhalApi\T('Error List');
    $est = \PhalApi\T('Error Status');
    $edt = \PhalApi\T('Error Description');
    echo <<<EOT
    <div class="errorList">
      <div class="errorList__title">
        <p id="ret_code_list_id">{$elt}</p>
      </div>
            <table class="ui red celled striped table" >
                <thead>
                    <tr><th>{$est}</th><th>{$edt}</th>
                </thead>
                <tbody>
EOT;
    
    usort($exceptions, function($left, $right) {
        return $left[0] > $right[0] ? 1 : -1;
    });
        
        foreach ($exceptions as $exItem) {
            $exCode = $exItem[0];
            $exMsg = isset($exItem[1]) ? $exItem[1] : '';
            echo "<tr><td>$exCode</td><td>$exMsg</td></tr>";
        }
        
        echo <<<EOT
            </tbody>
        </table>
    </div>
    
EOT;
}

/**
 * 底部
 */
$version = PHALAPI_PRO_VERSION;
$proVersion = PHALAPI_PRO_VERSION;
$thisYear = date('Y');
$curTimeStr = date('Y-m-d H:i:s');
$att = \PhalApi\T('Last generated at: ');
echo <<<EOT
<!--
        <div class="ui blue message">
          <strong>温馨提示：</strong> 此接口文档根据接口代码和注释实时自动生成，帮助文档请见<a href="http://docs.phalapi.net/#/v2.0/api-docs" target="_blank">PhalApi 2.x 开发文档</a>。
        </div>
-->
        <p class="generatedTime"><small>{$att}{$curTimeStr}</small></p>
        </div>

    </div>

EOT;

echo <<<EOT

<script src="{$semanticHost}/semantic.min.js" ></script>
<script src="{$semanticHost}/components/tab.js"></script>

<script type="text/javascript">
        $(function(){
            $("#json_output").hide();
            $("#json_output_api_result").hide();
            $("#submit").on("click",function(){
                $("#json_output").html('<div class="ui active inverted dimmer"><div class="ui text loader">接口请求中……</div></div>');
                $("#json_output").show();
                $("#json_output_api_result").html('');

                var data = getData();
                var url_arr = $("input[name=request_url]").val().split('?');
                var url = url_arr.shift();
                var param = url_arr.join('?');
                param = param.length > 0 ? param + '&' + data.param : data.param;
                url = url + '?' + param;
                $.ajax({
                    url: url,
                    type:'post',
                    data:data.data,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success:function(res,status,xhr){
                        var statu = xhr.status + ' ' + xhr.statusText;
                        var header = xhr.getAllResponseHeaders();
                        var json_text = JSON.stringify(res, null, 4);    // 缩进4个空格
                        $("#json_output").html('<pre>' + statu + '<br />' + header + '</pre>');
                        $("#json_output").show();
                    
                        if (hljs) {
                            // var hightLightCode = hljs.highlightAuto(json_text);
                            var hightLightCode = hljs.highlight('json', json_text);
                            json_text = hightLightCode.value;
                        }

                        $("#json_output_api_result").html('<pre><code>' + json_text + '</code></pre>');
                        $("#json_output_api_result").show();
                    },
                    error:function(error){
                        $("#json_output").html('接口请求失败：' + error);
                    }
                })
            })

            fillHistoryData();

            //checkLastestVersion();
            // 选项卡
            $('.tabular.menu .item').tab();

            $('.ui.dropdown').dropdown({
              // you can use any ui transition
              transition: 'drop'
            });
        })
    
        	
    function getData() {
      var data = new FormData();
      var param = [];
      $("td input").each(function(index,e) {
          if ($.trim(e.value)){
              if (e.type != 'file'){
                  if ($(e).data('source') == 'get') {
                      param.push(e.name + '=' + e.value);
                  } else {
                      data.append(e.name, e.value);
                  }

                  if (e.name != "service") $.cookie(e.name, e.value, {expires: 30});
              } else{
                  var files = e.files;
                  if (files.length == 1){
                      data.append(e.name, files[0]);
                  } else{
                      for (var i = 0; i < files.length; i++) {
                          data.append(e.name + '[]', files[i]);
                      }
                  }
              }
          }
      });
      param = param.join('&');
      return {param:param, data:data};
  }

  // 填充历史数据
  function fillHistoryData() {
      $("td input").each(function(index,e) {
          var cookie_value = $.cookie(e.name);
          if (e.name != "service" && cookie_value !== undefined) {
              e.value = cookie_value;
          }
      });
  }
</script>
EOT;

// include dirname(__FILE__) . '/api_footer.php';

