<?php

namespace PhpLife\App\Api;

use PhpLife\App\Admin\Config\CountryList;
use PhpLife\Config\McAlive;
use PhpLife\Frame\Logger;
use PhpLife\Frame\Request;
use PhpLife\Library\Area;
use PhpLife\Library\Des;
use PhpLife\Library\Memcache;

abstract class Controller extends \PhpLife\Frame\Controller
{
    protected $cookie;
    public $cache_key;
    protected $need_cache = false;

    /**
     * 验证登录信息
     * 无需验证或者单独验证的类可以覆盖该方法
     *
     * @param bool $checkLogin
     * @return bool
     * @throws \Exception
     */
    protected function checkAuth($checkLogin = false)
    {
        return true;
    }


    /**
     * 输出模板，自动查找模板路径
     *
     * @param
     *            $layout
     */
    protected function render($layout = 'Common/Layout')
    {
        header("Content-type: text/html; charset=utf-8");
        $this->getTemplate()->render(false, $layout);
    }



    /**
     * 输出json信息
     *
     * @param int $code
     * @param string $msg
     * @param array $data
     * @param string $callback
     * @param bool $need_cache 是否需要进行全局缓存
     */
    protected function output($code = 0, $msg = '', $data = array(), $callback = "")
    {
        $output = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data ?: array()
        );
        header('Content-type: application/json');
        if ($callback) {
            echo $response = $callback . "(" . json_encode($output) . ")";
            if ($this->need_cache) {
                Memcache::instance()->set($this->cache_key, $response, ALL_CACHE_TIME);
            }
            exit();
        } else {
            echo $response = json_encode($output);
            if ($this->need_cache) {
                Memcache::instance()->set($this->cache_key, $response, ALL_CACHE_TIME);
            }
            exit();
        }
        // 记录调试信息
        die();
    }
}