<?php

namespace app\admin\controller\sys_manage;

use app\admin\service\sys_manage\CategoryService;
use app\admin\validate\sys_manage\CategoryValidate;
use app\common\Tree;
use app\controller\Curd;
use app\model\SysCategory;
use support\Request;
use support\Response;

class CategoryController extends Curd
{
    public function __construct()
    {
        $this->model = new SysCategory();
    }

    public function index(Request $request)
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $format = 'tree';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'category_sort';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, 1000);
    }

    /**
     * @Desc 分类列表
     * @Author Gorden
     * @Date 2024/2/22 11:28
     *
     * @param Request $request
     * @return \support\Response
     */
    public function categoryList(Request $request)
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $format = 'tree';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'category_sort';
        $where['category_status'] = ['in', ['ACTIVED', 'UNSHOW']];
//        dump($where);
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, 1000);
    }

    public function afterQuery($items)
    {
        $categoryType = \request()->get('category_type', '');
        $categoryDatas = [];
        foreach ($items as &$item) {
            if (empty($item->category_super_path)) {
                $item->category_super_path = '#' . $item['category_id'] . '#';
            }
            $categorys = SysCategory::where('category_super_path', 'like', $item->category_super_path . '%')
                ->when(!empty($categoryType), function ($query) use ($categoryType) {
                    $query->where('category_type', $categoryType);
                })->whereIn('category_status', ['ACTIVED', 'UNSHOW'])
                ->paginate(1000)
                ->items();
            $categoryDatas = array_merge($categorys, $categoryDatas);
        }

        $items = array_merge($items, $categoryDatas);

        return $items;
    }

    protected function formatTree($items): Response
    {
        $format_items = [];
        foreach ($items as $item) {
            $format_items[] = [
                'name' => $item->category_name,
                'value' => (string)$item->category_id,
                'id' => $item->id ?? $item->category_id,
                'pid' => $item->pid ?? $item->category_super_id,
                'category_id' => $item->category_id,
                'category_name' => $item->category_name,
                'category_super_id' => $item->category_super_id,
                'category_status' => $item->category_status,
                'category_classify' => $item->category_classify,
                'category_type' => $item->category_type,
                'category_icon' => $item->category_icon,
                'category_images' => $item->category_images,
                'category_url' => $item->category_url,
                'category_page' => $item->category_page,
                'category_sort' => $item->category_sort,
                'category_groupby' => $item->category_groupby,
                'category_remark' => $item->category_remark,
                'category_extend_json' => $item->category_extend_json,
                'category_addtimes' => $item->category_addtimes,
            ];
        }
        $tree = new Tree($format_items);
        return json_success('success', $tree->getTree());
    }

    public function goodsCategory(Request $request)
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $format = 'tree';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'category_sort';
        $where['category_status'] = 'ACTIVED';
        $where['category_super_id'] = ['in', '31,154,5,181,30,70,42'];
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormatForGoods($query, $format, 1000);
        // $model->orWhereIn('category_id', ['31','154','5','181','30','70','42']);
    }

    /**
     * 执行真正查询，并返回格式化数据
     * @param $query
     * @param $format
     * @param $limit
     * @return Response
     */
    protected function doFormatForGoods($query, $format, $limit): Response
    {
        $methods = [
            'select' => 'formatSelect',
            'tree' => 'formatTree',
            'table_tree' => 'formatTableTree',
            'normal' => 'formatNormal',
        ];
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if (method_exists($this, "afterQuery")) {
            $items = call_user_func([$this, "afterQuery"], $items);
        }
        $super = SysCategory::whereIn('category_id', ['31', '154', '5', '181', '30', '70', '42']);
        $superPaginator = $super->paginate($limit);
        $superTotal = $superPaginator->total();
        $superItems = $superPaginator->items();

        $items = array_merge($items, $superItems);
        $total = $total + $superTotal;

        $format_function = $methods[$format] ?? 'formatNormal';
        return call_user_func([$this, $format_function], $items, $total);
    }

    /**
     * @Desc 分类详情
     * @Author Gorden
     * @Date 2024/2/22 11:37
     *
     * @param $id
     * @return \support\Response
     */
    public function categoryInfo($id)
    {
        return CategoryService::categoryInfo($id);
    }

    /**
     * @Desc 添加分类
     * @Author Gorden
     * @Date 2024/2/22 10:25
     *
     * @param Request $request
     * @return \support\Response
     */
    public function addCategory(Request $request)
    {
        $validate = new CategoryValidate();
        if (!$validate->scene('add')->check($request->post())) {
            return json_fail($validate->getError());
        }

        return CategoryService::insertCategory($request->post());
    }

    /**
     * @Desc 修改分类
     * @Author Gorden
     * @Date 2024/2/22 11:05
     *
     * @param $id
     * @param Request $request
     * @return \support\Response
     */
    public function updateCategory($id, Request $request)
    {
        $validate = new CategoryValidate();
        if (!$validate->scene('update')->check($request->post())) {
            return json_fail($validate->getError());
        }

        return CategoryService::updateCategory($id, $request->post());
    }

    /**
     * @Desc 修改分类状态
     * @Author Gorden
     * @Date 2024/2/22 11:49
     *
     * @param $id
     * @param Request $request
     * @return \support\Response
     */
    public function updateStatus($id, Request $request)
    {
        $validate = new CategoryValidate();
        if (!$validate->scene('update_status')->check($request->post())) {
            return json_fail($validate->getError());
        }

        return CategoryService::updateStatus($id, $request->post());
    }

    /**
     * @Desc 删除分类
     * @Author Gorden
     * @Date 2024/2/22 11:57
     *
     * @param $id
     * @return \support\Response
     */
    public function delCategory(Request $request)
    {
        return CategoryService::delCategory($request);
    }

    public function getCategoryTree(Request $request)
    {
        $category_id = $request->get('category_id');
        return CategoryService::getCategoryTree($category_id);
    }
}