<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\ArticleCategoryModel;
use app\admin\model\v1\ArticleModel;
use app\admin\model\v1\ProductCategoryModel;
use app\admin\model\v1\ProductModel;
use think\facade\Db;

class System
{
    // 系统信息
    public function info()
    {
        $mysql_version = Db::query('select version() as version');
        $info = [
            [
                'name'  => '操作系统',
                'value' => PHP_OS
            ],
            [
                'name'  => '运行环境',
                'value' => $_SERVER["SERVER_SOFTWARE"]
            ],
            [
                'name'  => 'PHP版本',
                'value' => PHP_VERSION
            ],
            [
                'name'  => '上传附件限制',
                'value' => ini_get('upload_max_filesize')
            ],
            [
                'name'  => 'MySQL版本',
                'value' => !empty($mysql_version) ? $mysql_version[0]['version'] : '未知'
            ],
            [
                'name'  => '最大执行时间',
                'value' => ini_get('max_execution_time') . 's'
            ],
            [
                'name'  => 'GD版本',
                'value' => function_exists('gd_info') ? (gd_info()['GD Version']) : '未知'
            ],
            [
                'name'  => '最大占用内存',
                'value' => ini_get('memory_limit')
            ],
            [
                'name'  => '当前时间',
                'value' => date('Y-m-d H:i:s')
            ],
            [
                'name'  => '服务器时区',
                'value' => function_exists("date_default_timezone_get") ? date_default_timezone_get() : '未知'
            ],
            [
                'name'  => '是否开启安全模式',
                'value' => ini_get('safe_mode') ? 'YES' : 'NO'
            ],
            [
                'name'  => '允许打开远程连接',
                'value' => ini_get("allow_url_fopen") ? 'YES' : 'NO'
            ],
            [
                'name'  => 'CURL支持',
                'value' => function_exists('curl_init') ? 'YES' : 'NO'
            ],
            [
                'name'  => 'Zlib支持',
                'value' => function_exists('gzclose') ? 'YES' : 'NO'
            ],
            [
                'name'  => '自身版本',
                'value' => '1.0.0'
            ],
            [
                'name'  => '服务器域名/IP',
                'value' => $_SERVER['HTTP_HOST'] . '[' . gethostbyname($_SERVER['SERVER_NAME']) . ']'
            ]
        ];

        return success('获取成功', $info);
    }

