<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    use HasFactory;

    protected $table = 'base_settings';

    //todo 对数据库做简单的封装 get和set(管理端会用到)  加缓存
    /**
     * @param String $tags
     * @param String $key
     * @param String $default
     * @return array|String
     */
    public static function get(string $tags, string $key = '', bool $is_string = false)
    {
        if($tags){
          $map[] = ['tags','=',$tags];
        }
        if($key){
          $map[] = ['key','=',$key];
        }
        $map[] = ['is_delete','=',0];
        if($is_string){
          $list = self::where($map)->select('title', 'key', 'value','tags')->get();
          $settings = [];
          foreach($list as $key=>&$val){
            $settings[$val['tags']][] = $val;
          }
        }else{
          $list = self::where($map)->select('title', 'key', 'value','tags')->get()->toArray();
          $settings = [];
          foreach($list as $key=>&$val){
            $val['value'] = json_decode($val['value']);
            $settings[$val['tags']][] = $val;
          }
        }
        return $settings;
    }

    /**
     * @param String $tags
     * @param String $key
     * @param String $value
     * @return int
     */
    public static function set(string $tags, string $key, string $value)
    {
        return self::where([['tags', $tags], ['key', $key]])->update(['value' => $value]);
    }
}
