<?php

namespace app\admin\service\notify;

use app\admin\service\coupon\CouponDetailService;
use app\model\Coupon;
use app\model\CouponDetail;
use app\model\Goods;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberQuota;
use app\model\MemberRole;
use app\model\Order;
use app\model\OrderSheet;
use app\model\PayDetail;
use app\model\RuleAdded;
use app\model\RuleAddedComponent;
use Monolog\Handler\IFTTTHandler;
use support\exception\BusinessException;
use support\Log;

class RechargeService
{
    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/28 16:50
     *
     * @param $orderId
     * @return mixed
     * @throws BusinessException
     */
    public static function disposeOrder($orderId)
    {
        $orderSheet = OrderSheet::where('join_sheet_order_id', $orderId)->first();
        if (!$orderSheet) {
            throw new BusinessException('订单数据异常');
        }
        $goods = Goods::find($orderSheet->join_sheet_goods_id);
        // 自定义充值产品
        if ($goods->join_goods_category_id == 210) {
            return 0;
        }
        if (empty($goods->goods_attribute_json)) {
            throw new BusinessException('产品数据异常');
        }
        $attributeJson = json_decode($goods->goods_attribute_json, true);
        if (!isset($attributeJson['added'])) {
            throw new BusinessException('产品数据异常');
        }

        return $attributeJson['added']['nbr'];
    }

