<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/4
 * Time: 上午9:56
 */

namespace App\Modules\Finance\Services;


use App\Modules\Finance\Models\Bill;
use App\Modules\Finance\Models\CommissionRate;

class CommissionRateService
{

    /**
     *
     * @param $id
     * @return mixed
     */
    public static function getCommissionRateSingle($id) {
        $result = CommissionRate::where('id', $id)->first();
        return $result;
    }

    /**
     * 获取佣金结算比例列表
     * @param $channelId
     * @return mixed
     */
    public static function getCommissionRateList($channelId) {
        $result = CommissionRate::getListByDistributionChannel($channelId);
        return $result;
    }

    /**
     * 创建佣金结算
     * @param $channelId
     * @param $begin_amount 起始金额
     * @param $end_amount 结束金额
     * @param $rate 比例
     * @return mixed
     */
    public static function addCommissionRate($channelId, $begin_amount, $end_amount, $rate) {
        if(is_numeric($rate) && $rate >= 1) {
            $rate = '';
        }

        $data['distribution_channel_id'] = $channelId;
        $data['begin_amount'] = $begin_amount;
        $data['end_amount'] = $end_amount;
        $data['rate'] = $rate;

        $result = CommissionRate::create($data);

        return $result;
    }

    /**
     * 更新佣金结算
     * @param $id
     * @param string $begin_amount 起始金额
     * @param string $end_amount 结束金额
     * @param string $rate 比例
     * @param string $channelId
     */
    public static function updateCommissionRate($id, $begin_amount = '', $end_amount = '', $rate = '', $channelId = '') {
        $commissionRate = self::getCommissionRateSingle($id);
        if(empty($commissionRate)) {
            return;
        }

        if(is_numeric($rate) && $rate >= 1) {
            $rate = '';
        }

        if($begin_amount) {
            $commissionRate['begin_amount'] = $begin_amount;
        }
        if($end_amount) {
            $commissionRate['end_amount'] = $end_amount;
        }
        if($rate) {
            $commissionRate['rate'] = $rate;
        }
        if($channelId) {
            $commissionRate['distribution_channel_id'] = $channelId;
        }
        $commissionRate->save();
    }

    /**
     * 获取当前渠道当前佣金比例
     * @param $channelId
     * @return mixed
     */
    public static function getRateCommissionRate($channelId) {
        $rate = Bill::getRate($channelId);
        return $rate;
    }
}