<?php 

namespace App\Services; 

use App\OwnerReport;
use App\OwnerStoragePriceModel;

Class OwnerStoragePriceModelService
{ 
    public function getSelection(array $columns = ["counting_type","using_type"], array $withs = [])
    {
        return OwnerStoragePriceModel::query()->select($columns)->with($withs)->get();
    }

    public function paginate($id = null,array $withs = [])
    {
        $query = OwnerStoragePriceModel::query()->orderByDesc('id')->with($withs);
        if ($id)$query->where("id",$id);
        return $query->paginate($params["paginate"] ?? 50);
    }

    public function create(array $params)
    {
        return OwnerStoragePriceModel::query()->create($params);
    }

    public function update(array $params, array $values)
    {
        $query = OwnerStoragePriceModel::query();
        foreach ($params as $column => $value){
            $query->where($column,$value);
        }
        return $query->update($values);
    }

    public function find($id)
    {
        return OwnerStoragePriceModel::query()->find($id);
    }
    public function destroy($id)
    {
        return OwnerStoragePriceModel::destroy($id);
    }

    //暂时不考虑单位换算问题：后期可能存在多单位换算，此处仅视为单位为 m²
    public function calculationAmount(OwnerStoragePriceModel $model, $area, $owner_id = null, $month = null)
    {
        if (!$model || !$area) return 0;
        if ($area < $model->minimum_area) $area = $model->minimum_area;
        $money = $area*$model->price;
        switch ($model->discount_type){
            case "按单减免":
                if ($owner_id && $month){
                    $report = OwnerReport::query()->select("id","total")
                        ->where("owner_id",$owner_id)
                        ->where("counting_month","like",$month."%")->first();
                    $money -= $report ? ($report->total)*($model->discount_value) : 0;
                }
                break;
            case "固定减免":
                $money -= $model->discount_value;
                break;
        }
        return $money;
    }
}