<?php

namespace App\Bonus;

use Carbon\Carbon;
use Modules\Coupon\Models\Coupon;
use Modules\Coupon\Models\CouponGrant;
use Modules\User\Models\Identity;
use Modules\User\Models\Order;
use Modules\User\Models\User;

class IdentityBonus
{

    /**
     * 开通身份
     *
     * @param  User  $user
     * @param  Order  $order
     * @param  array  $source
     * @return bool|string
     */
    public static function BuyIdentity(User $user, Order $order, array $source = [])
    {
        dd(1);
        try {
            $identity       = $order->identity;
            $parent         = $user->parent;
            $parentIdentity = $parent ? $user->parent->identityFirst() : '';

            //开通赠送水滴
            $crystal = $order->identity->getRule('give_crystal', '0');
            if ($crystal > 0) {
                $user->account->rule('open_identity_score', $crystal, true, array_merge($source, [
                    'user_order_id' => $order->id
                ]));
            }
            //发券
            self::grantCoupon($user, $order, $parent, $parentIdentity);

            //是否有上级
            if ($parent && $parentIdentity && $order->price > 0) {
                //增加业绩
                $parent->addPerf($order->price, $order);
                //开通的是季卡
                if ($identity->job == Identity::JOB_JK) {


                    //直推季卡获得水滴
                    $hasRecommend_jk_score = $parentIdentity->getRule('recommend_jk_score', '');
                    if ($hasRecommend_jk_score) {
                        $user->parent->account->rule(
                            'recommend_jk_score',
                            $hasRecommend_jk_score,
                            false,
                            array_merge($source, [
                                'user_order_id' => $order->id
                            ])
                        );
                    }

                    //合伙人推荐奖励
                    self::setHhRecommendJk($hasRecommend_jk_score, $user, $order, $source);
                }

                //开通的是年卡
                if ($identity->job == Identity::JOB_NK) {
                    //直推年卡获得水滴
                    $hasRecommend_nk_score = $parentIdentity->getRule('recommend_nk_score', '');
                    if ($hasRecommend_nk_score) {
                        $user->parent->account->rule(
                            'recommend_nk_score',
                            $hasRecommend_nk_score,
                            false,
                            array_merge($source, [
                                'user_order_id' => $order->id
                            ])
                        );
                    }

                    //合伙人推荐奖励
                    self::setHhRecommendNk($hasRecommend_nk_score, $user, $order, $source);
                }
            }

            return true;
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

    }

    /**
     * Notes: 发券
     * 推荐会员得优惠券  季卡 年卡 创始
     *
     * @Author: 玄尘
     * @Date: 2022/8/31 13:53
     */
    public static function grantCoupon($user, $order, $parent, $parentIdentity)
    {
        if ($parent && $parentIdentity->job !== Identity::JOB_HH) {
            $jkIdentity               = Identity::query()->Jk()->first();
            $openJkCount              = $parent->getOpenJkCount();//开通季卡次数
            $recommendUserCoupunCount = $parent->getRecommendUserCouponCount();//推荐季卡得优惠券数
            $recommend_coupon         = $parentIdentity->getRule('recommend_coupon', null);//是否有推荐奖励

            //推荐季卡得优惠券
            if ($recommend_coupon && $order->type == Order::TYPE_OPEN && $openJkCount > $recommendUserCoupunCount) {
                $coupon = Coupon::query()
                    ->whereHas('items', function ($q) use ($jkIdentity) {
                        $q->withGoods($jkIdentity);
                    })
                    ->first();

                $ended_at = Carbon::parse($parentIdentity->pivot->ended_at);
                if ($coupon && $ended_at->gt(now())) {
                    $days = $ended_at->addMonth()->diffInDays(now());
                    #TODO 推季卡会员得优惠券
                    //  $user->parent->getCoupon($coupon->id, CouponGrant::CHANNEL_EXPAND, $days);
                    $user->parent->getCoupon($coupon->id, CouponGrant::CHANNEL_EXPAND);
                }
            }
        }
    }

    /**
     * Notes: 合伙人推荐季卡
     *
     * @Author: 玄尘
     * @Date: 2022/8/19 15:11
     */
    public static function setHhRecommendJk($score, $user, $order, $source)
    {
        $hhUsers    = $user->getParentHh();//获取所有合伙人
        $hhIdentity = Identity::query()->where('job', Identity::JOB_HH)->first();
        $rule_name  = 'recommend_indirect_jk_balance';
        if ($hhIdentity && ! empty($hhUsers)) {
            //有人获得了推荐水滴就是间推

            $i = 1;
            foreach ($hhUsers as $hhUser) {
                $jkChildren = $hhUser->getJkChildrenCount();
                $amount     = 0;

                if ($i > 1) {
                    break;
                }

                //间接
                if ($score) {
                    if ($jkChildren > 10) {
                        $rateName = 'recommend_rate_indirect_jk_balance_gt';
                    } else {
                        $rateName = 'recommend_rate_indirect_jk_balance_lte';
                    }
                } else {//直接
                    if ($jkChildren > 10) {
                        $rateName = 'recommend_rate_jk_balance_gt';
                    } else {
                        $rateName = 'recommend_rate_jk_balance_lte';
                    }

                    $rule_name = 'recommend_jk_balance';
                }

                $hasRate  = $hhIdentity->getRule($rateName, 0);//获取比例
                $rateData = self::getNonZeroRate($hasRate);
                $amount   = bcmul($order->price, $rateData, 2);

                if ($amount) {
                    //执行分润
                    $hhUser->account->rule(
                        $rule_name,
                        $amount,
                        false,
                        array_merge($source, [
                            'user_order_id' => $order->id,
                            'rate'          => $rateData
                        ])
                    );
                    //培育津贴
                    self::allowance($hhUser, $amount, $source);
                }

                $i++;
            }
        } else {
            info('没有找到合伙人');
        }
    }

    /**
     * Notes: 合伙人间推季卡
     *
     * @Author: 玄尘
     * @Date: 2022/8/19 15:13
     */
    public static function setHhRecommendNk($score, $user, $order, $source)
    {
        $hhUsers    = $user->getParentHh();//获取所有合伙人
        $hhIdentity = Identity::query()->where('job', Identity::JOB_HH)->first();
        $rule_name  = 'recommend_indirect_nk_balance';
        if ($hhIdentity && ! empty($hhUsers)) {
            //有人获得了推荐水滴就是间推
            $i = 1;
            foreach ($hhUsers as $hhUser) {
                $nkChildren = $hhUser->getNkChildrenCount();
                $amount     = 0;
                if ($i > 1) {
                    break;
                }

                //间接
                if ($score) {
                    if ($nkChildren > 10) {
                        $rateName = 'recommend_rate_indirect_nk_balance_gt';
                    } else {
                        $rateName = 'recommend_rate_indirect_nk_balance_lte';
                    }
                } else {//直接
                    if ($nkChildren > 10) {
                        $rateName = 'recommend_rate_nk_balance_gt';
                    } else {
                        $rateName = 'recommend_rate_nk_balance_lte';
                    }

                    $rule_name = 'recommend_nk_balance';
                }
                $hasRate  = $hhIdentity->getRule($rateName, 0);//获取比例
                $rateData = self::getNonZeroRate($hasRate);
                $amount   = bcmul($order->price, $rateData, 2);


                if ($amount > 0) {
                    //执行分润
                    $hhUser->account->rule(
                        $rule_name,
                        $amount,
                        false,
                        array_merge($source, [
                            'user_order_id' => $order->id,
                            'rate'          => $rateData
                        ])
                    );

                    //培育津贴
                    self::allowance($hhUser, $amount, $source);
                }
                $i++;
            }
        }
    }


    /**
     * Notes: 获取百分比数据
     *
     * @Author: 玄尘
     * @Date: 2022/8/19 14:56
     * @param $rate
     * @param $decimals
     * @return int|string|null
     */
    public static function getNonZeroRate($rate, $decimals = 2)
    {
        return $rate > 0 ? bcdiv($rate, 100, $decimals) : 0;
    }

    /**
     * Notes: 培育津贴
     *
     * @Author: 玄尘
     * @Date: 2022/8/30 14:32
     */
    public static function allowance(User $user, $amount, $source)
    {
        $UserIdentity = $user->identityFirst();
        $hasRate      = $UserIdentity->getRule('recommend_rate_allowance', 0);//获取培育津贴比例
        if ($UserIdentity->job == Identity::JOB_HH && $hasRate) {
            $hhUsers  = $user->getParentHh();//获取所有合伙人
            $rateData = self::getNonZeroRate($hasRate);
            $amount   = bcmul($amount, $rateData, 2);

            $i = 1;
            if (! empty($hhUsers)) {
                foreach ($hhUsers as $hhUser) {
                    if ($i > 1) {
                        break;
                    }
                    $hhUser->account->rule(
                        'allowance_balance',
                        $amount,
                        false,
                        $source
                    );
                    $i++;
                }
            }
        }

    }


}
