<?php

namespace Modules\Configuration\Models;

use App\Models\Model;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;

class Configuration extends Model
{
    use Cachable;

    const TYPE_TEXT     = 'text';
    const TYPE_IMG      = 'image';
    const TYPE_SELECT   = 'select';
    const TYPE_CHECKBOX = 'checkbox';
    const TYPE_NUMBER   = 'number';
    const TYPE_RATE     = 'rate';
    const TYPES         = [
        self::TYPE_TEXT     => '文本',
        self::TYPE_IMG      => '图片',
        self::TYPE_SELECT   => '下拉列表',
        self::TYPE_CHECKBOX => '多选框',
        self::TYPE_NUMBER   => '数值',
        self::TYPE_RATE     => '比例',
    ];
    protected $casts = [
        'source' => 'json',
    ];

    /**
     * Notes   : 获取当前模块下的参数配置
     *
     * @Date   : 2021/12/1 13:18
     * @Author : Mr.wang
     * @param $module
     * @return mixed
     */
    public static function getModule($module)
    {
        return self::where('module', $module)
            ->get()
            ->pluck('paramsValue', 'keyValue');
    }

    /**
     * Notes   : 获取参数值
     *
     * @Date   : 2021/12/1 11:43
     * @Author : Mr.wang
     * @param  string  $key
     * @param  string  $default
     * @return string
     */
    public static function getValue(string $key = '', $default = ''): string
    {
        $config = self::where('keyValue', $key)->first();
        if (! $config) {
            return $default;
        }

        return $config->paramsValue ?? $default;

    }

    /**
     * Notes   : 获取参数
     *
     * @Date   : 2021/12/1 11:42
     * @Author : Mr.wang
     * @return string
     */
    public function getParamsTextAttribute(): string
    {
        if (in_array($this->type, [
            'select', 'checkbox', 'radio',
        ])) {
            return $this->source[$this->paramsValue] ?? '';
        } else {
            return $this->paramsValue ?? '';
        }
    }
}
