<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use app\portal\controller\LoginController;
use think\Db;
use app\admin\model\ThemeModel;
use think\View;
use app\portal\model\CollectionModel;
use app\portal\model\LikeModel;
use app\portal\model\PortalPostModel;
use think\Session;

class HomeBaseController extends BaseController
{
    public $appkey = 737607150;//微博appkey
    public $appsecret = 'd80b43a1e74e8ba095590b36a3459480';//微博appsecret
    public $redirect_uri = 'http://www.starplanet.cn/portal/login/wb_login';//回调地址

    public $appkey1 = 'wx9cfa880272f186bf';//微信开放平台appkey
    public $appsecret1 = '11b643393b1e54d6ef5eaa984ba4e545';//微信开放平台appsecret

    public $appkey2 = 'wx0bd7bc2aa0f332d6';//微信公众订阅号appkey
    public $appsecret2 = 'b62e49f48f48de7b7fff2ea0af3939de';//微信公众订阅号appsecret

    public $appkey3 = 'wx3f1a38ee1e74f2bc';//微信公众服务号appkey
    public $appsecret3 = '87f9c080450979db7d6a5e296529b577';//微信公众服务号appsecret

    protected function initialize()
    {
        // 监听home_init
        hook('home_init');
        parent::initialize();
        $siteInfo = cmf_get_site_info();
        View::share('site_info', $siteInfo);
        //获取登录信息
        $this->getUserLoginInfo();
        $this->getFooter();
        $this->getHeader();
        $this->getComment();
        $this->is_collection();
        $this->is_like();
        $this->getShareCount();
        $keyword = $this->request->param('keyword');
        $this->assign('keyword',$keyword);

        $cmfDefaultTheme = cmf_get_current_theme();
        //域名后面相对路径
        $url = $_SERVER['REQUEST_URI'];
        if($cmfDefaultTheme == 'simpleboot3_mobile' && (strpos($url,'Detail')!==false || strpos($url,'getMoreVideo')!==false)){
            $this->wxShare();
        }
    }

    protected function _initializeView()
    {
        $cmfThemePath    = config('template.cmf_theme_path');
        $cmfDefaultTheme = cmf_get_current_theme();

        $themePath = "{$cmfThemePath}{$cmfDefaultTheme}";

        $root = cmf_get_root();
        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $domain=cmf_get_domain();
            $viewReplaceStr = [
                '__ROOT__'     => $domain.$root,
                '__TMPL__'     => $domain."{$root}/{$themePath}",
                '__STATIC__'   => $domain."{$root}/static",
                '__WEB_ROOT__' => $domain.$root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', WEB_ROOT . "{$themePath}/");
        config('view_replace_str', $viewReplaceStr);

        $themeErrorTmpl = "{$themePath}/error.html";
        if (file_exists_case($themeErrorTmpl)) {
            config('dispatch_error_tmpl', $themeErrorTmpl);
        }

        $themeSuccessTmpl = "{$themePath}/success.html";
        if (file_exists_case($themeSuccessTmpl)) {
            config('dispatch_success_tmpl', $themeSuccessTmpl);
        }


    }

    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array  $vars     模板输出变量
     * @param array  $replace  模板替换
     * @param array  $config   模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        $template = $this->parseTemplate($template);
        $more     = $this->getThemeFileMore($template);
        $this->assign('theme_vars', $more['vars']);
        $this->assign('theme_widgets', $more['widgets']);
        $content = parent::fetch($template, $vars, $replace, $config);

        $designingTheme = cookie('cmf_design_theme');

        if ($designingTheme) {
            $app        = $this->request->module();
            $controller = $this->request->controller();
            $action     = $this->request->action();

            $output = <<<hello
<script>
var _themeDesign=true;
var _themeTest="test";
var _app='{$app}';
var _controller='{$controller}';
var _action='{$action}';
var _themeFile='{$more['file']}';
if(parent && parent.simulatorRefresh){
  parent.simulatorRefresh();  
}
</script>
hello;

            $pos = strripos($content, '</body>');
            if (false !== $pos) {
                $content = substr($content, 0, $pos) . $output . substr($content, $pos);
            } else {
                $content = $content . $output;
            }
        }


        return $content;
    }

