<?php
namespace app\admin\server\category;

use app\admin\model\Category;

class CategoryServer
{
    /**
     * Notes:获取分类列表
     * @param string $keywords
     * @return array
     * User: ZQ
     * Date: 2022/9/30
     */
    public static function getCategoryList(string $keywords)
    {
        $list = Category::getCategoryList($keywords);
        return $list;
    }

    /**
     * Notes:修改分类
     * @param string $category_name
     * @param int $category_id
     * @param int $category_pid
     * @param int $category_type
     * @param string $category_open_type
     * @param string $category_open_url
     * @param string $category_recommend
     * @return int
     * User: ZQ
     * Date: 2022/9/13
     */
    public static function updateCategory($category_id, $category_name, $category_pid, $category_type, $category_icon, $category_open_type, $category_open_url, $category_sort, $category_recommend)
    {
        Category::affairBegin();
        try {
            $where = [];
            $where['category_id'] = $category_id;
            $data = [];
            $data['category_name'] = $category_name;
            $data['category_pid'] = $category_pid;
            $data['category_type'] = $category_type;
            $data['category_icon'] = $category_icon;
            $data['category_open_type'] = $category_open_type;
            $data['category_open_url'] = $category_open_url;
            $data['category_sort'] = $category_sort;
            $data['category_recommend'] = $category_recommend;
            $data['category_update_time'] = time();
            $result = Category::where($where)->update($data);
            if ($result !== false){
                Category::affairCommit();
                return true;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            Category::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:删除分类
     * @param int $category_id
     * @return int
     * User: ZQ
     * Date: 2022/9/3
     */
    public static function delCategory($category_id)
    {
        Category::affairBegin();
        try {
            $where = [];
            $where['category_id'] = $category_id;
            $data['category_del'] = 1;
            $result = Category::where($where)->update($data);
            if (!empty($result)){
                Category::affairCommit();
                return true;
            }
            throw new \Exception('删除失败！');
        }catch (\Exception $exception){
            Category::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes: 添加分类
     * @param string $category_name
     * @param int $category_pid
     * @return int
     * User: ZQ
     * Date: 2022/9/14
     */
    public static function insertCategory($category_name, $category_pid, $category_type, $category_icon, $category_open_type, $category_open_url, $category_sort, $category_recommend)
    {

        Category::affairBegin();
        try {
            $data = [];
            $data['category_name'] = $category_name;
            $data['category_pid'] = $category_pid;
            $data['category_type'] = $category_type;
            $data['category_icon'] = $category_icon;
            $data['category_open_type'] = $category_open_type;
            $data['category_open_url'] = $category_open_url;
            $data['category_sort'] = $category_sort;
            $data['category_recommend'] = $category_recommend;
            $data['category_create_time'] = time();
            $result =  Category::insertGetId($data);
            if (!empty($result)){
                Category::affairCommit();
                return $result;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            Category::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:查询分类
     * @param int $category_id
     * @return int
     * User: ZQ
     * Date: 2022/9/13
     */
    public static function categoryInfo($category_id)
    {
        $Category = new Category();
        $where = [];
        $where['category_id'] = $category_id;
        $result = Category::where($where)->first();
        $result['category_is_category'] = (int)$result['category_is_category'];
        $result['category_pid_arr'] = $Category->getParentCategoryId($result['category_pid']);
        if (empty($result['category_pid_arr'])){
            $result['category_pid_arr'] = [0];
        }
        $result['category_is_show'] = ($result['category_is_show'] == 1 ? true : false);
        return $result;
    }

    /**
     * Notes:获取菜单列表
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * User: ZQ
     * Date: 2022/9/13
     */
    public static function categoryLevel()
    {
        $list = Category::getLevel(0);
        if (!empty($list)){
            for ($i=0;$i<count($list);$i++){
                $list[$i]['children'] = Category::getLevel($list[$i]['value']);
                if (!empty($list[$i]['children'])){
                    for ($s=0;$s<count($list[$i]['children']);$s++){
                        $list[$i]['children'][$s]['children'] = Category::getLevel($list[$i]['children'][$s]['value']);
                    }
                }
            }
        }

        return $list;
    }
    /**
     * Notes:获取菜单列表
     * @param string $keywords
     * @param int $page
     * @param int $limit
     * @return array
     * User: ZQ
     * Date: 2022/9/13
     */
    public static function secondLevel()
    {
        $list = Category::getLevel(0);
        if (!empty($list)){
            for ($i=0;$i<count($list);$i++){
                $list[$i]['children'] = Category::getLevel($list[$i]['value']);
            }
        }

        return $list;
    }

    /**
     * Notes:修改分类是否推荐
     * @param int $category_recommend
     * @param int $category_id
     * @return int
     * User: ZQ
     * Date: 2022/9/3
     */
    public static function updateStatus($category_id, $category_recommend)
    {
        Category::affairBegin();
        try {
            $where = [];
            $where['category_id'] = $category_id;
            $data = [];
            $data['category_recommend'] = $category_recommend;
            $result = Category::where($where)->update($data);
            if ($result !== false){
                Category::affairCommit();
                return true;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            Category::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:菜单列表
     * @param array $adminInfo
     * @return array
     * User: yym
     * Date: 2022/9/21
     */
    public static function getHomeCategoryList(array $adminInfo)
    {
//        $redis_key = 'roles_' . $adminInfo['admin_roles'];
//        if(Redis::exists($redis_key))
//        {
//            $list = json_decode(Redis::get($redis_key), true);
//        }else{
            $category_list_ids = array();
            if($adminInfo['admin_is_boos'] != 1)
            {
                $rules = SystemRole::getRuleList(explode(',', $adminInfo['admin_roles']));
                if(!empty($rules))
                {
                    foreach ($rules as $row)
                    {
                        $category_list_ids = empty($category_list_ids) ? explode(',', $row['role_rules']) : array_merge($category_list_ids, explode(',', $row['role_rules']));
                    }
                }else{
                    $category_list_ids = array(0);
                }
            }
            if(!empty($category_list_ids))
            {
                $Category = new Category();
                //获取每个自己的父级
                foreach ($category_list_ids as $item)
                {
                    if($item <= 0){
                        continue;
                    }
                    $category_list_ids = array_merge($category_list_ids, $Category->getParentPid($item));
                }
                $category_list_ids = array_unique($category_list_ids);
            }
            $list = Category::getHomeCategoryList($category_list_ids);
//            Redis::setEx($redis_key, 86400, json_encode($list));
//        }
        return $list;
    }

    /**
     * tree 子菜单
     * @param array $data 数据
     * @param int $pid 父级id
     * @param bool $ischild 是否为子集
     * @param int $fatherindex 父级key
     * @return array
     * User: ZQ
     * Date: 2022/11/03
     */
    public static function rebuild_children($data, $pid = 0, $ischild = false, $fatherindex = 0)
    {
        static $arr = array();
        foreach ($data as $key => $value) {
            if ($value['category_pid'] == $pid) {
                if ($ischild) {
                    //下面相当于
                    //array_push($arr[$fatherindex]['children'],$value) ;
                    static $child = array();
                    $child[$fatherindex][] = $value;
                    $arr[$fatherindex]['children'] = $child[$fatherindex];
                    $fatherindex = $fatherindex;
                } else {
                    $arr[$key] = $value;
                    $arr[$key]['children'] = [];
                    $fatherindex = $key;
                }
                //继续当前id的子类
                self::rebuild_children($data, $value['category_id'], true, $fatherindex);
            }
        }
        return (array)$arr;
    }
    /**
     * tree 递归查询所有的分类
     * @return array
     * User: QJF
     * Date: 2022/11/03
     */
    public static function getLower($pid = 0){
        //先查询所有的一级分类
        $data = Category::where(['category_del'=>0,'category_pid'=>$pid])->get()->toArray();
        foreach ($data as $k=>$v){
            $data[$k]['children'] = self::getLower($v['category_id']);
        }
        return $data;
    }

}
