<?php
declare (strict_types = 1);

namespace app\index\middleware;

use think\Request;

class LoadLangPack extends \think\middleware\LoadLangPack
{
    // 重写检测语言方法
    protected function detect(Request $request): string
    {
        $domain_detect = env('INDEX_LANG_DETECT.DOMAIN_DETECT', false);
        if ($domain_detect) {
            $lang = $this->getLangSet($request, env('INDEX_LANG_DETECT.DOMAIN_RULE', []));
            if ($lang != '') {
                return $lang;
            }
        }

        return parent::detect($request);
    }

    // 根据请求及规则获取语言
    private function getLangSet(Request $request, array $rules): string
    {
        $map = [];
        foreach ($rules as $v) {
            $val  = str_replace('，', ',', $v);
            $item = explode(',', $v);
            foreach ($item as $val) {
                $it          = explode('=', $val);
                $map[$it[0]] = $it[1];
            }
        }
        
        return $map[$request->host()] ?? '';
    }
}
