<?php
namespace app\event;
use support\think\Db;
use Request;
use Symfony\Component\Console\Input\Input;
class User{
    function register_successed($user){
        $date = date('Y-m-d');
        cache_add('statistics_register_'.$date,1);
        $saveData = [
            'invite_code'  =>  build_invite_code($user->id)
        ];
        //管理直推人数和团队人数
        if($user->parent_id){
            parent_info( $user->id,[
                'id'    =>  $user->parent_id,
                'username' =>  Db::name('user')->where('id',op: $user->parent_id)->value('username')
            ]);
            //管理直推人数
            cache_add('team_direct_total_'.$user->parent_id,1);
            \app\model\UserExtend::where('user_id',$user->parent_id)->save([
                'direct_total'   =>  Db::raw('direct_total+1'),
                'team_total'     =>  Db::raw('team_total+1'),
            ]);
        }
        
        \app\model\User::where('id',$user->id)->update($saveData);
        //创建扩展数据
        \app\model\UserExtend::create([
            'user_id'   =>  $user->id,
            'direct_total'   =>  0,
            'team_total'     =>  0,
            'consume'   =>  0,
            'sales'     =>  0
        ]);

        
        $this->buildTeam($user);
    }
    function login_successed($data=[]){
        return $data;
    }
    function profile($user=[]){
        $data = $user;
        if(!is_array($data)){
            $data = $data->toArray();
        }
        $role_arr = [
            '1' =>  __('普通用户'),
            '2' =>  __('VIP'),
        ];
        $data['has_trade_password'] = $data['trade_password'] ? true: false;
        $data['avatar'] = cdnurl($data['avatar']);
        $disallowFields = ['trade_password','password','client','loginfailure'];
        $data = array_diff_key($data, array_flip($disallowFields));
        $data['recharge_total'] = cache('user_recharge_total_'.$data['id'])?:0;
        $data['withdrawl_total'] = cache('user_withdrawl_total_'.$data['id'])?:0;
        $data['income_total'] = cache('user_income_total_'.$data['id'])?:0;
        $data['today_income'] = cache('user_today_income_'.date('Ymd').'_'.$data['id'])?:0;
        $data['month_income'] = cache('user_month_income_'.date('Ym').'_'.$data['id'])?:0;
        $data['consume_total'] = cache('user_consume_total_'.$data['id'])?:0;
        $data['power_total'] = cache('user_power_total_'.$data['id'])?:0;
        $data['role_reward_total'] = cache('user_role_reward_total_'.$data['id'])?:0;
        $data['avatar'] = $data['avatar']?:"/static/img/avatar.png";
        $data['role'] = isset($role_arr[$data['role_id']]) ? $role_arr[$data['role_id']] : __('普通用户');//\app\model\UserRole::where('id',$data['role_id'])->value('name');
        
        $data['level'] = get_user_level($data['id']);
        /**
         * @var \support\OpenImSdk\Client $IM
         */
        $IM = request()->IM;
        $imToken = $IM->auth->getUserToken($data['id'],Input('platform'));
        $data['imToken'] = $imToken['token'];
        $data['userID'] = $data['id'] ;
        $data['id'] = idEncode($data['id']);
        $last_see = $last_see ?? cache('last_see_'.$data['id']);
        $count = 0;
        $data['friend_settings'] = [
            'unread_count'  => $count ??0,
            'userHeadImg'   => null,
        ];
        return $data; 
    }
    function changepwd_successed($data=[]){
        return $data;
    }
    function change_trade_pwd_successed($data=[]){
        return $data;
    }
    function logout_successed($data=[]){
        return $data;
    }
    function delete_successed($data=[]){
        return $data;
    }
    //用户角色组变化
    function roleup($user=[]){
        $data = $user;
        if(!is_array($data)){
            $data = $data->toArray();
        }
        if(!$user->active){
            $user->active = 1;
            $user->save();
            cache_add('team_direct_total_'.$user->parent_id,1);
        }
        return $user;
    }

    function buildTeam($user){


        // 插入自己的团队关系 (自己是自己的后代)
        $teamData = [
            [
                'ancestor_id' => $user->id,
                'descendant_id' => $user->id,
                'depth' => 0,
                'status' => 0,
            ]
        ];
        // 2. 处理团队关系（如果有推荐人）
        if ($user->parent_id) {

            parent_info( $user->id,[
                'id'    =>  $user->parent_id,
                'username' =>  Db::name('user')->where('id',$user->parent_id)->value('username')
            ]);
            // 获取推荐人所有的上级关系，生成新用户的团队关系
            $ancestors = Db::name('user_team')
                ->where('descendant_id', $user->parent_id)
                ->select();
            /** @var \app\model\UserTeam $ancestor */
            // 插入新用户与祖先的关系
            foreach ($ancestors as $ancestor) {
                $teamData[] = [
                    'ancestor_id' => $ancestor['ancestor_id'],
                    'descendant_id' => $user->id,
                    'depth' => $ancestor['depth'] + 1,
                    'status' => 1, // 默认状态为 0，表示无效
                ];
            }
        }
        // 批量插入关系
        try {
            Db::name('user_team')->insertAll($teamData);
        } catch (\Exception $e) {
            cp($e->getMessage());
        }
    }
    
    /**
     * 分润逻辑
     *
     * @param int $userId 用户ID（充值用户）
     * @param float $amount 充值金额
     * @param int $orderId 订单ID
     * @return bool
     */
    function distributeProfit($user_id, $amount, $order_id) {
        // 定义分润比例
        $commissionRates = Config('site.indirect_referral_award');

        // 启动事务
        Db::startTrans();
        try {
            // 查询上三级用户
            $ancestors = Db::name('user_team')
                ->alias('ut')
                ->join('user wu', 'ut.ancestor_id = wu.id') // 获取上级用户信息
                ->where('ut.descendant_id', $user_id)
                ->whereBetween('ut.depth', [1, 3]) // 限制深度为 1 到 3 级
                ->field('ut.ancestor_id, ut.depth')
                ->order('ut.depth ASC')
                ->select();

            // 遍历上级用户，计算并记录分润
            /** @var \app\model\UserTeam $ancestor */
            foreach ($ancestors as $ancestor) {
                $depth = $ancestor['depth'];
                if (isset($commissionRates[$depth])) {
                    $commission = $amount * $commissionRates[$depth]; // 计算分润金额

                    // 插入分润记录
                    Db::table('z_commission_logs')->insert([
                        'user_id' => $ancestor['ancestor_id'],
                        'order_id' => $order_id,
                        'amount' => $commission,
                        'created_at' => date('Y-m-d H:i:s'),
                    ]);
                }
            }

            // 提交事务
            Db::commit();
            return true;

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e; // 或记录日志以便调试
        }
    }
}