    /**
     * 自动定位模板文件
     * @access private
     * @param string $template 模板文件规则
     * @return string
     */
    private function parseTemplate($template)
    {
        // 分析模板文件规则
        $request = $this->request;
        // 获取视图根目录
        if (strpos($template, '@')) {
            // 跨模块调用
            list($module, $template) = explode('@', $template);
        }

        $viewBase = config('template.view_base');

        if ($viewBase) {
            // 基础视图目录
            $module = isset($module) ? $module : $request->module();
            $path   = $viewBase . ($module ? $module . DIRECTORY_SEPARATOR : '');
        } else {
            $path = isset($module) ? APP_PATH . $module . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR : config('template.view_path');
        }

        $depr = config('template.view_depr');
        if (0 !== strpos($template, '/')) {
            $template   = str_replace(['/', ':'], $depr, $template);
            $controller = cmf_parse_name($request->controller());
            if ($controller) {
                if ('' == $template) {
                    // 如果模板文件名为空 按照默认规则定位
                    $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . cmf_parse_name($request->action(true));
                } elseif (false === strpos($template, $depr)) {
                    $template = str_replace('.', DIRECTORY_SEPARATOR, $controller) . $depr . $template;
                }
            }
        } else {
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
        }
        return $path . ltrim($template, '/') . '.' . ltrim(config('template.view_suffix'), '.');
    }

    /**
     * 获取模板文件变量
     * @param string $file
     * @param string $theme
     * @return array
     */
    private function getThemeFileMore($file, $theme = "")
    {

        //TODO 增加缓存
        $theme = empty($theme) ? cmf_get_current_theme() : $theme;

        // 调试模式下自动更新模板
        if (APP_DEBUG) {
            $themeModel = new ThemeModel();
            $themeModel->updateTheme($theme);
        }

        $themePath = config('template.cmf_theme_path');
        $file      = str_replace('\\', '/', $file);
        $file      = str_replace('//', '/', $file);
        $webRoot   = str_replace('\\', '/', WEB_ROOT);
        $themeFile = str_replace(['.html', '.php', $themePath . $theme . "/", $webRoot], '', $file);

        $files = Db::name('theme_file')->field('more')->where('theme', $theme)
            ->where(function ($query) use ($themeFile) {
                $query->where('is_public', 1)->whereOr('file', $themeFile);
            })->select();

        $vars    = [];
        $widgets = [];
        foreach ($files as $file) {
            $oldMore = json_decode($file['more'], true);
            if (!empty($oldMore['vars'])) {
                foreach ($oldMore['vars'] as $varName => $var) {
                    $vars[$varName] = $var['value'];
                }
            }

            if (!empty($oldMore['widgets'])) {
                foreach ($oldMore['widgets'] as $widgetName => $widget) {

                    $widgetVars = [];
                    if (!empty($widget['vars'])) {
                        foreach ($widget['vars'] as $varName => $var) {
                            $widgetVars[$varName] = $var['value'];
                        }
                    }

                    $widget['vars']       = $widgetVars;
                    $widgets[$widgetName] = $widget;
                }
            }
        }

        return ['vars' => $vars, 'widgets' => $widgets, 'file' => $themeFile];
    }

    public function checkUserLogin()
    {
        $userId = cmf_get_current_user_id();
        if (empty($userId)) {
            if ($this->request->isAjax()) {
                $this->error("您尚未登录", cmf_url("user/Login/index"));
            } else {
                $this->redirect(cmf_url("user/Login/index"));
            }
        }
    }

