<?php
/**
 * Copyright: Shanghai NuLang Network Technology Co., Ltd.
 * Faith: Some things do not need others to understand.
 * Project: CoverCMS <Your world, your ambition>
 * License: http://www.svipplus.cn/license/
 * Author: The Rain° <rain@svipplus.cn>
 * File: CacheKit.php
 * Time: 10:59
 */

namespace app\common\toolKit;


use think\Db;

class CacheKit
{
    /**
     * 更新所有站点缓存
     */
    public static function updateSiteCache()
    {
        self::baseUpdate('sites', 'site');
    }

//    public static function updateModelCache()
//    {
//        $models = [
//            ['name'=>'文章模型','value'=>1],
//            ['name'=>'视频模型','value'=>1],
//            ['name'=>'单页模型','value'=>1],
//        ];
//    }

    public static function updateCategoryCache()
    {
        $siteId = SiteKit::currentSiteId();
        self::baseUpdate('categories.site.'.$siteId,'category',['site_id'=>$siteId]);
        self::updateCategoryListTreeCache($siteId);
        self::updateCategoryTreeCache($siteId);
    }

    /**
     * 更新栏目树缓存
     * @param $siteId
     */
    private static function updateCategoryTreeCache($siteId)
    {
        $homePng = asset('share/img/home.png');
        $folderGif = asset('share/img/folder.gif');
        $itemPng = asset('share/img/item.png');
        $baseItem = cache('categories.site.' . $siteId);
        $treeResult[1]['id'] = '1';
        $treeResult[1]['parent'] = '#';
        $treeResult[1]['state'] = ['opened' => true];
        $treeResult[1]['icon'] = $homePng;
        $treeResult[1]['text'] = '所有栏目';
        if (count($baseItem) > 0) {
            $categories = self::categories($siteId);
            foreach ($baseItem as $datum) {
                $key = intval($datum['id']) + 1;
                if ($datum['has_children']) {
                    if (!self::checkChildrenCType($categories, intval($datum['id']))){
                        continue;
                    }else{
                        $treeResult[$key]['icon'] = $folderGif;
                    }
                } else {
                    if (intval($datum['c_type'])===0){
                        continue;
                    }else{
                        $treeResult[$key]['icon'] = $itemPng;
                        $treeResult[$key]['c_type'] = $datum['c_type'];
                        $controller = CommonKit::getModelByCType($datum['c_type']);
                        $url = url('dash/'.$controller.'/index', ['category_id' => $datum['id']]);
                        $treeResult[$key]['a_attr'] = ['onclick' => 'switchArchiveLayout(\'' . $url . '\')'];
                    }
                }
                $treeResult[$key]['id'] = (string)(intval($datum['id']) + 1);
                $treeResult[$key]['parent'] = (string)(intval($datum['parent_id']) + 1);
                $treeResult[$key]['text'] = $datum['title'];
                if ($datum['layer'] < 4) {
                    $treeResult[$key]['state'] = ['opened' => true];
                }
                $treeResult[$key]['has_children'] = $datum['has_children'];
                $treeResult[$key]['all_children'] = $datum['all_children'];
            }
        }
        cache('categories.tree.site.' . $siteId, $treeResult);
    }

    private static function checkChildrenCType($categories, $cateId)
    {
        $currentCategory = $categories[$cateId];
        $currentCategoryAllChildren = json_decode($currentCategory['all_children']);
        $has = false;
        foreach ($currentCategoryAllChildren as $child){
            $childCategory = $categories[intval($child)];
            if (!$childCategory['has_children'] && intval($childCategory['c_type'])!==0){
                $has = true;
                break;
            }
        }
        return $has;
    }

    private static function categories($siteId)
    {
        return cache('categories.site.'.$siteId);
    }

    /**
     * 更新栏目列表树缓存
     * @param $siteId
     */
    private static function updateCategoryListTreeCache($siteId)
    {
        $baseItem = cache('categories.site.' . $siteId);
        $tree = [];
        if (count($baseItem) > 0) {
            $tree = self::tree($baseItem, 0, 1);
        }
        cache('categories.list.tree.site.' . $siteId, $tree);
    }

    /**
     * 栏目列表树底层方法
     * @param $list
     * @param int $pid
     * @param int $level
     * @return array
     */
    private static function tree(&$list, $pid = 0, $level = 0)
    {
        static $tree = [];
        $icon = ['&nbsp;&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ '];
        $blank = '&nbsp;&nbsp;';
        foreach ($list as $v) {
            if ($v['parent_id'] == $pid) {
                $v['layer'] = $level;
                $i = str_repeat($blank, (intval($level) - 1) * 2);
                if (intval($v['parent_id']) === 0) {
                    $v['title'] = $i . $icon[0] . $v['title'];
                } else {
                    if ($v['has_children']) {
                        $v['title'] = $i . $icon[1] . $v['title'];
                    } else {
                        $v['title'] = $i . $icon[2] . $v['title'];
                    }
                }
                $tree[] = $v;
                self::tree($list, $v['id'], $level + 1);
            }
        }
        return $tree;
    }

//    public static function updateKfCache()
//    {
//        self::baseUpdate('kfs','kefu');
//    }

    public static function updateManagerCache()
    {
        self::baseUpdate('managers', 'manager');
    }

    /**
     * @param $item
     * @param $sheet
     * @param array $options
     */
    private static function baseUpdate($item, $sheet, array $options = [])
    {
        $data = Db::name($sheet)->where($options)->order('weight desc')->select();
        $result = [];
        if (count($data) > 0) {
            foreach ($data as $datum) {
                $result[$datum['id']] = $datum;
            }
        }
        cache($item, $result);
    }
}