<?php

namespace app\admin\service\sys_manage;

use app\model\SysCategory;
use support\Db;
use support\Request;

class CategoryService
{
    /**
     * @Desc 分类列表
     * @Author Gorden
     * @Date 2024/2/22 11:28
     *
     * @param $page
     * @param $limit
     * @param $keywords
     * @return \support\Response
     */
    public static function categoryList($page, $limit, $keywords)
    {
        $list = SysCategory::select('*')
            ->when($keywords != '', function ($query) use ($keywords) {
                $query->where('category_name', 'like', '%' . $keywords . '%');
            })
            ->orderBy('category_addtimes', 'DESC')
            ->forPage($page, $limit)
            ->get()
            ->toArray();
        $count = SysCategory::when($keywords != '', function ($query) use ($keywords) {
            $query->where('category_name', 'like', '%' . $keywords . '%');
        })->count();

        return json_success('', compact('list', 'page', 'limit', 'count'));
    }

    /**
     * @Desc 分类详情
     * @Author Gorden
     * @Date 2024/2/22 11:37
     *
     * @param $id
     * @return \support\Response
     */
    public static function categoryInfo($id)
    {
        $category = SysCategory::where('category_id', $id)->first();
        if (!$category) {
            return json_fail('分类不存在');
        }

        return json_success('', $category->toArray());
    }

    /**
     * @Desc 添加分类
     * @Author Gorden
     * @Date 2024/2/22 10:25
     *
     * @param $params
     * @return \support\Response
     */
    public static function insertCategory($params)
    {
        DB::beginTransaction();
        try {
            $data = [
                'category_name' => $params['category_name'],
                'category_super_id' => $params['category_super_id'] ?? 0,
                'category_status' => $params['category_status'],
                'category_classify' => $params['category_classify'] ?? '',
                'category_type' => $params['category_type'] ?? '',
                'category_icon' => $params['category_icon'] ?? '',
                'category_images' => $params['category_images'] ?? '',
                'category_url' => $params['category_url'] ?? '',
                'category_page' => $params['category_page'] ?? '',
                'category_sort' => $params['category_sort'] ?? '',
                'category_groupby' => $params['category_groupby'] ?? '',
                'category_remark' => $params['category_remark'] ?? '',
                'category_extend_json' => !empty($params['category_extend_json']) ? $params['category_extend_json'] : '{}',
                'category_addtimes' => time()
            ];
            $categoryId = SysCategory::insertGetId($data);
            if (!$categoryId) {
                throw new \Exception('添加分类失败');
            }
            // 不是顶级分类，有path
            if ($params['category_super_id'] != 0) {
                // 回填path
                $parentSuperPath = self::getCategoryPath($params['category_super_id']);
                $superPath = '#' . $params['category_super_id'] . '#';
                if ($parentSuperPath == $superPath) {
                    $categorySuperPath = $superPath;
                } else {
                    $categorySuperPath = $parentSuperPath . $superPath;
                }
                SysCategory::where('category_id', $categoryId)->update(['category_super_path' => $categorySuperPath]);
            }
            // 提交事务
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            dump($e->getMessage());
            return json_fail('添加分类失败');
        }

        return json_success('添加分类成功');
    }

    /**
     * @Desc 修改分类
     * @Author Gorden
     * @Date 2024/2/22 11:14
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateCategory($id, $params)
    {
        try {
            $category = SysCategory::select('category_super_id')->where('category_id', $id)->first();
            if (!$category) {
                throw new \Exception('分类不存在');
            }
            $data = [
                'category_name' => $params['category_name'],
                'category_classify' => $params['category_classify'] ?? '',
                'category_type' => $params['category_type'] ?? '',
                'category_icon' => $params['category_icon'] ?? '',
                'category_images' => $params['category_images'] ?? '',
                'category_url' => $params['category_url'] ?? '',
                'category_page' => $params['category_page'] ?? '',
                'category_sort' => $params['category_sort'] ?? '',
                'category_groupby' => $params['category_groupby'] ?? '',
                'category_remark' => $params['category_remark'] ?? '',
                'category_status' => $params['category_status'] ?? '',
                'category_extend_json' => !empty($params['category_extend_json']) ? $params['category_extend_json'] : '{}',
                'category_addtimes' => time()
            ];
            if ($category->category_super_id != $params['category_super_id'] && $params['category_super_id'] != 0) {
                $data['category_super_id'] = $params['category_super_id'];
                $parentSuperPath = self::getCategoryPath($params['category_super_id']);
                $superPath = '#' . $params['category_super_id'] . '#';
                if ($parentSuperPath == $superPath) {
                    $data['category_super_path'] = $superPath;
                } else {
                    $data['category_super_path'] = $parentSuperPath . $superPath;
                }

            }
            if (!SysCategory::where('category_id', $id)->update($data)) {
                throw new \Exception('分类修改失败');
            }
        } catch (\Exception $e) {
            return json_fail('分类修改失败');
        }

        return json_success('分类修改成功');
    }

    /**
     * @Desc 修改分类状态
     * @Author Gorden
     * @Date 2024/2/22 11:49
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateStatus($id, $params)
    {
        try {
            SysCategory::where('category_id', $id)->update(['category_status' => $params['category_status']]);
        } catch (\Exception $e) {
            return json_fail('分类状态修改失败');
        }

        return json_success('分类状态修改成功');
    }

    /**
     * @Desc 删除分类
     * @Author Gorden
     * @Date 2024/2/22 11:56
     *
     * @param $id
     * @return \support\Response
     */
    public static function delCategory(Request $request)
    {
        $ids = $request->post('category_id');
        if (!$ids) {
            return json_fail("数据错误");
        }
        try {
            if (is_array($ids)) {
                SysCategory::whereIn('category_id', $ids)->delete();
            } else {
                SysCategory::where('category_id', $ids)->delete();
            }
        } catch (\Exception $e) {
            return json_fail('分类删除失败');
        }

        return json_success('分类删除成功');
    }

