<?php

namespace App\Services\goods;

use App\Models\goods\mysql\Category;

class CategoryService
{
    /**
     * 商品分类列表数据
     * @param string $name
     * @return array
     */
    public static function getCategoryList($name = "")
    {
        $where = [];
        if (!empty($name)) {
            $where["name[~]"] = "%" . $name . "%";
            $where["level"] = Category::LEVEL_2;
        }
        $allCategoryList = Category::getRecordList($where, ['category_id', 'parent_category_id', 'name', 'level']);
        $data = [];
        if (!empty($allCategoryList)) {
            $levelOneIdKeys = [];
            foreach ($allCategoryList as $caregory) {
                $levelOneIdKeys[$caregory["parent_category_id"]] = 1;
            }
            $levelOneIds = array_keys($levelOneIdKeys);
            $levelOneCategoryList = Category::getRecordList(["category_id" => $levelOneIds], ['category_id', 'parent_category_id', 'name', 'level']);
            foreach ($levelOneCategoryList as $key => $levelOneCategory) {
                $data[] = [
                    "category_id" => $levelOneCategory["category_id"],
                    "name" => $levelOneCategory["name"],
                ];
            }
            foreach ($allCategoryList as $caregory) {
                foreach ($data as $key => $item) {
                    if ($item["category_id"] == $caregory["parent_category_id"] && $caregory["level"] != Category::LEVEL_1) {
                        $data[$key]["sub_list"][] = [
                            "category_id" => $caregory["category_id"],
                            "name" => $caregory["name"],
                        ];
                    }
                }
            }
        }
        return $data;
    }

    /**
     * 查询一级商品分类
     * @return \Api\PhpUtils\Mysql\MysqlBase
     */
    public static function getLevelOneCategory()
    {
        return Category::getRecordList(["level"=>Category::LEVEL_1], ['category_id', 'name']);
    }
}