<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/13
 * Time: 9:53
 */
namespace Modules\Project\Services;

use Modules\Project\Entities\Goods;
use Modules\Project\Entities\GoodsList;

class GoodsService extends BaseService
{
    /**
     * 获取规格的uuid 不会随规格排序改变
     *
     * @param array  $spec
     * @param string $id
     *
     * @return string
     */
    public static function getSpecUuid($goods_id, $spec = [])
    {
        foreach ($spec as &$v) {
            ksort($v);

            $v = md5(json_encode($v));
        }

        sort($spec);

        return md5($goods_id.json_encode($spec));
    }

    /**
     * 入库
     */
    public static function stockpiling($goods_id, $spec, $num = 1)
    {
        //$uuid = self::getSpecUuid($goods_id, $spec);

        //$info = GoodsList::where('uuid', $uuid)->where('goods_id', $goods_id)->get()->first();

        $info = Goods::find($goods_id);

        if ($info) {
            $info->increment('goods_stock', $num);

            if ($info->goods_sale >= $num) {
                $info->decrement('goods_sale', $num);
            }

            /*
            $info->goods->increment('goods_stock', $num);

            if ($info->goods->goods_sale >= $num) {
                $info->goods->decrement('goods_sale', $num);
            }
            */
        } else {
            throw new \Exception('未找到此规格');
        }

        return $info;
    }

    /**
     * 卖出
     */
    public static function sellOut($goods_id, $spec, $num = 1)
    {
        //$uuid = self::getSpecUuid($goods_id, $spec);

        //$info = GoodsList::where('uuid', $uuid)->where('goods_id', $goods_id)->get()->first();

        $info = Goods::find($goods_id);

        if ($info && $info->goods_stock >= $num) {
            $info->decrement('goods_stock', $num);

            $info->increment('goods_sale', $num);

            //$info->goods->decrement('goods_stock', $num);

            //$info->goods->increment('goods_sale', $num);
        } else {
            throw new \Exception('库存不足');
        }

        return $info;
    }
}