    public static function getGoodsAttributeJson($orderId)
    {
        try {
            $orderSheet = OrderSheet::where('join_sheet_order_id', $orderId)->first();
            if (!$orderSheet) {
                throw new BusinessException('订单数据异常');
            }
            $goods = Goods::find($orderSheet->join_sheet_goods_id);
            if (empty($goods->goods_attribute_json)) {
                return [];
                // throw new BusinessException('产品数据异常');
            }

            return json_decode($goods->goods_attribute_json, true);

        } catch (BusinessException $e) {
            throw new BusinessException($e->getMessage());
        } catch (\Exception $e) {
            throw new BusinessException('产品数据异常');
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/29 16:25
     *
     * @param $memberId
     * @param $payAmount
     * @throws BusinessException
     */
    public static function disposeRole($memberId, $payAmount)
    {
        try {
            $member = Member::with([
                'role' => function ($query) {
                    $query->select('member_role_id', 'member_role_sort');
                }
            ])->where('member_id', $memberId)
                ->first();
            $memberRoleConfigJson = [];
            if (!empty($member->member_role_config_json)) {
                $memberRoleConfigJson = json_decode($member->member_role_config_json, true);
            }
            $role = MemberRole::where('member_role_category', 'COMBINE')
                ->where('member_role_range_begin', '<=', $payAmount)
                ->where('member_role_range_end', '>=', $payAmount)
                ->first();
            $memberRoleId = '';
            $memberRoleBegintime = '';
            // 没有角色,或者有角色,新角色等级高
            if ((!empty($member->role) && !empty($role) && $role->member_role_sort > $member->role->member_role_sort) || (empty($member->role) && !empty($role))) {
                $memberRoleId = $role->member_role_id;
                $memberRoleBegintime = date('Y-m-d H:i:s');
                $memberRoleConfigJson['next'] = [];
            } elseif (!empty($member->role) && !empty($role) && $role->member_role_sort == $member->role->member_role_sort) {
                $memberRoleId = $role->member_role_id;
                $memberRoleBegintime = date('Y-m-d H:i:s');
                $memberRoleConfigJson['next'] = [];
            } elseif (!empty($member->role) && !empty($role) && $role->member_role_sort < $member->role->member_role_sort) {
                $memberRoleId = $member->role->member_role_id;
                $memberRoleBegintime = $member->member_role_begintime;
                $memberRoleConfigJson['next'][] = ['member_role_begintime' => date('Y-m-d H:i:s'), 'member_role_id' => $role->member_role_id];
            }
            $memberRoleConfigJson['deadline_datetime'] = date('Y-m-d 23:59:59',strtotime($memberRoleBegintime.' +364 days'));
            if(!empty($memberRoleId)){
                Member::where('member_id', $memberId)->update([
                    'join_member_role_id' => $memberRoleId,
                    'member_role_begintime' => $memberRoleBegintime,
                    'member_role_config_json' => json_encode($memberRoleConfigJson)
                ]);
            }
        } catch (\Exception $e) {
            Log::error('计算等级异常：' . $e->getMessage());
            throw new BusinessException("计算等级异常");
        }
    }

    public static function disposeRoleCoupon($goodsAttributeJson,$couponParams, $memberId)
    {
        try {
            if (empty($goodsAttributeJson['coupon'])) {
                return;
            }

            // 发券
            foreach ($goodsAttributeJson['coupon'] as $key => $coupon) {
                $couponModel = Coupon::where('coupon_id', $key)->select('coupon_id', 'coupon_validdate_day', 'coupon_validdate_end', 'coupon_is_period', 'coupon_number')->first();
                if (empty($couponModel)) {
                    continue;
                }
                // 券是否过期
                if (!empty($couponModel->coupon_validdate_end) && strtotime($couponModel->coupon_validdate_end) < time()) {
                    continue;
                }
                // 发周期券
                if ($couponModel->coupon_is_period == 'Y') {
                    // 发券参数
                    $couponSendParams = ['gettype' => 'ROLE', 'coupon_id' => $key, 'member_id' => $memberId,'order_id'=>$couponParams['order_id'] ?? ''];
                    Log::info("发周期券参数", $couponSendParams);
                    CouponDetailService::sendPeriodCoupon($couponSendParams);
                    continue;
                }
                $couponResidue = 'all';
                if ($couponModel->coupon_number != 0) {
                    $couponResidue = CouponDetail::where('join_detail_coupon_id', $key)->whereIn('coupon_detail_status', ['INIT', 'PENDING'])->count();
                    // 超出优惠券设置的数量
                    if ($couponResidue < $coupon['num']) {
                        continue;
                    }
                }
                $endDate = '';
                if (!empty($couponModel->coupon_validdate_end)) {
                    $endDate = $couponModel->coupon_validdate_end;
                } elseif ($couponModel->coupon_validdate_day > 0) {
                    $endDate = date('Y-m-d H:i:s', time() + ($couponModel->coupon_validdate_day * 24 * 3600) - 1);
                }
                // 发券参数
                $couponSendParams = [
                    'gettype' => 'ROLE',
                    'coupon_id' => $key,
                    'chooseCouponNbr' => $coupon['num'],
                    'member_id' => $memberId,
                    'coupon_detail_gain_datetime' => date('Y-m-d H:i:s'),
                    'coupon_detail_deadline_datetime' => $endDate,
                    'order_id'=>$couponParams['order_id'] ?? ''
                ];

                Log::info("发普通券参数", $couponSendParams);
                if ($couponResidue != 'all' && $couponResidue - $coupon['num'] >= 0) {
                    CouponDetailService::customSendCouponHave($couponSendParams);
                } else {
                    for ($i = 0; $i < $coupon['num']; $i++) {
                        CouponDetailService::customSendCoupon($couponSendParams);
                    }
                }
            }
        } catch (\Exception $e) {
            throw new BusinessException("发券异常");
        }

    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/28 18:03
     *
     * @param $roleId
     * @param $memberId
     * @return void
     * @throws BusinessException
     */
    public static function disposeAdded($roleId, $memberId)
    {
        $role = MemberRole::find($roleId);
        if (empty($role->member_role_rule_json)) {
            throw new BusinessException('增值套包数据异常');
        }
        $ruleJson = json_decode($role->member_role_rule_json, true);
        if (!isset($ruleJson['added'])) {
            throw new BusinessException('增值套包数据异常');
        }
        $addedId = $ruleJson['added'];
        $added = RuleAdded::find($addedId);
        if (!$added) {
            throw new BusinessException('增值套包数据异常');
        }
        $diff = $added->rule_added_goods_diff;

        $components = RuleAddedComponent::where('join_component_rule_added_id', $addedId)->get()->toArray();
        switch ($diff) {
            case "SUM":
                self::diffSum($memberId, $components);
                break;
            case "REPLACE":
                self::diffReplace($memberId, $components);
                break;
            case "NONE":
                self::diffNone($memberId, $components);
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/28 18:03
     *
     * @param $memberId
     * @param $components
     * @return void
     */
    public static function diffSum($memberId, $components)
    {
        foreach ($components as $component) {
            self::saveMemberQuota($memberId, $component);
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/28 18:02
     *
     * @param $memberId
     * @param $components
     * @return void
     */
    public static function diffReplace($memberId, $components)
    {
        foreach ($components as $component) {
            if (MemberQuota::where('join_quota_member_id', $memberId)->where('join_member_rule_added_component_id', $component['rule_added_component_id'])->exists()) {
                MemberQuota::where('join_quota_member_id', $memberId)
                    ->where('join_member_rule_added_component_id', $component['rule_added_component_id'])
                    ->where('member_quota_status', 'PENDING')
                    ->delete();
            }

            self::saveMemberQuota($memberId, $component);
        }

    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/28 18:02
     *
     * @param $memberId
     * @param $components
     * @return void
     */
    public static function diffNone($memberId, $components)
    {
        foreach ($components as $component) {
            if (MemberQuota::where('join_quota_member_id', $memberId)->where('join_member_rule_added_component_id', $component['rule_added_component_id'])->exists()) {
                continue;
            }

            self::saveMemberQuota($memberId, $component);
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/5/28 18:02
     *
     * @param $memberId
     * @param $component
     * @return void
     */
    private static function saveMemberQuota($memberId, $component)
    {
        if ($component['rule_added_component_classify'] == 'MONTH') {
            $total = 12 * intval($component['rule_added_component_goods_nbr']);
            for ($i = 0; $i < $total; $i++) {
                self::doSaveMemberQuota($memberId, $component, 1);
            }
        } elseif ($component['rule_added_component_classify'] == 'YEAR') {
            if ($component['rule_added_component_goods_nbr'] == "-99.00") {
                self::doSaveMemberQuota($memberId, $component, -99);
            } else {
                for ($i = 0; $i < intval($component['rule_added_component_goods_nbr']); $i++) {
                    self::doSaveMemberQuota($memberId, $component, 1);
                }
            }
        } else {
            if ($component['rule_added_component_goods_nbr'] == "-99.00") {
                self::doSaveMemberQuota($memberId, $component, -99);
            } else {
                for ($i = 0; $i < intval($component['rule_added_component_goods_nbr']); $i++) {
                    self::doSaveMemberQuota($memberId, $component, 1);
                }
            }
        }
    }

    private static function doSaveMemberQuota($memberId, $component, $nbr)
    {
        $model = new MemberQuota();
        $model->member_quota_id = 'MQ' . date('ymdHi') . random_string(4, 'up');
        $model->join_quota_member_id = $memberId;
        $model->join_member_rule_added_component_id = $component['rule_added_component_id'];
        $model->member_quota_status = 'PENDING';
        $model->member_quota_category = $component['rule_added_component_category'];
        $model->member_quota_name = $component['rule_added_component_name'];
        $model->member_quota_nbr = $nbr;
        $model->member_quota_json = $component['rule_added_component_goods_json'];
        $model->member_quota_addtimes = time();
        $model->save();
    }

    /**
     * @Desc 充值前保存原账户数据
     * @Author Gorden
     * @Date 2024/10/14 9:18
     *
     * @param MemberAccount $memberAccount
     * @param $payAmount
     * @param $addedRate
     * @param $addedAmount
     * @return void
     * @throws BusinessException
     */
    public static function saveOriginData(MemberAccount $memberAccount, $payAmount, $addedRate, $addedAmount)
    {
        try {
            $memberAccount = $memberAccount->toArray();
            $memberAccount['pay_amount'] = $payAmount;
            $memberAccount['added_rate'] = $addedRate;
            $memberAccount['added_amount'] = $addedAmount;


            $member = Member::where('member_id', $memberAccount['join_account_member_id'])->first();
            $memberExtendJson = [];
            if (!empty($member->member_extend_json)) {
                $memberExtendJson = json_decode($member->member_extend_json, true);
            }
            $memberExtendJson['snap'][date('Y-m-d H:i:s')] = $memberAccount;
            $member->member_extend_json = json_encode($memberExtendJson);
            $member->save();

        } catch (\Exception $e) {
            throw new BusinessException('存储原数据失败');
        }
    }
}