<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    /**
     * 创建活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {

        $id = $request->input('id');
        $name = $request->input('name');
        $info = $request->input('info');
        $classify = $request->input('classify');
        $color = $request->input('color');
        $price = $request->input('price');
        $status = $request->input('status');
        if ($id) {
            $product = Product::find($id);
            $product->status = $status;
        } else {
            $product = new Product;
            $product->status = 0;
            $product->collect_num = 0;
            $product->sell_num = 0;
        }
        if ($name && $info && $classify && $color) {
            $product->name = $name;
            $product->info = $info;
            $product->color = $color;
            $product->price = $price;
            $product->classify = $classify;
            $product->save();
            return Response()->json([
                "status" => 0,
                "message" => "保存成功!"
            ]);
        } else {
            return Response()->json([
                "status" => -1,
                "message" => "信息不能为空!"
            ]);
        }
    }

    /**
     * 每页20进行分页
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        $products = Product::all()->toArray();
        $datas = array_map(function ($product) {
            return [
                "id" => $product["id"],
                "classify" => $product["classify"],
                "name" => $product["name"],
                "price" => $product["price"],
                "photo" => $product["photo"]
            ];
        }, $products);

        $data = [];
        foreach ($datas as $d) {
            if(!array_key_exists($d["classify"], $data)) {
                $data[$d["classify"]] = [];
            }
            array_push($data[$d["classify"]], $d);
        }
        return response()->json([
            "status" => 0,
            "data" => $data
        ]);
    }

}