    /**
     *  API返回信息格式函数 ;0失败,1成功
     * @param string $code
     * @param string $message
     * @param array $data
     */
    public function apiResponse($code = '', $msg = '',$data = array()){
        header('Access-Control-Allow-Origin: *');
        header('Content-Type:application/json; charset=utf-8');
        $result = array(
            'code'=>$code,
            'msg'=>$msg,
            'data'=>$data,
        );
        die(json_encode($result,JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取登录信息
     */
    public function getUserLoginInfo(){
        $user = cmf_get_current_user();
        $user = empty($user)?'':$user;
        $this->assign('user',$user);
    }

    //获取底部相关内容
    public function getFooter(){
        //关于我们
        $about = Db::name('about_us')
            ->where('id',1)
            ->field('id,excerpt')
            ->find();
        $this->assign('about',$about);

        //关注我们
        $table = 'focus';
        $field = 'id,image,name';
        $focus = $this->getCommon($table,$field,2);
        $this->assign('focus',$focus);

        //合作伙伴
        $table = 'cooperation';
        $field = 'id,image';
        $cooperation = $this->getCommon($table,$field,12);
        $this->assign('cooperation',$cooperation);
        //友情链接
        $table = 'link';
        $field = 'id,name,url';
        $link = $this->getCommon($table,$field,12);
        $this->assign('link',$link);
    }

    public function getCommon($table,$field,$limit){
        $res = Db::name($table)
            ->where('status', 1)
            ->field($field)
            ->limit($limit)
            ->order('weigh desc')
            ->select()
            ->toArray();
        return $res;
    }

    //获取导航栏相关内容
    public function getHeader(){
        $parent = Db::name('portal_category')
            ->whereIn('id',[2,3,4])
            ->field('id,name,description url')
            ->select()
            ->toArray();
        $child = Db::name('portal_category')
            ->where('parent_id','<>',0)
            ->field('id,parent_id,name,description url')
            ->select()
            ->toArray();
        $arr = [];
        foreach($parent as &$p_value){
            foreach ($child as $c_key => $c_value) {
                if ($p_value['id'] == $c_value['parent_id']) {
                    $p_value['child'][] = $c_value;
                }
            }
            array_push($arr,$p_value);
        }
        $this->assign('slide',$arr);
    }

    //获取评论内容
    public function getComment(){
        $id = $this->request->param('id',0,'intval');
        $comment = Db::name('comment')
            ->alias('c')
            ->join('user u','c.user_id = u.id','LEFT')
            ->where(['c.status'=>1,'post_id'=>$id])
            ->field('u.user_nickname nickname,u.avatar,c.content,c.create_time')
            ->select()->toArray();
        $this->assign('comment',$comment);
    }

    //是否收藏
    public function is_collection(){
        //判断是否登录
        $login = cmf_is_user_login();
        $article_id = $this->request->param('id');//文章id
        if($login){
            $uid = cmf_get_current_user_id();
            $collectionModel = new CollectionModel();
            $res = $collectionModel->where(['uid'=>$uid,'post_id'=>$article_id])->find();
            if($res){
                $this->assign('is_collection',1);
            }else{
                $this->assign('is_collection',0);
            }
        }else{
            $this->assign('is_collection',0);
        }
    }

    //是否点赞
    public function is_like(){
        //判断是否登录
        $login = cmf_is_user_login();
        $article_id = $this->request->param('id');//文章id
        if($login){
            $uid = cmf_get_current_user_id();
            $likeModel = new LikeModel();
            $res = $likeModel->where(['uid'=>$uid,'post_id'=>$article_id])->find();
            if($res){
                $this->assign('is_like',1);
            }else{
                $this->assign('is_like',0);
            }
        }else{
            $this->assign('is_like',0);
        }
    }

    //获取微信微博分享数量
    public function getShareCount(){
        $article_id = $this->request->param('id');//文章id
        $postModel = new PortalPostModel();
        $share = $postModel->where(['id'=>$article_id])->field('id,post_share_wx,post_share_wb')->find();
        $this->assign('share',$share);
    }

    //获取微信分享配置信息
    public function wxShare($url=''){
        $jsapiTicket = $this->getSignature();
        // 注意 URL 一定要动态获取,不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        if($url === '') {
            $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        }
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'&timestamp='.$timestamp.'&url='.$url;
        $signature = sha1($string);
        $data = [
            "appId"     => $this->appkey2,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        ];
        $this->assign('data',$data);
    }

    //获取微信分享签名随机字符串
    public function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //获取access_token
    public function getWxAccessToken(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appkey2.'&secret='.$this->appsecret2;
        $res = $this->http_get($url);
        $json_arr = json_decode($res,true);
        $token = $json_arr['access_token'];
        return $token;
    }

    //获取微信分享签名
    public function getSignature(){
        if(isset($_SESSION['ticket_expire_time']) && $_SESSION['ticket_expire_time'] > time() && $_SESSION['ticket']){
            $ticket = $_SESSION['ticket'];
        }else{
            $token = $this->getWxAccessToken();
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token.'&type=jsapi';
            $res = $this->http_get($url);
            $json_arr = json_decode($res,true);
            $ticket = $json_arr['ticket'];
            $_SESSION['ticket'] = $ticket;
            $_SESSION['ticket_expire_time'] = time()+7000;
        }
        return $ticket;
    }

    //curl  get请求
    public function http_get($url){
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false);//不开启header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }

    //curl post请求
    public function http_post($url,$data){
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 开启header
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//请求头部
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }

}