<?php

namespace app\event\order;

use app\admin\service\coupon\CouponService;
use app\admin\service\order\CommissionService;
use app\model\Goods;
use app\model\Member;
use app\model\MemberAccount;
use app\model\PayDetail;
use app\model\SysConfig;
use support\Db;
use support\exception\BusinessException;
use support\Log;

class ReferrerEvent
{
    public function grant($params)
    {
        try {
            Log::info("进入推荐官事件", $params);
            $config = SysConfig::where('config_key', 'app-identity-referrer-config')->first();
            $configParams = json_decode($config->config_value_json, true);
            // 更新身份{"duedate": "2025-09-26", "datetime": "2024-09-27 14:40:51", "order_id": "OD2409271440L951"}
            $memberUpdateData = [
                'member_referrer_json' => json_encode([
                    'datetime' => date('Y-m-d H:i:s'),
                    'duedate' => date('Y-m-d', strtotime("+" . ($configParams['config']['valid']-1) . ' day')),
                    'order_id' => $params['orderId'],
                ]),
                'member_is_referrer' => 'Y',
            ];
            Member::where('member_id', $params['member_id'])->update($memberUpdateData);

            // 给上级提成
            CommissionService::commission($configParams, $params['member_id'], $params['orderId'], $params['order_amount_pay'], '推荐康养推荐官');

            //发放优惠券
            $params['gettype'] = 'REFERRER';
            CouponService::autoSendCouponByGoods($params);

        } catch (BusinessException $e) {
            _syslog('会员合伙人', '推荐官处理失败：' . $e->getMessage());
            throw new BusinessException("推荐官处理失败");
        } catch (\Exception $e) {
            Log::info('PARTNER_DISPOSE_ERROR：' . $e->getMessage(), $params);
            _syslog('会员合伙人', '推荐官处理失败');
            throw new BusinessException("推荐官处理失败");
        }
    }
}