<?php

namespace App\Services;

use App\Province;
use Illuminate\Support\Str;
use App\Traits\ServiceAppAop;


class ProvinceService
{
    use ServiceAppAop;
    protected $modelClass=Province::class;
    public static $provinces = ['青海','新疆','内蒙古','广西','西藏','宁夏','北京','上海','重庆','天津'];


    public function findByName($name)
    {
        if(!$name)return null;
        $province = Province::query()->where('name',$name)->first();
        if(isset($province))return $province;

        foreach (ProvinceService::$provinces as $province) {
            if(strstr($province,$name) != null || strstr($name,$province) != null){
                return Province::query()->where('name',$province)->first();
            }
        }
        if(str_ends_with($name,'市')){
            $province_name = Str::before($name,'市');
            return   Province::query()->where('name','like',$province_name.'%')->first();
        }
        if(str_ends_with($name,'省')){
            $province_name = Str::before($name,'省');
            return   Province::query()->where('name','like',$province_name.'%')->first();
        }
        return null;
    }

    public function first(array $params)
    {
        $query = Province::query();
        foreach ($params as $column=>$param){
            $query->where($column,$param);
        }
        return $query->first();
    }
}
