<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Schema\Blueprint;
use Schema;

class Log extends Model
{

    protected $guarded;

    protected $table;

    protected $casts = [
        'in_source'  => 'array',
        'out_source' => 'array',
    ];

    const TYPE_FREEZECOUPON = 'freezecoupon';
    const TYPE_DESTROY      = 'destroy';
    const TYPE_QUERY        = 'query';
    const TYPE_GRANT        = 'grant';
    const TYPES             = [
        self::TYPE_FREEZECOUPON => '核销',
        self::TYPE_DESTROY      => '作废',
        self::TYPE_QUERY        => '查询',
        self::TYPE_GRANT        => '发券',
    ];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        if (! $this->table) {
            $this->table = 'api_log_'.date('Ym');
        }

        if (! Schema::hasTable($this->table)) {
            Schema::create($this->table, function (Blueprint $table) {
                $table->increments('id');
                $table->string('path', 255);
                $table->string('method', 15)->index();
                $table->text('in_source');
                $table->string('type', 20)->index();
                $table->text('out_source')->nullable();
                $table->timestamps();
            });
        }
    }

    public function setTable($table)
    {
        if (Schema::hasTable($table)) {
            $this->table = $table;

            return $this;
        }

    }

    /**
     * 为数组 / JSON 序列化准备日期。
     *
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    /**
     * Notes: 关联优惠券-成功
     *
     * @Author: 玄尘
     * @Date: 2022/1/19 11:24
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function coupon(): HasOne
    {
        return $this->hasOne(Coupon::class, 'redemptionCode', 'coupon_no')->where('status', 2);
    }

    /**
     * Notes: 关联优惠券
     *
     * @Author: 玄尘
     * @Date: 2022/1/19 13:12
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function coupons(): HasMany
    {
        return $this->hasMany(Coupon::class, 'redemptionCode', 'coupon_no');
    }
}