    /**
     * @Desc 获取path
     * @Author Gorden
     * @Date 2024/2/22 10:40
     *
     * @param $categoryId
     * @return int|mixed
     */
    public static function getCategoryPath($categoryId)
    {
        $category = SysCategory::where('category_id', $categoryId)->first();
        if (!$category) {
            throw new \Exception('分类不存在');
        }
        if (empty($category->category_super_path)) {
            return "#" . $categoryId . "#";
        }
        return $category->category_super_path;
    }

    /**
     * Notes: 获取树状分类信息
     * User: ZhouBenXu
     * DateTime: 2024/7/2 下午2:52
     * @param $parentId
     * @return \support\Response
     */
    public static function getCategoryTree($parentId)
    {
        // 查询当前父级ID下的所有分类
        $list = self::getAllCategories($parentId);
        $allCategories = self::getTree($list, 152);
        return json_success('', $allCategories);
    }

    /**
     * Notes: 获取指定分类下的所有分类
     * User: ZhouBenXu
     * DateTime: 2024/7/2 下午2:41
     * @param $parentId
     * @param $categories
     * @return array|mixed
     */
    public static function getAllCategories($parentId = 0, $categories = [])
    {
        // 查询当前父级ID下的所有分类
        $row = SysCategory::where('category_super_id', $parentId)->where('category_status', 'ACTIVED')->get()->toArray();
        if (!empty($row)) {
            foreach ($row as $key => $value) {
                // 当前分类加入数组
                $value['label'] = $value['category_name'];
                $value['value'] = $value['category_id'];
                $categories[] = $value;
                // 递归查询子分类
                $categories = self::getAllCategories($value['category_id'], $categories);
            }
        }
        return $categories;
    }

    /**
     * Notes: 树状结构
     * User: ZhouBenXu
     * DateTime: 2024/7/2 下午2:51
     * @param $list
     * @param $id
     * @return array
     */
    public static function getTree($list = [], $id = 0)
    {
        $tree = array();
        foreach ($list as $k => $v) {
            if ($v['category_super_id'] == $id) {
                if (!empty(self::getTree($list, $v['category_id']))) {
                    $v['children'] = self::getTree($list, $v['category_id']);
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }


    /**
     * @Desc 分类详情
     * @Author Gorden
     * @Date 2024/2/22 11:37
     *
     * @param $id
     * @return \support\Response
     */
    public static function getCategoryInfos($ids)
    {
        $category = SysCategory::whereIn('category_id', $ids)->select(['category_id', 'category_name', 'category_super_id'])->get()->toArray();
        if (!$category) {
            return json_fail('分类不存在');
        }
        return $category;
    }

    /**
     * @Desc 获取分类及父级
     * @Author Gorden
     * @Date 2024/12/10 15:54
     *
     * @param $category_id
     * @return array
     */
    public static function getCategoryAndSupper($category_id = [])
    {
        $categoryNames = [];
        foreach ($category_id as $id) {
            $category = SysCategory::where('category_id', $id)->first();
            if (!empty($category) && !empty($category->category_super_path)) {
                $superIds = array_filter(array_unique(explode('#', $category->category_super_path)));
                $superCategory = SysCategory::whereIn('category_id', $superIds)->pluck('category_name', 'category_id')->toArray();
                foreach ($superIds as $superId) {
                    if (key_exists($superId, $superCategory)) {
                        if (isset($categoryNames[$id])) {
                            $categoryNames[$id] = $categoryNames[$id] . $superCategory[$superId] . ' / ';
                        }else{
                            $categoryNames[$id] = $superCategory[$superId] . ' / ';
                        }
                    }
                }
                $categoryNames[$id] = $categoryNames[$id] . $category->category_name;
            }
        }

        return $categoryNames;
    }

}