<?php 

namespace App\Services; 

use App\OwnerInStorageRule;
use App\OwnerOutStorageRule;
use App\OwnerPriceOperation;
use App\Services\common\QueryService;
use App\Unit;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

Class OwnerPriceOperationService
{
    /**
     * @param Builder $builder
     * @param array $params
     * @return Builder
     */
    private function query(Builder $builder, array $params)
    {
        if ($params["owner_id"] ?? false){
            $ids = $this->ownerGetIds($params["owner_id"]);
            if ($ids)$builder->whereIn("id",$ids);
            unset($params["owner_id"]);
        }
        $columnQueryRules = [
            "name" => ["like"=>""]
        ];
        return app(QueryService::class)->query($params, $builder, $columnQueryRules);
    }

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


    private function ownerGetIds(string $owner_id)
    {
        if (!$owner_id)return [];
        $arr = DB::select(DB::raw("SELECT owner_price_operation_id AS id FROM owner_price_operation_owner WHERE owner_id in (".$owner_id.")"));
        return array_column($arr,"id");
    }

    public function destroy($id)
    {
        OwnerOutStorageRule::query()->where("owner_price_operation_id",$id)->delete();
        OwnerInStorageRule::query()->where("owner_price_operation_id",$id)->delete();
        DB::table("owner_price_operation_owner")->where("owner_price_operation_id",$id)->delete();
        return OwnerPriceOperation::destroy($id);
    }

    /**
     * @param array $params
     * @return Model
     */
    public function create(array $params)
    {
        return OwnerPriceOperation::query()->create($params);
    }

    public function insertRule(array $params, $type = '出库')
    {
        if ($type == '出库')OwnerOutStorageRule::query()->insert($params);
        else OwnerInStorageRule::query()->insert($params);
    }

    public function find($id, $isGetRule = false, $withs = [])
    {
        $query = OwnerPriceOperation::query()->with($withs)->find($id);
        if ($isGetRule){
            if ($query->operation_type == '入库'){
                $query->load("ownerInStorageRule");
                $query->rules = $query->ownerInStorageRule ? json_encode([$query->ownerInStorageRule]) : null;
            }else{
                $query->load("ownerOutStorageRules");
                $query->rules = json_encode($query->ownerOutStorageRules);
            }
        }
        return $query;
    }

    public function destroyRule($id, $type)
    {
        if ($type=="入库")OwnerInStorageRule::query()->where("owner_price_operation_id",$id)->delete();
        else OwnerOutStorageRule::query()->where("owner_price_operation_id",$id)->delete();
    }

    public function findUpdate(OwnerPriceOperation $model, array $params)
    {
        return $model->update($params);
    }

    /** 参数顺序： 数量 匹配对象 列映射 货主ID 单位ID 类型 SKU .
     *  匹配顺序： 类型 货主 策略 单位 特征                    ..多对多匹配规则废弃，1对1，设单位必定为件,对应规则必然只有一项存在
     *  单位匹配： 件，箱，单 由小到大，依次换算匹配           .
     * @param int $amount
     * @param array|object $matchObject  key-val
     * @param array $columnMapping       key-val
     * @param string $owner_id
     * @param string $type
     * @param string $sku
     * @return double
     * 错误代码： -1:非法数量 -2:无计费模型 -3:未知单位 -4:sku为空 -5:货主未找到 -6:无箱规 -7:未匹配到计费模型
     */
    public function matchRule($amount, $matchObject, $columnMapping, $owner_id, $sku = null, $type = '出库')
    {
        if ($amount <= 0 )return -1;

        $unitModels = Unit::query()->whereIn("name",["件","箱","单"])->get();
        $units = [];
        foreach ($unitModels as $unitModel)$units[$unitModel->id] = $unitModel->name;

        $withs = $type=='出库' ? ['ownerOutStorageRules'=>function($query){
            /** @var Builder $query */
            $query->orderByRaw("CASE strategy  WHEN '默认' THEN 1 WHEN '特征' THEN 2 WHEN '起步' THEN 3 END DESC,priority DESC");
        }] : ['ownerInStorageRule'] ;
        $rules = OwnerPriceOperation::query()->with($withs)
            ->where("operation_type","出库")
            ->whereHas("ownerPriceOperationOwners",function ($query)use($owner_id){
                /** @var Builder $query */
                $query->where("id",$owner_id);
            })
            ->orderByRaw("strategy desc,priority desc")->get(); //货主下的全部规则
        if (!$rules)return -2;

        if ($type == '入库'){
            foreach ($rules as $rule){
                if (!$rule->ownerInStorageRule)continue;
                if ($rule->strategy == '特征'){
                    $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);
                    if ($bool === true){
                        if (!isset($units[$rule->ownerInStorageRule->unit_id])) return -3;
                        if ($units[$rule->ownerInStorageRule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
                            $amount = $this->changeUnit($amount,$owner_id,$sku);
                            if ($amount<0) return $amount;
                        }
                        if ($units[$rule->ownerInStorageRule->unit_id] == '单')$amount = 1; //为单时数量设为1;
                        return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
                    };
                }else{
                    if (!isset($units[$rule->ownerInStorageRule->unit_id])) return -3;
                    if ($units[$rule->ownerInStorageRule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
                        $amount = $this->changeUnit($amount,$owner_id,$sku);
                        if ($amount<0) return $amount;
                    }
                    if ($units[$rule->ownerInStorageRule->unit_id] == '单')$amount = 1; //为单时数量设为1;
                    return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
                };
            }
            return -7;
        }
        //出库
        foreach ($rules as $rule){
            if (!$rule->ownerOutStorageRules)continue;
            if ($rule->strategy == '特征'){
                $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);//匹配特征
                if ($bool === true){
                    $money = $this->matchOutStorage($amount,$rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
                    if ($money>0)return $money;
                };
            }else{
                $money = $this->matchOutStorage($amount,$rule->ownerOutStorageRules,$columnMapping,$matchObject,$units,$owner_id,$sku);
                if ($money>0)return $money;
            };
        }
        return -7;
    }
    private function changeUnit($amount,$owner_id,$sku)
    {
        if (!$sku)return -4;
        $pack = app("CommodityService")->getPack($owner_id,$sku);
        if (!$pack)return -6;
        return ceil($amount/$pack);
    }
    private function matchOutStorage($amount, $rules, $columnMapping, $matchObject, $units, $owner_id, $sku)
    {
        $money = 0;
        foreach ($rules as $rule){
            switch ($rule->strategy){
                case "起步":
                    $money = $rule->amount * $rule->unit_price;
                    if ($units[$rule->unit_id] == '箱') { //为箱时同步商品寻找箱规
                        if (!$sku)return -4;
                        $pack = app("CommodityService")->getPack($owner_id,$sku);
                        if (!$pack)return -6;
                        $rule->amount *= $pack;
                    }

                    if ($amount < $rule->amount)$amount = $rule->amount;
                    else $amount -= $rule->amount;
                    break;
                case "特征":
                    if (app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject)){
                        if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单') return -3;
                        if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
                            $amount = $this->changeUnit($amount,$owner_id,$sku);
                        }
                        return (ceil($amount/$rule->amount)*$rule->unit_price)+$money;
                    };
                    break;
                case "默认":
                    if (!isset($units[$rule->unit_id]) || $units[$rule->unit_id] == '单') return -3;
                    if ($units[$rule->unit_id] == '箱'){ //为箱时同步商品寻找箱规
                        $amount = $this->changeUnit($amount,$owner_id,$sku);
                    }
                    return (ceil($amount/$rule->amount)*$rule->unit_price)+$money;
                    break;
            }
        }
        return -7;
    }

    private function matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $unit_id, $rules, $sku, $units = null, $isMatch = false)
    {
        /*foreach ($rules as $rule){
            if ($unit_id != $rule->ownerInStorageRule->unit_id)continue;
            else{
                if ($rule->strategy == '特征'){
                    $bool = app("FeatureService")->matchFeature($rule->feature,$columnMapping,$matchObject);
                    if ($bool === true){
                        return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
                    };
                }else{
                    return ceil($amount/$rule->ownerInStorageRule->amount)*$rule->ownerInStorageRule->unit_price;
                };
            }
        }
        //单位换算
        if (!$units){
            $unitModels = Unit::query()->whereIn("name",["件","箱","单"])->get();
            if (!$unitModels) return null;
            foreach ($unitModels as $unitModel)$units[$unitModel->name] = $unitModel->id;
        }
        $name = array_search($unit_id,$units);
        //递归匹配
        switch ($name){
            case "件"://布尔值校验是否匹配过件来确保箱只匹配一次件
                return $this->matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $units["箱"], $rules, $sku, $units, true);
            case "箱"://箱存在向下向上转换
                if ($isMatch){
                    return $this->matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $units["单"], $rules, $sku, $units);
                }else{
                    return $this->matchInStorage($amount, $matchObject, $columnMapping, $owner_id, $units["件"], $rules, $sku, $units);
                }
            case "单"://三次匹配皆无，返回null
                return null;
        }*/
    }
}