<?php

namespace App\Services;

use App\Unit;
use App\Traits\ServiceAppAop;
use Illuminate\Support\Facades\Cache;


class UnitService
{
    use ServiceAppAop;
    protected $modelClass=Unit::class;
    /*
     * array | string $column
     * 默认一些select字段,可传递string 或 array来指定select字段
     * */
    public function getSelection($column = ['id','name']){
        if (!is_array($column)) {
            $column = [$column];
        }
        return Unit::query()->orderBy("sequence")->select($column)->get();
    }

    /**
     * 设置/刷新 单位缓存
     */
    public function setUnitCache()
    {
        $units = Unit::query()->get();
        Cache::forever("units",$units);
    }

    /**
     * 获取单位缓存
     *
     * @return mixed
     */
    public function getUnitCache()
    {
        if (!Cache::has("units")){
            $units = Unit::query()->get();
            Cache::forever("units",$units);
        }
        return Cache::get("units");
    }

    /**
     * 获取单位集的映射
     *
     * @param null|array $targets
     *
     * @return array
     */
    public function getUnitMapping($targets = null)
    {
        return Cache::remember("unitMapping:".json_encode($targets,JSON_UNESCAPED_UNICODE),config("cache.expirations.rarelyChange"),function ()use($targets){
            $result = [];
            $units = $this->getUnitCache();
            if (!$units)return [];
            foreach ($units as $unit){
                if (!$targets)$result[$unit->id] = $unit->name;
                else if (array_search($unit->name,$targets)!==false)$result[$unit->id] = $unit->name;
            }
            return $result;
        });
    }

}
