<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2021-02-04
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\http\middleware;
use think\Controller;
use app\common\model\Site;
use app\common\model\Domains;
use think\facade\Cache;
use Request;

class Getsiteinfo extends Controller
{
	public function handle($request, \Closure $next)
    {
        // 路由请求信息
    	$routeinfo = $request->route();
        // 缓存所有站点和栏目，array
        $site_nav_list = Cache::get('site_nav_list');
        if(!$site_nav_list) {
            $site_nav_list = Site::with('navlist,navlist.cmsmodels,domains')->append(['expired','url','navlist.url','navlist.hasChild','navlist.ext'])->order("torder asc,id asc")->select()->toArray();
            Cache::set('site_nav_list',$site_nav_list);
        }
        
       	// 确定默认站点信息
        $local_domain = Request::domain();
        $defaultSiteinfo = array_filter($site_nav_list,function($row)use($local_domain){
            return in_array($local_domain, array_column($row['domains'],'domain'));
        });
        if(!$defaultSiteinfo) {
            $defaultSiteinfo = array_filter($site_nav_list,function($row){
                return $row['isdefault'] == 1;
            });
        }
        $defaultSiteinfo = reset($defaultSiteinfo);
        // 判断当前站点信息
    	if(empty($routeinfo['lang'])) {
    		$request->siteinfo = $defaultSiteinfo;
    	} else {
            $site_nav_list_alias = array_column($site_nav_list,NULL,'alias');
    		$request->siteinfo = isset($site_nav_list_alias[$routeinfo['lang']]) ? $site_nav_list_alias[$routeinfo['lang']] : NULL;
    	}
        if($request->siteinfo) {
            define('SITEID', $request->siteinfo['id']);
            define('SITEALIAS', $request->siteinfo['alias']);
            define('DEFAULTSITEID',$defaultSiteinfo['id']);
        } else {
            abort(404,lang('站点不存在'));
        }
    	return $next($request);
    }
}