<?php

namespace Modules\Project\Entities;

use Illuminate\Database\Eloquent\Model;
use Modules\Base\Entities\User;
use SMG\Address\HaveAddress;

class Order extends Model
{
    use HaveAddress;

    protected $with = ['orderGoods','orderGoods.goods'];

    /**
     * 默认 待支付
     */
    const STATUS_DEFAULT = 1;

    /**
     * 已取消
     */
    const STATUS_CANCEL = 2;

    /**
     * 已支付
     */
    const STATUS_PAID = 3;

    /**
     * 已发货
     */
    const STATUS_SHIPPED = 4;

    /**
     * 已确认(收货)
     */
    const STATUS_CONFIRM = 5;

    /**
     * 已完成
     */
    const STATUS_COMPLETE = 6;

    protected $fillable = [
        'order_no','user_id', 'goods_price', 'discount_amount', 'payable_amount', 'paid_amount', 'status', 'remarks','expires_at','express_id','tracking_no','freight','shipped_at',
    ];

    public function orderGoods()
    {
        return $this->hasMany(OrderGoods::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function express()
    {
        return $this->belongsTo(Express::class);
    }

    public function log()
    {
        return $this->hasMany(OrderLog::class);
    }

    public function addLog($data)
    {
        $this->log()->create(
            [
                'before_status' => $data['before_status'],
                'after_status' => $data['after_status'],
                'remarks' => isset($data['remarks']) ? $data['remarks'] : null,
                'extend' => isset($data['extend']) ? $data['extend'] : null,
            ]
        );

        return $this;
    }

    public function getCoverPictureAttribute()
    {
        $orderGoods = $this->orderGoods;

        if ($orderGoods && $orderGoods[0]) {
            return $orderGoods[0]->goods ? $orderGoods[0]->goods->cover_picture : '';
        } else {
            return '';
        }
    }
}
