<?php

namespace App\Web\Controllers;

use App\Exceptions\ApiException;
use App\Http\Controllers\BaseController;
use App\Web\Services\BlogService;
use App\Web\Services\WebService;
use App\Web\Services\WebUtmService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\View;

class IndexController extends BaseController
{

    protected $webService = null;
    protected $blogService = null;
    protected $webUtmService;

    /**
     * 构造函数
     * UserController constructor.
     * @param WebService $webService
     * @param BlogService $blogService
     */
    public function __construct(WebService $webService, BlogService $blogService, WebUtmService $webUtmService)
    {
        $this->webUtmService = $webUtmService;
        $this->webService=$webService;
        $this->blogService=$blogService;
    }

    /**
     * 路由公共入口
     */
    public function index(Request $request)
    {
        $urla = $request->route("module", "home"); //模块
        $urla = urldecode($urla);
        //是否开启广告统计功能
        if(config('app.is_utm')) {
            $utmParams = $request->only(['campaign_id', 'campaign_name', 'campaign_source', 'campaign_term', 'campaign_medium', 'campaign_content']);
            $clientIp = $request->getClientIp();
            $clientHost = $request->getHttpHost();
            $clientPath = $request->path();
            $this->webUtmService->statisticAnalysis($utmParams, $clientIp, $clientHost, $clientPath);
        }
        if ($urla == 'sitemap.xml') {
            $xmlStr = $this->webService->getSiteMap();
            return response($xmlStr)->withHeaders([
                'Content-Type' => 'text/xml; charset=UTF-8'
            ]);
        }
        if ($urla == 'robots.txt') {
            $str = "User-agent: *" . "\r\n" . "Allow: /";
            $filename = "robots.txt";
            header("Content-Type: application/octet-stream");
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            echo $str;
            die;
        }
        $pageRenderData =  $this->webService->getWebPageRenderData($urla);
       // print_r($pageRenderData);die;
        $requestParams=$request->all();
        if(!empty($pageRenderData['route_path'])){
            $view=$pageRenderData['route_path'];
        } else {
            $view=$urla.'.index';
            $pageRenderData = [];
        }
        if (!View::exists($view)) {
            //视图不存在，跳转到404页面
            $errorPage= $this->webService->getStaticPageInfo(['route_path'=>'404.index']);
            if(!empty($errorPage['urla'])){
                $redirectUrl='/'.$errorPage['urla'];
            }else{
                $redirectUrl='/404';
            }
            return redirect($redirectUrl);
        }
        $pageRenderData['global_seo_data']=$this->webService->getGlobalSeo();
        $pageRenderData['menu_data']=$this->webService->getWebMenu();
        $pageRenderData['product_type_menu']=$this->webService->getProductTypeMenu();
        $pageRenderData['product_tag_list']=$this->webService->getProductTagRenderData();
        $pageRenderData['plate_type_menu'] = $this->webService->getPlateTypeMenu();
        $pageRenderData['meeting_type_menu'] = $this->webService->getMeetingTypeMenu();
        $pageRenderData['urla']=$urla;
        $hostUrl= config('app.url');
        $pageRenderData['location_url']=$hostUrl.'/'.$urla;
        $pageRenderData['canonical_url']=config('app.web_url').'/'.$urla;
        if(!empty($requestParams)) {
            $pageRenderData = array_merge($pageRenderData, $requestParams);
        }
        $request_scheme = empty($_SERVER['REQUEST_SCHEME']) ? 'http' : $_SERVER['REQUEST_SCHEME'];
        $pageRenderData['request_scheme']=$request_scheme;
        //获取文章列表页面数据
        $pageRenderData['page'] = $request->input('page', 1);
        if (empty($pageRenderData['head_menu'])) {
            $pageRenderData['head_menu'] = [];
        }
        if (empty($pageRenderData['page_content'])) {
            $pageRenderData['page_content'] = [];
        }
//        dd($pageRenderData);
        return view($view, $pageRenderData);
    }

    /**
     * @param string blade 组件名称
     * @param string view_file 视图文件
     * @return mixed
     * @throws \App\Base\Exceptions\ApiException
     * @throws \Illuminate\Validation\ValidationException
     * @api get /blade 获取渲染后的组件html内容
     * @group 客户端 公共接口
     * @successExample
     * {"ret":0,"msg":"success","data":'html'}
     */
    public function blade(Request $request)
    {
        $this->validate($request, [
            'blade' => 'required',
            'view_file' => 'required',
            'page' => 'integer',
            'page_size' => 'integer'
        ], [
            'blade.required' => 'blade不能为空',
            'view_file.required' => 'view_file不能为空',
            'page.integer' =>  'page只能为数字',
            'page_size.integer' =>'page_size只能为数字',
        ]);
        $blade = $request->input("blade");
        $viewFile = $request->input("view_file");
        $components = Blade::getClassComponentAliases();
        $class = $components[$blade] ?? '';
        if (empty($class)) {
            throw new ApiException(1004,['msg'=> $blade]);
        }
        $params = $request->all();
        $c = new $class($viewFile, $params);
        return $c->render();
    }
}
