<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\model\ArticleCategoryModel;
use app\index\model\ArticleModel;
use app\index\model\SysBannerModel;
use think\facade\View;

/**
 * 专题-Nas控制器
 */
class TopicNas extends Common
{
    /**
     * 重写控制器初始化
     */
    protected function initialize()
    {
        // 获取国家/语言列表
        $languages = $this->getLanguages();
        // 输出国家/语言列表
        if (get_platform() == 'mobile') {
            View::assign('header_languages', $languages);
        }

        // 获取当前语言
        $current_language = $this->getCurrentLanguage($languages);
        if (!empty($current_language)) {
            $this->lang_id = $current_language['id'];
        }

        // 获取产品分类
        $categorys = $this->getProductCategory($this->lang_id);
        // 输出产品分类
        View::assign('header_categorys', $categorys);

        // 输出顶部导航
        View::assign('header_navigation', $this->getNavigation('NAV_680ef95e9db90', $this->lang_id));

        // 获取系统配置
        $configs = $this->getSysConfig($this->lang_id, ['basic', 'contact', 'media']);
        $this->basic_config = $configs['basic'];
        // 输出系统配置
        View::assign('basic_config', $configs['basic']);
        View::assign('contact_config', $configs['contact']);
        View::assign('media_config', $configs['media']);

        // 获取底部导航
        $footer_navigation = $this->getNavigation('NAV_67f60be43df8d', $this->lang_id);
        // 输出底部导航
        View::assign('footer_navigation', $footer_navigation);
    }

