<?php 

namespace App\Services;

use App\CommodityBarcode;
use App\DeliveryAppointmentDetail;
use App\Services\common\QueryService;
use App\Traits\ServiceAppAop;
use App\DeliveryAppointment;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use phpDocumentor\Reflection\Types\Integer;

class DeliveryAppointmentService
{
    use ServiceAppAop;
    protected $modelClass=DeliveryAppointment::class;

    /**
     * 搜索QUERY
     *
     * @param array $params
     *
     * @return Builder
     */
    public function query(array $params)
    {
        $owners = app("UserService")->getPermittingOwnerIds(Auth::user());
        return app(QueryService::class)->query($params,DeliveryAppointment::query(),[
            'created_at_start' => ['alias' => 'created_at' , 'startDate' => ' 00:00:00'],
            'appointment_date_start' => ['alias' => 'appointment_date' , 'startDate' => ' 00:00:00'],
            'created_at_end' => ['alias' => 'created_at' , 'endDate' => ' 23:59:59'],
            'appointment_date_end' => ['alias' => 'appointment_date' , 'endDate' => ' 23:59:59'],
            "owner_id"=>['multi' => ','],
            "id"=>['multi' => ','],
        ])->orderByDesc("id")->whereIn("owner_id",$owners)->with(["cars.car","details.commodity.barcodes"]);
    }

    /**
     * 根据吨，立方，SKU减产系数计算产能
     *
     * @param double $tonne
     * @param double $cubicMeter
     * @param int $amount
     * @param int $rpcc reduced_production_capacity_coefficient
     *
     * @return double
     */
    public function calculateCapacity($tonne, $cubicMeter, $amount, $rpcc)
    {
        $need = max(($tonne*config("appointment.production_capacity.tonne")),
            ($cubicMeter*config("appointment.production_capacity.cubic_meter")));
        $coefficient = config("appointment.production_capacity.coefficient");
        if ($amount && ($need/$amount < $coefficient)){
            $need *= 1+(($coefficient-($need/$amount))*($rpcc/100));
        }
        return $need;
    }

    /**
     * 根据提供的详情数组插入详情
     *
     * @param DeliveryAppointment|object $parent
     * @param array $details
     * @param string $name
     * @param string $amount
     * @param string $barCode
     */
    public function insertDetails($parent, array $details, $name="name", $amount="amount", $barCode="bar_code")
    {
        $codes = [];
        $names = [];
        $insert = [];//插入的元素
        foreach ($details as $index=>$detail){
            if (isset($detail["commodity_id"]) && $detail["commodity_id"]){
                $insert[] = [
                    "delivery_appointment_id" => $parent->id,
                    "commodity_id"            => $detail["commodity_id"],
                    "bar_code"                => null,
                    "name"                    => null,
                    "amount"                  => $detail[$amount],
                ];
                unset($details[$index]);continue;
            }
            if ($detail[$barCode])$codes[] = $detail[$barCode];
            else $names[] = $detail[$name];
        }
        $map = [];//存储条码与ID的映射
        if ($codes || $names){
            CommodityBarcode::query()->with("commodity")->whereHas("commodity",function ($query)use($parent){
                /** @var Builder $query */
                $query->where("owner_id",$parent->owner_id);
            })->whereIn("code",$codes)->orWhereHas("commodity",function ($query)use($names){
                /** @var Builder $query */
                $query->whereIn("name",$names);
            })->get()->each(function ($commodity)use(&$map){
                $map[$commodity->code] = $commodity->commodity_id;
                $map[$commodity->commodity->name] = $commodity->commodity_id;
            });
        }
        foreach ($details as $detail){
            $code = $detail[$barCode];
            $insert[] = [
                "delivery_appointment_id" => $parent->id,
                "commodity_id"            => $code ? ($map[$code] ?? null) : ($map[$detail[$name]] ?? null),
                "bar_code"                => $code,
                "name"                    => $detail[$name],
                "amount"                  => $detail[$amount],
            ];
        }
        if ($insert)DeliveryAppointmentDetail::query()->insert($insert);
    }

    /**
     * 获取一个KEY值用于验证二维码 21-4-2 切换为永久二维码
     *
     * @return string
     */
    public function getKey()
    {
        $y = 'w';//date("y");
        $m = 'a';//date("m");
        $d = 's';//date("d");
        $k1 = substr(env("APP_KEY"),7,2);
        $k2 = substr(env("APP_KEY"),10,2);
        $k3 = substr(env("APP_KEY"),15,2);
        return md5($k3.$y.$k2.$m.$k1.$d);
    }

    /**
     * 验证key值
     *
     * @param string $key
     * @return bool
     */
    public function checkKey(string $key):bool
    {
        if ($key!=$this->getKey())return false;
        return true;
    }

    /**
     * 获取当前时段
     *
     * @param int|null $hour
     *
     * @return int|bool
     */
    public function getPeriod($hour=null)
    {
        if (!$hour)$hour = date("H");
        foreach (DeliveryAppointment::PERIOD as $key=>$period){
            $arr = explode("-",$period);
            if (count($arr)!=2)continue;
            if ($hour>=$arr[0] && $hour<$arr[1])return $key;
        }
        return false;
    }

    /**
     * 验证预约单完整性修改状态
     *
     * @param integer $id
     */
    public function checkFull($id)
    {
        /** @var DeliveryAppointment|\stdClass $delivery */
        $delivery = DeliveryAppointment::query()->withCount(["cars"=>function($query){
            /** @var Builder $query */
            $query->whereNull("delivery_time")->where("status","!=",2);
        }])->find($id);
        if ($delivery->cars_count == 0)$delivery->update(["status"=>2]);
    }
}