<?php

namespace App\Services;

use App\OwnerAreaReport;
use App\OwnerBillReport;
use App\Services\common\QueryService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Traits\ServiceAppAop;


class OwnerAreaReportService
{
    use ServiceAppAop;
    protected $modelClass=OwnerAreaReport::class;
    /**
     * @param Builder $builder
     * @param array $params
     * @return Builder
     */
    private function query(Builder $builder, array $params)
    {
        $columnQueryRules = [
            'counting_month_start' => ['alias' => 'counting_month', 'startDate' => '-01'],
            'counting_month_end' => ['alias' => 'counting_month', 'endDate' => '-31'],
            'owner_id' => ['multi' => ','],
        ];
        if ($params["customer_id"] ?? false){
            $builder->whereHas('owner',function ($query)use(&$params){
                /** @var Builder $query*/
                $query->where("customer_id",$params["customer_id"]);
                unset($params["customer_id"]);
            });
        }
        return app(QueryService::class)->query($params, $builder, $columnQueryRules);
    }

    public function paginate(array $params, array $withs = null)
    {
        $areas = OwnerAreaReport::query()->whereIn("owner_id",Auth::user()['permittingOwnerIds'])->orderByDesc('id');
        if ($withs)$areas->with($withs);
        return $this->query($areas,$params)->paginate($params["paginate"] ?? 50);
    }


    /**
     * 面积变更会去对比账单更新账单 考虑到后续账单变更有多种渠道此处加排他锁
     *
     * @param array $params
     * @param array $values
     * @return bool|string
     */
    public function update(array $params, array $values)
    {
        DB::beginTransaction();
        $area = $this->query(OwnerAreaReport::query(),$params)->with("ownerStoragePriceModel")->lockForUpdate()->first();
        try{
            if ($values["accounting_area"] ?? null && $area->accounting_area != $values["accounting_area"]){
                $report = OwnerBillReport::query()->lockForUpdate()->where("owner_id",$area->owner_id)
                    ->where("counting_month",'like',$area->counting_month."%")->first();
                if ($report){
                    if (!$area->ownerStoragePriceModel)return false;
                    $storeFee = app("OwnerStoragePriceModelService")->calculationAmount($area->ownerStoragePriceModel, $values["accounting_area"], $area->owner_id, $area->counting_month);
                    $up = ["storage_fee"=>$storeFee];
                    if ($report->confirm_fee !== null || $report->confirmed == '是'){
                        $initial = $report->work_fee + $report->logistic_fee + $storeFee;
                        $up["difference"] = $initial - $report->confirm_fee;
                    }
                    $report->update($up);
                }
            }
            $area->update($values);
            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            return $e->getMessage();
        }
    }

    public function get(array $params, array $withs = null)
    {
        $query = OwnerAreaReport::query()->orderByDesc('id');
        if ($withs)$query->with($withs);
        return $this->query($query,$params)->get();
    }

    //锁定面积
    public function lockArea($id = null, $ownerId = null, $countingMonth = null)
    {
        if (!$id && !$ownerId && !$countingMonth)return false;
        $query = OwnerAreaReport::query()->where("status","编辑中");
        if ($id)$query->where("id",$id);
        if ($ownerId)$query->where("owner_id",$ownerId);
        if ($countingMonth)$query->where("counting_month","like",$countingMonth."%");
        return $query->update(["status"=>"已完成"]);
    }

    //根据货主生成盘点面积记录
    public function notExistToInsert($owners)
    {
        if (!$owners)return;
        $reports = OwnerAreaReport::query()
            ->where("counting_month",">=",date("Y-m")."-01")
            ->whereIn("owner_id",array_column(is_array($owners) ? $owners : $owners->toArray(),"id"))->get();
        $sign = [];
        foreach ($reports as $report)$sign[$report->owner_id."_".$report->owner_storage_price_model_id] = true;
        $month = date('Y-m-d');
        $date = date('Y-m-d H:i:s');
        $createOwnerAreaReport = [];
        foreach ($owners as $owner){
            if (!$owner->ownerStoragePriceModels)continue;
            foreach ($owner->ownerStoragePriceModels as $model){
                $key = $owner->id."_".$model->id;
                if (!isset($sign[$key])) $createOwnerAreaReport[] = [
                    "owner_id"              => $owner->id,
                    "counting_month"        => $month,
                    "user_owner_group_id"   => $owner->user_owner_group_id,
                    "created_at"            => $date,
                    "owner_storage_price_model_id"  => $model->id,
                ];
            }
        }
        if ($createOwnerAreaReport){
            DB::table("owner_area_reports")->insert($createOwnerAreaReport);
            LogService::log(__METHOD__,"项目管理-生成盘点记录",json_encode($createOwnerAreaReport));
        }
    }
}
