<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model\goods;

use think\Model;

/**
 * @package app\common\model\goods
 * @class Distribution
 * @author xzncit 2024-02-14
 */
class Distribution extends Model {

    protected $name = "goods_distribution";

    /**
     * 获取运费价格
     * @param $goods
     * @param $num
     * @param $address
     * @return float|int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getFreightPrice($goods,$num,$address){
        if($goods["delivery_id"] == -1){
            return formatMoney($goods["fixed_freight"] * $num);
        }else if($goods["delivery_id"] == 0){
            return 0;
        }

        if(empty($address)){
            return 0;
        }

        $delivery = self::where("id",$goods["delivery_id"])->find();
        if(empty($delivery)){
            return 50;
        }

        $distribution = [
            "first_weight"  => $delivery["first_weight"],
            "second_weight" => $delivery["second_weight"],
            "first_price"   => $delivery["first_price"],
            "second_price"  => $delivery["second_price"]
        ];

        if(!empty($delivery["area_group"])){
            $areaGroup = json_decode($delivery["area_group"]);
            foreach($areaGroup as $key=>$value){
                if(in_array($address["province"],$value) && in_array($address["city"],$value)){
                    $firstPriceGroup  = json_decode($delivery["first_price_group"]);
                    $secondPriceGroup = json_decode($delivery["second_price_group"]);
                    $distribution["first_price"]  = $firstPriceGroup[$key];
                    $distribution["second_price"] = $secondPriceGroup[$key];
                    break;
                }
            }
        }

        return self::calculate($goods["goods_weight"] * $num,$distribution);
    }

    /**
     * @param $weight
     * @param $distribution
     * @return float|int
     */
    protected static function calculate($weight,$distribution) {
        $firstWeight  = $distribution["first_weight"];
        $secondWeight = $distribution["second_weight"];

        if($weight <= $firstWeight) {
            return $distribution["first_price"];
        }

        $num = ceil(($weight - $firstWeight) / $secondWeight);
        return $distribution["first_price"] + $distribution["second_price"] * $num;
    }

}