<?php

namespace Modules\Payment\Models;

use App\Models\Model;
use Exception;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;

class Setting extends Model
{

    use Cachable,
        SoftDeletes;

    protected $table = 'payment_settings';

    protected $casts = [
        'in_use' => 'boolean',
    ];

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

        self::saved(function ($model) {
            if ($model->in_use && $model->id) {
                self::where('id', '<>', $model->id)
                    ->where('in_use', 1)
                    ->update(['in_use' => 0]);
            }

//            Cache::tags('payment_config')->flush();
        });
    }

    /**
     * Notes   : 挂载的微信支付
     *
     * @Date   : 2021/5/26 2:01 下午
     * @Author : < Jason.C >
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function wechat(): BelongsTo
    {
        return $this->belongsTo(Wechat::class);
    }

    /**
     * Notes   : 挂载的支付宝
     *
     * @Date   : 2021/5/26 2:18 下午
     * @Author : < Jason.C >
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function alipay(): BelongsTo
    {
        return $this->belongsTo(Alipay::class);
    }

    /**
     * Notes   : 获取微信/支付宝的配置
     *
     * @Date   : 2021/5/26 2:19 下午
     * @Author : < Jason.C >
     * @param  string  $type
     * @return array
     * @throws \Exception
     */
    public static function getDefaultConfig(string $type): array
    {
        if (! in_array($type, ['wechat', 'alipay'])) {
            throw new Exception('不支持的支付渠道');
        }

        $setting = self::orderByDesc('in_use')->first();

        return $setting->$type->toConfig();
    }

}