<?php

namespace Modules\Project\Entities;

use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelFollow\Traits\CanBeFavorited;
use SMG\Categories\Traits\Categorizable;
use SMG\Support\ModelAttribute\HaveAttribute;

class Goods extends Model
{
    protected static $category_types = ['category','brand'];

    use Categorizable, CanBeFavorited, HaveAttribute;

    protected function fillableFromArray(array $attributes)
    {
        foreach (array_diff_key($attributes, array_flip($this->getFillable())) as $key => $value) {
            if ($this->isCategoryAttribute($key)) {
                $this->setCategoryAttribute($key, $value);
            }
        }

        foreach (array_diff_key($attributes, array_flip($this->getFillable())) as $key => $value) {
            if ($key == 'attr') {
                $this->setAttr($value);
            }
        }

        return $attributes;
    }

    public function setAttribute($key, $value)
    {
        if ($this->isCategoryAttribute($key)) {
            return $this->setCategoryAttribute($key, $value);
        } elseif ($key == 'attr') {
            return $this->setAttr($value);
        } else {
            return parent::setAttribute($key, $value);
        }
    }

    public function setHotAttribute($value)
    {
        if( $value == 'off' ||  $value == '0')
            $this->attributes['hot'] = 0;
        else
            $this->attributes['hot'] = 1;
    }

    public function setFineAttribute($value)
    {
        if( $value == 'off' ||  $value == '0')
            $this->attributes['fine'] = 0;
        else
            $this->attributes['fine'] = 1;
    }

    protected $with = ['goodsList'];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('sort', function ($builder) {
            $builder->orderBy('sort', 'ASC');
        });
    }

    //
    public function setPicturesAttribute($pictures)
    {
        if (is_array($pictures)) {
            $this->attributes['pictures'] = json_encode($pictures);
        }
    }

    public function getPicturesAttribute()
    {
        return json_decode($this->attributes['pictures'], true);
    }

    public function setTransportValueAttribute($data)
    {
        if (is_array($data)) {
            $this->attributes['transport_value'] = json_encode($data);
        }
    }

    public function getTransportValueAttribute()
    {
        $res = json_decode($this->attributes['transport_value'], true);

        return $res ? $res : [];
    }

    /**
     * 规格
     */
    public function spec()
    {
        return $this->belongsTo(GoodsSpec::class);
    }

    /**
     * 商品列表
     */
    public function goodsList()
    {
        return $this->hasMany(GoodsList::class);
    }

    public function getFirstPictureAttribute()
    {
        if ($this->pictures) {
            return $this->pictures[0];
        }

        return '';
    }
}
