<?php
namespace app\api\controller;
use app\model\User as UserModel;
use app\model\UserTeam as UserTeamModel;
use app\model\WorkRecord as WorkRecordModel;
use support\Request;
use support\think\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * 用户团队
 */
class TeamController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = [];
    /**
     * @Apidoc\Title("团队概览")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("username", type="string",require=true, desc="用户名")
     * @Apidoc\Param("nickname", type="string",require=true, desc="密码")
     */
    public function index(Request $request){
        $user = \support\Jwt::getUserinfo();
        $user_id = $user['id'];
        $user= Hook('user.profile',$user);
        $team_ids = UserTeamModel::where('ancestor_id',$user_id)->where('depth','>',0)->column('descendant_id');
        
        $result=[
            'total_count'       =>  count($team_ids),//团队总人数
            'direct_total'       =>  cache('team_direct_total_'.$user_id)??0,//直属团队人数
            'recharge_total'    =>  cache('team_recharge_total_'.$user_id)??0,
            'withdrawl_total'   =>  cache('team_withdrawl_total_'.$user_id)??0,
            'income_total'      =>  cache('team_income_total_'.$user_id)??0,
            'today_income_total'      =>  cache('user_today_income_total_'.$user_id)??0,
            'promotion_income_total'      =>  cache('user_promotion_income_total_'.$user_id)??0,
            'consume_total'     =>  Db::name('user_extend')->where('user_id',$user_id)->value('sales'),//cache('team_consume_total_'.$user_id)??0,//团队总业绩
            'user_sales_reward'     =>  cache('user_sales_reward_'.$user_id)??0,//销售奖
            'user_output_reward'     =>  cache('user_output_reward_'.$user_id)??0,//产值奖
            'user_withdrawl_reward'     =>  cache('user_withdrawl_reward'.$user_id)??0,//提现奖
            'user'              =>  $user[0],
            
        ];
        return $this->success(__('successful'),$result);

    }

    /**
     * @Apidoc\Title("团队列表")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("page", type="int",require=false, desc="页码")
     * @Apidoc\Param("limit", type="int",require=false, desc="分页大小")
     */
    public function list(Request $request){
        $user = \support\Jwt::getUser();
        $limit = $request->get('limit',10);
        $page = $request->get('page',1);
        $kw = $request->get('kw');

        // 假设 $user_id 是要查询的用户 ID
        // $user = User::find($user['id']);  // 查询用户对象

        // // 获取该用户的下属团队
        // $teamMembers = $user->team()
        //     ->where('status', 1)  // 只查询有效的下属
        //     ->with('user')  // 联合查询 User 模型，获取下属的详细信息
        //     ->order('depth')  // 按照层级深度排序
        //     ->select();

        // foreach ($teamMembers as $member) {
        //     echo '下属用户ID: ' . $member->descendant_id . '，层级深度: ' . $member->depth . '，状态: ' . $member->status . '，用户名: ' . $member->user->name . '，邮箱: ' . $member->user->email . "\n";
        // }
        // return $this->success(__('successful'),$result);


        // $model = Db::name('user_team')
        //     ->alias('ut')
        //     ->join('user wu', 'ut.descendant_id = wu.id')
        //     ->where('ut.ancestor_id', $user['id'])
        //     ->where('ut.depth', '<=', 3) // 限制三级内
        //     ->field('wu.id, wu.username, wu.group, ut.depth')
        //     ->order('ut.depth ASC, wu.username ASC');

        // if($limit == 'all' || $limit >= 999999){
        //     $result = $model->select();
        // }else{
        //     // 分页处理
        //     $result = $model->page($page, $limit)->select();
        //     $total = $model->count(); // 获取总记录数
        //     $result->each(function ($item) {
        //         //cache_add('user_recharge_total_'.$item['id'],1);
        //         //cache_add('user_withdrawl_total_'.$item['id'],1);
        //         //cache_add('user_income_total_'.$item['id'],1);
        //         $item['avatar'] = cdnurl($item['avatar'] ?: '/storage/avatar/default.png');  
        //         $item['recharge_total'] = cache('user_recharge_total_'.$item['id']);
        //         $item['withdrawl_total'] = cache('user_withdrawl_total_'.$item['id']);
        //         $item['income_total'] = cache('user_income_total_'.$item['id']);
        //         $item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
        //         return $item;
        //     });
        //     $result = [
        //         'data' => $result,
        //         'total' => $total,
        //         'current_page' => $page,
        //         'last_page' => ceil($total / $limit),
        //         'per_page' => $limit,
        //     ];
        // }

        $user_id = \support\Jwt\JwtToken::getCurrentId();
        $model = UserModel::alias('u') 
            ->where('parent_id',$user_id)
            ->join('user_extend ue', 'u.id = ue.user_id')
            ->where('u.parent_id', $user['id'])
            //->where('ue.active', 1)
            ->field('u.id, u.username,u.money,u.score,u.role_id, u.group,u.avatar, u.created_at')
            ->order('u.created_at desc');
        if($kw){
            $model = $model->whereLike("u.username",'%'.$kw.'%');
        }

        if($limit == 'all' || $limit >= 999999){
            $result = $model->select();
            // $result = [
            //     'data' => $result,
            //     'total' => count($result),
            //     'current_page' => 1,
            //     'last_page' => 1,
            //     'per_page' => count($result),
            // ];
            $result= \think\Paginator::make($result, 99999999999, 1, count($result));
        }else{
            $result = $model->paginate($limit);
        }
        $role_arr = [
            '0' =>  __('普通用户'),
            '1' =>  __('V1'),
            '2' =>  __('V2'),
            '3' =>  __('V3'),
            '4' =>  __('V4'),
            '5' =>  __('V5'),
        ];
        $result = $result->toArray();
        foreach($result['data'] as $k=>$item){
            $result['data'][$k]['avatar'] = cdnurl($item['avatar'] ?: '/storage/avatar/default.png');  
            $result['data'][$k]['recharge_total'] = cache('user_recharge_total_'.$item['id'])??0;
            $result['data'][$k]['withdrawl_total'] = cache('user_withdrawl_total_'.$item['id'])??0;
            $result['data'][$k]['withdrawl_reward'] = cache('user_withdrawl_reward_'.$item['id'])??0;
            $result['data'][$k]['income_total'] = cache('user_income_total_'.$item['id'])??0;
            $result['data'][$k]['consume_total'] = cache('user_consume_total_'.$item['id'])??0;
            $result['data'][$k]['play_count'] = cache('user_play_count_'.$item['id'])??0;
            //$result['data'][$k]['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
            $result['data'][$k]['total_count']       =  UserTeamModel::where('ancestor_id',$item['id'])->where('status',1)->where('depth','>',0)->count('descendant_id');
            $result['data'][$k]['direct_total']      =  cache('team_direct_total_'.$item['id'])??0;
            $performance = get_performance($item['id']);
            $result['data'][$k]['performance_large'] = $performance[0];
            $result['data'][$k]['performance_small'] = $performance[1];
            $result['data'][$k]['role'] = isset($role_arr[$item['role_id']]) ? $role_arr[$item['role_id']] : __('普通用户');
            $result['data'][$k]['level'] = get_user_level($item['id'],$item['performance_small']);
            $result['data'][$k]['questionnaire_count'] = WorkRecordModel::where('user_id',$item['id'])->count('id');
        	$result['data'][$k]['id'] = idEncode($item['id']);
            //return $item;
        }
        return $this->success(__('successful'),$result);
    }
    /**
     * @Apidoc\Title("改变用户等级")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="string",require=false, desc="ID")
     * @Apidoc\Param("level", type="int",require=false, desc="等级")
     */
    function changelevel(Request $request){
        $user = \support\Jwt::getUser();
        $id = $request->post('id');
        $level = $request->post('level');
        $id = idDecode($id);
        if(!$id || !$level){
        	return $this->error(__('Invalid parameters'));
        }
        $child_user = UserModel::find($id);
        if(!$child_user){
        	return $this->error(__('Invalid user'));
        }
        if($child_user->parent_id!=$user->id){
        	return $this->error(__('Access denied'));
        }
        
        if($user->role_id <= $level){
        	return $this->error(__('It cannot be lower than the user\'s current level'));
        }
        if($child_user->role_id >= $level){
        	return $this->error(__('It cannot be lower than the user\'s current level'));
        }
        $child_user->role_id = $level;
        $child_user->save();
        return $this->success(__('successful'));
        
    }

}