<?php
// +----------------------------------------------------------------------
// | HkCms 语言包中间件
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\common\middleware;

use Closure;
use think\App;
use think\Cookie;
use think\facade\Db;
use think\Lang;
use think\Request;
use think\Response;

/**
 * 多语言加载
 */
class LoadLangPack
{
    protected $app;

    protected $lang;

    public function __construct(App $app, Lang $lang)
    {
        $this->app  = $app;
        $this->lang = $lang;
    }

    /**
     * 路由初始化（路由规则注册）
     * @access public
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        $name = $this->app->http->getName();
        $name = $name=='api' ? 'index':$name;
        if ($name=='admin' || $name=='index') {
            // 获取数据库设定的默认语言
            $config = site();
            if (!empty($config[$name.'_lang'])) {
                $defaultLang = $config[$name.'_lang'];
            } else {
                $defaultLang = Db::name('config')->where(['name'=>$name.'_lang'])->value('value');
            }
            if (empty($defaultLang)) {
                $defaultLang = config('lang.default_lang');
            }

            // 自动侦测当前语言
            $langset = $this->detect($request);
            if (!empty($langset)) { // 覆盖默认语言
                $defaultLang = $langset;
            }

            // 缓存清理
            if ($name=='index') {
                $oldLang = $this->app->cookie->get('old_'.$name.'_'.config('lang')['cookie_var']);
                if ($defaultLang!=$oldLang) {
                    clear_cache('temp','index');
                }
            }

            $this->app->lang->setLangSet($defaultLang);

            if ($name=='index') {
                $this->app->cookie->set('old_'.$name.'_'.config('lang')['cookie_var'], $defaultLang);
            }

            if ('en' != $defaultLang) { // 默认en，不需要去加载en
                // 加载TP系统语言包
                $this->lang->load([
                    $this->app->getThinkPath() . 'lang' . DIRECTORY_SEPARATOR . $defaultLang . '.php',
                ]);

                $this->app->LoadLangPack($defaultLang);
            }

//            $this->saveToCookie($this->app->cookie);
            $this->app->cookie->set($name.'_'.config('lang')['cookie_var'], $defaultLang);
        }

        return $next($request);
    }

    /**
     * 自动侦测设置获取语言选择
     * @access public
     * @param Request $request
     * @return string
     */
    public function detect(Request $request): string
    {
        // 自动侦测设置获取语言选择
        $langSet = '';
        $config = config('lang');

        // 多语言的情况下
        $name = $this->app->http->getName();
        $site = site();
        if ($site['content_lang_on']==1 && $name=='index') {
            $url = $request->url();
            preg_match("/(?<=\/)[A-Za-z_\-]+(?=\/)/", $url, $lang);
            if (!empty($lang) && isset($site['index_lang_list'][$lang[0]])) {
                //$lang = str_replace('/','', $lang[0]);
                return $lang[0];
            }
        }

        if ($request->get($config['detect_var'])) {
            // url中设置了语言变量
            $langSet = strtolower($request->get($config['detect_var']));
        } elseif ($request->header($config['header_var'])) {
            // Header中设置了语言变量
            $langSet = strtolower($request->header($config['header_var']));
        } elseif ($request->cookie(app()->http->getName().'_'.$config['cookie_var'])) {
            // Cookie中设置了语言变量
            $langSet = strtolower($request->cookie(app()->http->getName().'_'.$config['cookie_var']));
        }

        if (empty($config['allow_lang_list']) || in_array($langSet, $config['allow_lang_list'])) {
            // 合法的语言
            return $langSet;
        } else {
            return '';
        }
    }

    /**
     * 保存当前语言到Cookie
     * @access public
     * @param Cookie $cookie Cookie对象
     * @return void
     */
    public function saveToCookie(Cookie $cookie)
    {
        $config = config('lang');
        if ($config['use_cookie']) {
            $cookie->set(app()->http->getName().'_'.$config['cookie_var'], $this->detect(request()));
        }
    }
}