    /**
     * 专题-Nas首页
     */
    public function index()
    {
        $focus_image  = [];
        $nas_category = [];
        $nas_video    = [];
        $nas_solution = [];
        $nas_software = [];
        // 获取banner数据
        $banners = SysBannerModel::with(['items' => function($query) {
                $query->withoutField(['sort', 'created_at', 'updated_at', 'deleted_at'])
                    ->order(['sort' => 'asc', 'id' => 'desc'])
                    ->enabled(true);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel([
                'BANNER_680f156a805a8',
                'BANNER_680f15ca5482f',
                'BANNER_680f161b5fd3a',
                'BANNER_680f16358f14c',
                'BANNER_680f1e5132184'
            ])
            ->language($this->lang_id)
            ->enabled(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        if (!$banners->isEmpty()) {
            $banners_map = [];
            foreach ($banners as $banner) {
                $banners_map[$banner->unique_label] = $banner;
            }
            $focus_image  = data_get($banners_map, 'BANNER_680f156a805a8')?->items->toArray();
            $nas_category = data_get($banners_map, 'BANNER_680f15ca5482f')?->items->chunk(3)?->toArray();
            $nas_video    = data_get($banners_map, 'BANNER_680f161b5fd3a')?->items->first()?->toArray();
            $nas_solution = data_get($banners_map, 'BANNER_680f16358f14c')?->items->toArray();
            $nas_software = data_get($banners_map, 'BANNER_680f1e5132184')?->items->toArray();
        }
        View::assign('focus_image', $focus_image);
        View::assign('nas_category', $nas_category);
        View::assign('nas_video', $nas_video);
        View::assign('nas_solution', $nas_solution);
        View::assign('nas_software', $nas_software);

        return View::fetch('index');
    }

    /**
     * 专题-Nas产品体验页
     */
    public function product()
    {
        $focus_image        = [];
        $step               = [];
        $trial_instructions = [];
        // 获取banner数据
        $banners = SysBannerModel::with(['items' => function($query) {
                $query->withoutField(['sort', 'created_at', 'updated_at', 'deleted_at'])
                    ->order(['sort' => 'asc', 'id' => 'desc'])
                    ->enabled(true);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel([
                'BANNER_68103aaebe4c4',
                'BANNER_68103acd1a8b9',
                'BANNER_68103daed6623'
            ])
            ->language($this->lang_id)
            ->enabled(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        if (!$banners->isEmpty()) {
            $banners_map = [];
            foreach ($banners as $banner) {
                $banners_map[$banner->unique_label] = $banner;
            }
            $focus_image        = data_get($banners_map, 'BANNER_68103aaebe4c4')?->items->first()?->toArray();
            $step               = data_get($banners_map, 'BANNER_68103acd1a8b9')?->items->toArray();
            $trial_instructions = data_get($banners_map, 'BANNER_68103daed6623')?->items->toArray();
        }
        View::assign('focus_image', $focus_image);
        View::assign('step', $step);
        View::assign('trial_instructions', $trial_instructions);

        return View::fetch('product');
    }

    /**
     * 专题-Nas客户合作页
     */
    public function cooperation()
    {
        $focus_image            = [];
        $cooperation_methods    = [];
        $cooperation_advantages = [];
        $cooperation_cotacts    = [];
        // 获取banner数据
        $banners = SysBannerModel::with(['items' => function($query) {
                $query->withoutField(['sort', 'created_at', 'updated_at', 'deleted_at'])
                    ->order(['sort' => 'asc', 'id' => 'desc'])
                    ->enabled(true);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel([
                'BANNER_6810670b8ef17',
                'BANNER_681067451b78f',
                'BANNER_6810685ab7c6c',
                'BANNER_681068ab73073'
            ])
            ->language($this->lang_id)
            ->enabled(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        if (!$banners->isEmpty()) {
            $banners_map = [];
            foreach ($banners as $banner) {
                $banners_map[$banner->unique_label] = $banner;
            }
            $focus_image            = data_get($banners_map, 'BANNER_6810670b8ef17')?->items->first()?->toArray();
            $cooperation_methods    = data_get($banners_map, 'BANNER_681067451b78f')?->items->toArray();
            $cooperation_advantages = data_get($banners_map, 'BANNER_6810685ab7c6c')?->items->toArray();
            $cooperation_cotacts    = data_get($banners_map, 'BANNER_681068ab73073')?->items->chunk(3)?->toArray();
        }
        View::assign('focus_image', $focus_image);
        View::assign('cooperation_methods', $cooperation_methods);
        View::assign('cooperation_advantages', $cooperation_advantages);
        View::assign('cooperation_cotacts', $cooperation_cotacts);

        return View::fetch('cooperation');
    }
    
    /**
     * 专题-Nas帮助中心页
     */
    public function help()
    {
        // 获取文章分类及文章数据
        $parent = ArticleCategoryModel::uniqueLabel('CATEGORY_681182e0a4529')->language($this->lang_id)->value('id');
        $parent_two = ArticleCategoryModel::parent($parent)->language($this->lang_id)->column('id');//二级分类id
        array_push($parent_two,$parent);
        $article_categorys = ArticleCategoryModel::with(['article' => function($query) {
                $query->field(['id', 'title', 'category_id'])
                    ->order(['sort' => 'asc', 'id' => 'desc'])
                    ->limit(3);
            }])
            ->field([
                'id',
                'pid',
                'name',
                'icon'
            ])
            ->language($this->lang_id)
//            ->parent($parent)
            ->parentChild($parent_two)
            ->isShow(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        //查询三级分类
        $article_categorys_new = [];
        $article_categorys_two = [];
//        dump($article_categorys->toArray());exit;
        if (!$article_categorys->isEmpty()) {
            foreach ($article_categorys->toArray() as $kk=>$vv) {
                if ( $parent == $vv['pid'] ) {
                    array_push($article_categorys_new,$vv);
                } else {
                    $article_categorys_two[$vv['pid']][] = $vv;
                }
            }
            if ( !empty($article_categorys_two) ) {
                foreach ($article_categorys_new as &$vvv) {
                    $articles = $vvv['article'];
                    if ( isset($article_categorys_two[$vvv['id']]) ) {
                        foreach ($article_categorys_two[$vvv['id']] as $v) {
                            foreach ($v['article'] as $av) {
                                if ( count($articles) < 3 ) {
                                    array_push($articles,$av);
                                }
                            }
                        }
                    }
                    $vvv['article'] = $articles;
                }
            }
        }


        View::assign('article_categorys', $article_categorys_new);
//        View::assign('article_categorys', $article_categorys);

        $contacts = [];
        // 获取banner数据
        $banners = SysBannerModel::with(['items' => function ($query) {
                $query->withoutField(['sort', 'created_at', 'updated_at', 'deleted_at'])
                    ->order(['sort' => 'asc', 'id' => 'desc'])
                    ->enabled(true);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel(['BANNER_6819754be2dc6'])
            ->language($this->lang_id)
            ->enabled(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        if (!$banners->isEmpty()) {
            $banners_map = [];
            foreach ($banners as $banner) {
                $banners_map[$banner->unique_label] = $banner;
            }
            $contacts = data_get($banners_map, 'BANNER_6819754be2dc6')?->items->toArray();
        }
        View::assign('contacts', $contacts);

        return View::fetch('help');
    }

    /**
     * 专题-Nas帮助中心详情
     */
    public function helpDetail()
    {
        $id = request()->get('id');
        // 获取文章详情
        $article = ArticleModel::bypk($id)->find();
        View::assign('article', $article);

        // 获取文章分类及文章数据
        $parent = ArticleCategoryModel::uniqueLabel('CATEGORY_681182e0a4529')->language($this->lang_id)->value('id');
        $parent_two = ArticleCategoryModel::parent($parent)->language($this->lang_id)->column('id');//二级分类id
        array_push($parent_two,$parent);
        $article_categorys = ArticleCategoryModel::with(['article' => function ($query) {
                $query->field(['id', 'title', 'category_id'])->order(['sort' => 'asc', 'id' => 'desc']);
            }])
            ->field([
                'id',
                'pid',
                'name',
                'icon'
            ])
            ->language($this->lang_id)
//            ->parent($parent)
            ->parentChild($parent_two)
            ->isShow(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
//        dump($article_categorys->toArray());exit;
        //查询三级分类
        $article_categorys_new = [];
        $article_categorys_two = [];
        if (!$article_categorys->isEmpty()) {
            foreach ($article_categorys->toArray() as $kk=>$vv) {
                if ( $parent == $vv['pid'] ) {
                    $vv['child'] = '';
                    array_push($article_categorys_new,$vv);
                } else {
                    $article_categorys_two[$vv['pid']][] = $vv;
                }
            }
            if ( !empty($article_categorys_two) ) {
                foreach ($article_categorys_new as &$vvv) {
                    $vvv['child'] = isset($article_categorys_two[$vvv['id']])?$article_categorys_two[$vvv['id']]:'';
                }
            }
        }
//        dump($article_categorys_new);exit;
//        dump($article_categorys_two);exit;

        View::assign('article_categorys', $article_categorys_new);

        return View::fetch('help_detail');
    }

    /**
     * 专题-Nas帮助中心搜索
     */
    public function helpSearch()
    {
        $keywords = request()->post('keywords');
        // 根据关键词查询文章
        $parent = ArticleCategoryModel::uniqueLabel('CATEGORY_681182e0a4529')
            ->language($this->lang_id)
            ->value('id');
            
        // 获取帮且中心分类子分类
        $categorys  = [];
        $table_name = (new ArticleCategoryModel)->getTable();
        if (env('DB_VERSION', '5') == '8') {
            $categorys = \think\facade\Db::query(preg_replace(
                '/\s+/u', 
                ' ',
                "WITH RECURSIVE article_tree_by AS (
                    SELECT a.id, a.pid FROM $table_name a WHERE a.id = {$parent}
                    UNION ALL
                    SELECT k.id, k.pid FROM $table_name k INNER JOIN article_tree_by t ON t.id = k.pid
                )
                SELECT id FROM article_tree_by WHERE id <> {$parent}"
            ));
        } else {
            $categorys = \think\facade\Db::query("
                SELECT t2.id
                    FROM ( 
                        SELECT 
                            @r AS _id, (SELECT @r := GROUP_CONCAT(id) FROM $table_name WHERE FIND_IN_SET(pid, _id)) AS parent_id
                        FROM 
                            (SELECT @r := $parent) vars, $table_name h 
                        WHERE @r <> 0) t1 
                    JOIN $table_name t2 
                    ON FIND_IN_SET(t2.pid, t1._id)
                ORDER BY t2.id;
            ");
        }
        if (empty($categorys)) return success('success', []);

        // 获取文章数据
        $articles = ArticleModel::field([
                'id',
                'category_id',
                'title'
            ])
            ->withSearch(['title'], [
                'title' => $keywords??null
            ])
            ->language($this->lang_id)
            ->where('category_id', 'IN', array_column($categorys, 'id'))
            ->select();
        //查询上级id
        $parent_two = ArticleCategoryModel::parentColumn(array_column($categorys, 'id'))->language($this->lang_id)->column('pid','id');//二级分类id
        $articles_data = $articles->toArray();
        foreach ($articles_data as &$v) {
            $v['pid'] = 0;
            if ( $parent_two[$v['category_id']] !== $parent ) {
                $v['pid'] = $v['category_id'];
                $v['category_id'] = $parent_two[$v['category_id']];
            }
        }

        return success('success', $articles_data);
    }
    
    /**
     * 专题-Nas软件下载页
     */
    public function download()
    {
        $data = [];
        // 获取banner数据
        $banners = SysBannerModel::with(['items' => function($query) {
                $query->withoutField(['sort', 'created_at', 'updated_at', 'deleted_at'])
                    ->order(['sort' => 'asc', 'id' => 'desc'])
                    ->enabled(true);
            }])
            ->atPlatform(request()->from)
            ->uniqueLabel([
                'BANNER_6810798e6e828',
                'BANNER_68107a0a63910',
                'BANNER_681079cfa83c9',
                'BANNER_68107a1584238'
            ])
            ->language($this->lang_id)
            ->enabled(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();
        if (!$banners->isEmpty()) {
            $banners_map = [];
            foreach ($banners as $banner) {
                $banners_map[$banner->unique_label] = $banner;
            }
            $cyber_image = data_get($banners_map, 'BANNER_6810798e6e828')?->items->first()?->toArray();
            if (!empty($cyber_image)) $data['cyber']['focus_image'] = $cyber_image;
            
            $weline_image = data_get($banners_map, 'BANNER_68107a0a63910')?->items->first()?->toArray();
            if (!empty($weline_image)) $data['weline']['focus_image'] = $weline_image;

            $cyber_down_items = data_get($banners_map, 'BANNER_681079cfa83c9')?->items->toArray();
            if (!empty($cyber_down_items)) $data['cyber']['down_items'] = $cyber_down_items;
            
            $weline_down_items = data_get($banners_map, 'BANNER_68107a1584238')?->items->toArray();
            if (!empty($weline_down_items)) $data['weline']['down_items'] = $weline_down_items;
        }
        View::assign('data', $data);

        return View::fetch('download');
    }
}
