<?php

namespace App\Http\Controllers;

use App\Components\AsyncResponse;
use App\OrderFreeze;

class OrderFreezeController extends Controller
{
    use AsyncResponse;
    public function index()
    {
        $this->gate("订单管理-自动冻结");
        $freezes = OrderFreeze::query()->with(["logistic:id,name","province:id,name","city:id,name","district:id,name","town:id,name","street:id,name"])
            ->orderByDesc("id")->where("status",0)
            ->paginate(request("paginate") ?? 50);
        return view("order.index.freeze",compact("freezes"));
    }

    public function store()
    {
        $this->gate("订单管理-自动冻结");
        $freeze = OrderFreeze::query()->where("logistic_id",request("logistic_id"))->where("status",0);
        if (request("province_id"))$freeze->where("province_id",request("province_id"));
        else $freeze->whereNull("province_id");

        if (request("city_id"))$freeze->where("city_id",request("city_id"));
        else $freeze->whereNull("city_id");

        if (request("district_id"))$freeze->where("district_id",request("district_id"));
        else $freeze->whereNull("district_id");

        if (request("town_id"))$freeze->where("town_id",request("town_id"));
        else $freeze->whereNull("town_id");

        if (request("street_id"))$freeze->where("street_id",request("street_id"));
        else $freeze->whereNull("street_id");

        if (request("thawed_at"))$freeze->where("thawed_at",request("thawed_at"));
        else $freeze->whereNull("thawed_at");

        $freeze = $freeze->first();
        if ($freeze && $freeze->id!=request("id"))$this->error("已存在冻结选项，无需重复录入");
        $obj = [
            "logistic_id"   => request("logistic_id"),
            "province_id"   => request("province_id"),
            "city_id"       => request("city_id"),
            "district_id"   => request("district_id"),
            "town_id"       => request("town_id"),
            "street_id"     => request("street_id"),
            "thawed_at"     => request("thawed_at"),
        ];
        if (request("id")){
            $freeze = OrderFreeze::query()->find(request("id"));
            $freeze->update($obj);
        }else $freeze = OrderFreeze::query()->create($obj);
        app("OrderFreezeService")->refreshFreezes();
        $freeze->load(["logistic:id,name","province:id,name","city:id,name","district:id,name","town:id,name","street:id,name"]);
        $this->success($freeze);
    }

    public function delFreeze()
    {
        $this->gate("订单管理-自动冻结");
        if (!request("id"))$this->error("非法参数");
        OrderFreeze::query()->where("id",request("id"))->update(["status"=>1]);
        app("OrderFreezeService")->refreshFreezes();
        $this->success();
    }
}
