<?php

namespace App\Services;

use App\Order;
use App\Owner;
use App\OwnerReport;
use App\OwnerStoragePriceModel;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use App\Traits\ServiceAppAop;


class OwnerStoragePriceModelService
{
    use ServiceAppAop;
    protected $modelClass=OwnerStoragePriceModel::class;
    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)
    {
        $params["operation"] = "C";
        return OwnerStoragePriceModel::query()->create($params);
    }

    /**
     * 拷贝目标数据
     *
     * @param object|int $model
     * @param array $values
     * @param array|null $owners
     *
     * @return object|null
     */
    public function copy($model, $values = [], $owners = null)
    {
        if (is_integer($model))$model = OwnerStoragePriceModel::query()->find($model);
        if (!$model)return null;
        $values["operation"] = "U";
        $values["target_id"] = $model->id;
        foreach ($model->getFillable() as $column){
            if (!array_key_exists($column,$values))$values[$column] = $model[$column];
        }
        if ($owners===null){
            $query = DB::raw("SELECT * FROM owner_storage_price_model_owner WHERE owner_storage_price_model_id = {$model->id}");
            $owners = array_column(DB::select($query),"owner_id");
        }
        /** @var OwnerStoragePriceModel $model */
        $model = OwnerStoragePriceModel::query()->create($values);
        $model->owners()->sync($owners);
        return $model;
    }

    /**
     * 审核或恢复目标集
     *
     * @param bool $isAudit
     * @param integer|null|array $ownerId
     * @param integer|null|array $ids
     */
    public function auditOrRecover($isAudit = true, $ownerId = null, $ids = null)
    {
        if (!$ownerId && !$ids)return;
        $result = app(QueryService::class)->priceModelAuditOrRecoverQuery($isAudit,OwnerStoragePriceModel::query(),$ownerId,$ids);
        if ($result["delete"])$this->destroy($result["delete"]);
        if ($result["update"])OwnerStoragePriceModel::query()->whereIn("id",$result["update"])->update(["operation"=>null,"target_id"=>null]);
    }

    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, $withs = [])
    {
        return OwnerStoragePriceModel::query()->with($withs)->find($id);
    }
    public function destroy($id)
    {
        $sql = "SELECT * FROM owner_storage_price_model_owner WHERE owner_storage_price_model_id ";
        if (is_array($id)){
            $query = "IN (";
            for ($i=0;$i<count($id)-1;$i++)$query .= "?,";
            $query .= "?)";
        }else{
            $query = "= ?";
            $id = [$id];
        }
        $owners = array_column(DB::select(DB::raw($sql.$query),$id),"owner_id");
        DB::delete(DB::raw("DELETE FROM owner_storage_price_model_owner WHERE owner_storage_price_model_id ".$query),$id);
        app("OwnerService")->refreshRelevance($owners,0,true);

        return OwnerStoragePriceModel::destroy($id);
    }

    //暂时不考虑单位换算问题：后期可能存在多单位换算，此处仅视为单位为 m²,m³
    public function calculationAmount(OwnerStoragePriceModel $model, $area, $owner_id = null, $month = null)
    {
        /** @var \stdClass $model */
        if (!$model || !$area || $model->operation) return array(0,null);
        if ($area < $model->minimum_area) $area = $model->minimum_area;
        switch ($model->discount_type){
            case "按单减免":
                if ($owner_id && $month){
                    if ($model->timeUnit->name == '月'){
                        $report = OwnerReport::query()->select("id",DB::raw("(to_business_quantity+to_customer_quantity) AS total"))
                            ->where("owner_id",$owner_id)
                            ->where("counting_month","like",$month."%")->first();
                        if ($report && $report->total>=0)$area -= floor($report->total/$model->discount_value);
                    }else{
                        $days = date('t', strtotime($month."-01"));
                        $area *= $days;
                        $logistics = app("OwnerPriceExpressService")->getBuildLogistic($owner_id);
                        $logisticSql = "(''";
                        foreach ($logistics as $logistic)$logisticSql.=",".$logistic;
                        $logisticSql .= ")";
                        for($i=1;$i<=$days;$i++){
                            $d = $i<10 ? "0".$i : $i;
                            $query = DB::raw("SELECT COUNT(1) c FROM orders WHERE logistic_id IN {$logisticSql} AND wms_status = ? AND wms_edittime BETWEEN ? AND ?");
                            $count = DB::selectOne($query,['订单完成',$month."-".$d." 00:00:00",$month."-".$d." 23:59:59"]);
                            if ($count && $count->c>=0)$area -= floor($count->c/$model->discount_value);
                        }
                    }
                }
                break;
            case "固定减免":
                if ($model->timeUnit->name == '月'){
                    $area -= $model->discount_value;
                }else{
                    $days = date('t', strtotime($month."-01"));
                    $area *= $days;
                    $area -= $days*$model->discount_value;
                }
                break;
        }
        $index = 0;
        if ($model->amount_interval){
            $total = app("OrderService")->getOrderQuantity($owner_id);
            for ($i=count($model->amount_interval);$i<0;$i--){
                if ($total>=$model->amount_interval[$i])$model->price = $index;
            }
        }
        $money = $area>0 ? $area*$model->price[$index] : 0;
        if ($model->taxRate)$taxFee = $money * ($model->taxRate->value/100);
        else{
            /** @var Owner|\stdClass $owner */
            $owner = new Owner();
            $owner->id = $owner_id;
            $owner->load("taxRate");
            if ($owner->taxRate)$taxFee = $money * ($owner->taxRate->value/100);
            else $taxFee = null;
        }
        return array($money,$taxFee);
    }
}
