<?php
namespace Modules\Project\Services\Order\Goods;

use Modules\Project\Entities\Goods;
use Modules\Project\Entities\GoodsList;
use Modules\Project\Services\Order\Transport\TransportRow;

class GoodsRow
{
    private $model;

    private $spec_model;

    private $spec;

    private $qty = 0;

    private $id;

    private $uuid;

    public function __construct($data)
    {
        $this->id = $data['id'];
        $this->spec = isset($data['spec'])?$data['spec']:[];
        $this->qty = $data['qty'];
    }

    /**
     * @return Goods
     */
    public function model()
    {
        if (!$this->model) {
            $this->model = (new Goods())->find($this->id);
        }

        return $this->model;
    }

    /**
     * 运费
     */
    public function freight()
    {
        return new TransportRow($this->model(), $this->qty);
    }

    /**
     * 价格
     */
    public function total()
    {
        return bcmul($this->selling_price(), $this->qty, 2);
    }

    public function qty()
    {
        return $this->qty;
    }

    public function spec()
    {
        return $this->spec;
    }

    /**
     * 获取售价
     */
    public function selling_price()
    {
        return $this->model()->selling_price;
    }

    /**
     * @return GoodsList
     */
    private function specGoods()
    {
        if (!$this->spec_model) {
            $this->model()->with([

                'goodsList' => function ($query) {
                    $query->where('uuid', $this->uuid());
                },

            ]);

            if ($this->model()->goodsList->toArray()) {
                $this->spec_model = $this->model()->goodsList[0];
            } else {
                throw \Illuminate\Validation\ValidationException::withMessages([
                    'goods.*.spec' => ['商品规格有误'],
                ]);
            }
        }

        return $this->spec_model;
    }

    /**
     * 累加
     *
     * @param $qty
     */
    public function increase($qty)
    {
        $this->qty = $this->qty + $qty ;
    }

    public function uuid()
    {
        if (!$this->uuid) {
            $this->uuid = $this->getSpecUuid();
        }

        return $this->uuid;
    }

    /**
     * 获取规格的uuid 不会随规格排序改变
     *
     * @param array  $spec
     * @param string $id
     *
     * @return string
     */
    protected function getSpecUuid()
    {
        $spec = $this->spec;

        foreach ($spec as &$v) {
            ksort($v);

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

        sort($spec);

        return md5($this->id.json_encode($spec));
    }
}