    // 组装系统内页面URL
    public function urls()
    {
        $lang_id = request()->lang_id;

        if (request()->has('link_to')) {
            $param = request()->get([
                'link_to',
                'id'
            ]);

            $urls = [];
            switch ($param['link_to']) {
                case 'article':
                    $articles = $this->getArticleByCategory($lang_id, $param['id']);
                    $urls     = array_map(function($item) {
                        $item['url'] = (string)url('/index/article/detail/' . $item['id']);
                        return $item;
                    }, $articles);
                    break;
                case 'product':
                    $products = $this->getProductByCategory($lang_id, $param['id']);
                    $urls     = array_map(function($item) {
                        $item['url'] = (string)url('/index/product/detail/' . $item['id']);
                        return $item;
                    }, $products);
                    break;
                default:
                    return error('请确认link_to参数');
                    break;
            }
            return success('获取成功', $urls);
        } else {
            // 获取文章分类
            $article_category = $this->getArticleCategory($lang_id);
            // 获取产品分类
            $product_category = $this->getProductCategory($lang_id);

            $urls = [
                [
                    'name'    => '自定义',
                    'link_to' => 'custom',
                    'data'    => []
                ],
                [
                    'name'    => '文章分类',
                    'link_to' => 'article_category',
                    'data'    => array_to_tree(array_map(function($item) {
                        $item['url'] = (string)url('/index/article/index/' . $item['id']);
                        return $item;
                    }, $article_category), 0, 'pid', false, false)
                ],
                [
                    'name'    => '文章管理',
                    'link_to' => 'article',
                    'data'    => array_to_tree($article_category, 0, 'pid', false, false)
                ],
                [
                    'name'    => '产品分类',
                    'link_to' => 'product_category',
                    'data'    => array_to_tree(array_map(function($item) {
                        if ($item['pid'] == 0) {
                            $item['url'] = (string)url('/index/product/category/'. $item['id']);
                        } else {
                            $item['url'] = (string)url('/index/product/subcategory/' . $item['id']);
                        }
                        return $item;
                    }, $product_category), 0, 'pid', false, false)
                ],
                [
                    'name'    => '产品',
                    'link_to' => 'product',
                    'data'    => array_to_tree($product_category, 0, 'pid', false, false)
                ],
                [
                    'name'    => '其他内页',
                    'link_to' => 'system_page',
                    'data'    => self::getSystemOtherPages()
                ]
            ];

            return success('获取成功', $urls);
        }
    }
    // 获取文章分类数据
    private function getArticleCategory($lang_id)
    {
        $data = ArticleCategoryModel::field([
                'id',
                'pid',
                'name'
            ])
            ->language($lang_id)
            ->isShow(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();

        return $data->toArray();
    }
    // 获取产品分类数据
    private function getProductCategory($lang_id)
    {
        $data = ProductCategoryModel::field([
                'id',
                'pid',
                'name'
            ])
            ->language($lang_id)
            ->isShow(true)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();

        return $data->toArray();
    }
    // 根据文章分类获取文章
    private function getArticleByCategory($lang_id, $category_id)
    {
        $data = ArticleModel::field([
                'id',
                'title' => 'name'
            ])
            ->language($lang_id)
            ->category($category_id)
            ->select();

        return $data->toArray();
    }
    // 根据产品分类获取产品
    private function getProductByCategory($lang_id, $category_id)
    {
        $data = ProductModel::field([
                'id',
                'name'
            ])
            ->language($lang_id)
            ->category($category_id)
            ->enabled()
            ->isShow(true)
            ->select();

        return $data->toArray();
    }

    // 获取系统其他内页
    static private function getSystemOtherPages()
    {
        return [
            [
                'id'   => 1,
                'name' => '首页',
                'url'  => (string)url('/index/index/index')
            ],
            [
                'id'   => 2,
                'name' => '新品上市',
                'url'  => (string)url('/index/product/newpro')
            ],
            [
                'id'   => 3,
                'name' => '附件下载',
                'url'  => (string)url('/index/attachment/index')
            ],
            [
                'id'   => 4,
                'name' => '问答中心',
                'url'  => (string)url('/index/faq/index')
            ],
            [
                'id'   => 5,
                'name'     => '关于我们',
                'url'      => '',
                'children' => [
                    [
                        'id'   => 51,
                        'name' => '品牌介绍',
                        'url'  => (string)url('/index/aboutus/introduction')
                    ],
                    [
                        'id'   => 52,
                        'name' => '品牌故事',
                        'url'  => (string)url('/index/aboutus/story')
                    ],
                    [
                        'id'   => 53,
                        'name' => '品牌历程',
                        'url'  => (string)url('/index/aboutus/mileage')
                    ],
                    [
                        'id'   => 54,
                        'name' => '文化介绍',
                        'url'  => (string)url('/index/aboutus/culture')
                    ],
                    [
                        'id'   => 55,
                        'name' => '售后政策',
                        'url'  => (string)url('/index/aboutus/policy')
                    ]
                ]
            ],
            [
                'id'       => 6,
                'name'     => '联系我们',
                'url'      => '',
                'children' => [
                    [
                        'id'   => 61,
                        'name' => '联系我们',
                        'url'  => (string)url('/index/contactus/index')
                    ],
                    [
                        'id'   => 62,
                        'name' => '留言联系我们',
                        'url'  => (string)url('/index/contactus/message')
                    ],
                    [
                        'id'   => 63,
                        'name' => '留言成为分销商',
                        'url'  => (string)url('/index/contactus/distributor')
                    ],
                    [
                        'id'   => 64,
                        'name' => '留言批量购买',
                        'url'  => (string)url('/index/contactus/bulkbuy')
                    ]
                ]
            ],
            [
                'id'       => 7,
                'name'     => 'NAS专题',
                'url'      => '',
                'children' => [
                    [
                        'id'   => 71,
                        'name' => '首页',
                        'url'  => (string)url('/index/topic/nas/index')
                    ],
                    [
                        'id'   => 72,
                        'name' => '产品体验',
                        'url'  => (string)url('/index/topic/nas/product')
                    ],
                    [
                        'id'   => 73,
                        'name' => '客户合作',
                        'url'  => (string)url('/index/topic/nas/cooperation')
                    ],
                    [
                        'id'   => 74,
                        'name' => '帮助中心',
                        'url'  => (string)url('/index/topic/nas/help')
                    ],
                    [
                        'id'   => 75,
                        'name' => '软件下载',
                        'url'  => (string)url('/index/topic/nas/download')
                    ]
                ]
            ],
            [
                'id'       => 8,
                'name'     => '电力品线专题',
                'url'      => '',
                'children' => [
                    [
                        'id'   => 81,
                        'name' => '首页',
                        'url'  => (string)url('/index/topic/power_prodline/index')
                    ],
                ]
            ],
            [
                'id'       => 9,
                'name'     => '笔记本（AI PC）专题',
                'url'      => '',
                'children' => [
                    [
                        'id'   => 91,
                        'name' => '首页',
                        'url'  => (string)url('/index/topic/laptop/index')
                    ],
                ]
            ],
            [
                'id'       => 9,
                'name'     => '闪存（SSD）专题',
                'url'      => '',
                'children' => [
                    [
                        'id'   => 101,
                        'name' => '首页',
                        'url'  => (string)url('/index/topic/ssd/index')
                    ],
                ]
            ]
        ];
    }

    // 根据系统页面url获取回显数据项
    static public function getEchoDataBySystemPageUrl($link_to, $link)
    {
        if ('custom' == $link_to || empty($link)) return [];

        $data   = [];
        $params = [];
        $url    = parse_url($link, PHP_URL_QUERY);
        if (empty($url)) {
            $parts        = explode('/', trim($link, '/'));
            $params['id'] = (int)str_replace('.html', '', end($parts));
        } else {
            parse_str($url, $params);
        }

        switch ($link_to) {
            case 'article_category':
                if (empty($params['id'])) return [];
                $data = ArticleCategoryModel::field(['id', 'name'])->bypk($params['id'])->find();
                break;
            case 'article':
                if (empty($params['id'])) return [];
                $data = ArticleModel::field(['id', 'title' => 'name'])->bypk($params['id'])->find();
                break;
            case 'product_category':
                if (empty($params['id'])) return [];
                $data = ProductCategoryModel::field(['id', 'name'])->bypk($params['id'])->find();
                break;
            case 'product':
                if (empty($params['id'])) return [];
                $data = ProductModel::field(['id', 'name'])->bypk($params['id'])->find();
                break;
            case 'system_page':
                $data = self::filterSystemOtherPage(self::getSystemOtherPages(), function($item) use ($params, $link) {
                    if (empty($params['id'])) return $item['url'] == $link;
                    return $item['id'] == $params['id'];
                });
                break;
            default:
                return [];
                break;
        }
        if (empty($data)) return [];

        return [
            'id'   => $data['id'],
            'name' => $data['name'],
            'link' => $link
        ];
    }

    // 根据条件过滤结果
    static private function filterSystemOtherPage(array $data, callable $callback): array
    {
        foreach ($data as $it) {
            if ($callback($it)) {
                return $it;
            }
            if (isset($it['children'])) {
                $child = self::filterSystemOtherPage($it['children'], $callback);
                if (!empty($child)) {
                    return $child;
                }
            }
        }

        return [];
    }
}
