<?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 FranchiseeEvent
{
    public function grant($params)
    {
        try {
            Log::info("进入加盟合伙人事件", $params);
            $config = SysConfig::where('config_key', 'app-identity-franchisee-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_franchisee_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'],
                    'dept_id' => $params['dept_id'] ?? '',
                    'dept_name' => $params['dept_name'] ?? ''
                ]),
                'member_is_franchisee' => 'Y',
            ];
            Member::where('member_id', $params['member_id'])->update($memberUpdateData);
            // 余额账户
            $memberAccount = MemberAccount::where('join_account_member_id', $params['member_id'])->where('member_account_classify', 'CASH')->first();
            // 增值到最后一条支付记录
            $added = 0;
//            $payDetail = PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->orderBy('pay_addtimes', 'DESC')->first();
            if (!empty($configParams['account']) && !empty($configParams['account']['added']) && $configParams['account']['added'] > 0) {
                $added = round($params['order_amount_total'] * $configParams['account']['added'], 2);
//                $payDetail->pay_extend_json = json_encode(['added_rate' => $configParams['account']['added'], 'added_amount' => $added]);
//                $payDetail->save();
                $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])->select('goods_id', 'goods_name')->first();
                // 增加一条支付记录
                PayDetail::insert([
                    'join_pay_member_id' => $params['member_id'],
                    'join_pay_order_id' => 'FRANCHISEE',
                    'join_pay_object_json' => json_encode([
                        'recharge_order_id' => $params['orderId'],
                        'recharge_config' => [
                            'nbr' => round($params['order_amount_total'] * $configParams['account']['added'], 2)
                        ],
                        'recharge_goods_id' => $params['join_sheet_goods_id'] ?? '',
                        'recharge_goods_name' => !empty($goods->goods_name) ? $goods->goods_name : ''
                    ]),
                    'pay_status' => 'SUCCESS',
                    'pay_category' => 'RECHARGE',
                    'pay_amount' => 0,
                    'pay_paytimes' => date('Y-m-d H:i:s'),
                    'pay_prepayid' => $params['member_id'] . '-CASH',
                    'pay_addtimes' => time()
                ]);
            }
            // 入账
            $memberAccount->member_account_income = $memberAccount->member_account_income + $added;
            $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $added;
            $memberAccount->save();

            // 给上级提成
            CommissionService::commission($configParams, $params['member_id'], $params['orderId'], $params['order_amount_pay'], '推荐加盟合伙人');

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

        } catch (BusinessException $e) {
            _syslog('加盟合伙人', '加盟合伙人处理失败：' . $e->getMessage());
            throw new BusinessException("加盟合伙人处理失败");
        } catch (\Exception $e) {
            Log::info('FRANCHISEE_DISPOSE_ERROR：' . $e->getMessage(), $params);
            _syslog('加盟合伙人', '加盟合伙人处理失败');
            throw new BusinessException("加盟合伙人处理失败");
        }
    }
}