<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/8
 * Time: 12:20
 */
namespace Modules\Project\Tranaformers;

use Modules\Project\Entities\Goods;

class GoodsTransformer extends BaseTransformer
{
    protected $is_list;

    public function is_list($flag)
    {
        $this->is_list = $flag;

        return $this;
    }

    protected $availableIncludes = ['spec','goodsList'];

    /**
     * @OA\Schema(
     *     description="商品",
     *     type="object",
     *     schema="Goods",
     *     @OA\Property(property="id", type="integer", description="ID"),
     *     @OA\Property(property="title", type="string", description="标题"),
     *     @OA\Property(property="cover_picture", type="string", description="封面图"),
     *     @OA\Property(property="pictures", type="array", @OA\Items(), description="图片"),
     *     @OA\Property(property="spec_param", type="string",description="商品规格"),
     *     @OA\Property(property="market_price", type="string", description="市场价"),
     *     @OA\Property(property="selling_price", type="string", description="售价"),
     *     @OA\Property(property="goods_stock", type="string", description="库存"),
     *     @OA\Property(property="goods_sale", type="string", description="已销售数量"),
     *     @OA\Property(property="description", type="string", description="商品详情"),
     *     @OA\Property(property="favorited", type="integer", description="是否已收藏"),
     *     @OA\Property(property="created_at", type="string", description="注册时间"),
     *     @OA\Property(property="updated_at", type="string", description="更新时间")
     * )
     */
    public function transform(Goods $table)
    {
        $spec_param = json_decode($table->spec_param, true);

        unset($spec_param['products']);

        unset($spec_param['all_spec']);

        $user = \Auth::guard('api')->user();

        return [
            'id' => $table->id,
            'title' => $table->title,
            'spec_param' => $this->is_list ? null : $spec_param,
            'market_price' => $table->market_price,
            'cover_picture' => $table->cover_picture,
            'pictures' => $this->is_list ? null : $table->pictures,
            'selling_price' => $table->selling_price,
            'goods_stock' => $table->goods_stock,
            'goods_sale' => $table->goods_sale,
            'description' => $this->is_list ? null : $table->description,
            'favorited' => $user ? ($table->isFavoritedBy($user) ? 1 : 0) : 0,
            'created_at' => $table->created_at->toDateTimeString(),
            'updated_at' => $table->updated_at->toDateTimeString(),
        ];
    }

    public function includeGoodsList(Goods $table)
    {
        return $this->collection($table->goodsList, new GoodsListTransformer());
    }

    public function includeSpec(Goods $table)
    {
        return $this->item($table->spec, new GoodsSpecTransformer());
    }
}
