<?php
namespace app\api\controller;
use support\Request;
use support\Response;
use support\think\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * 用户角色
 */
class RoleController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = ['recent'];
    
    /**
     * @Apidoc\Title("当前角色信息")
     * @Apidoc\Method("GET")
     */
    function detail(){
        $user = \support\Jwt::getUser();
        $data = \app\model\UserRole::where('id',$user->role_id)->field('name,id,price')->find();
        return $this->success(__('successful'),$data);
    }
    /**
     * @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');

        $model = \app\model\UserRole::where('id','>',0)->field('id,name,price')
            ->order('id asc');

        if($limit == 'all' || $limit >= 999999){
            $result = $model->select();
            $result= \think\Paginator::make($result, 99999999999, 1, count($result));
        }else{
            $result = $model->paginate($limit);
        }
        return $this->success(__('successful'),$result);
    }

    /**
     * @Apidoc\Title("最近购买列表")
     * @Apidoc\Method("GET")
     */
    public function recent(Request $request){
        $list = (new \app\model\BalanceLog)->setSuffix('_money')->where('type',\app\enum\BalanceType::PURCHASE_ROLE->value)
            ->order('created_at','desc')->limit(0,10)->field('user_id,created_at,memo')->select();
        $list = $list->toArray();
        $data = [];
        $role_list = \app\model\UserRole::where('id', '>',1)
            ->column('name','id');
        foreach($list as $v){
            $data[] = [
                'username'  =>  \app\model\User::where('id',$v['user_id'])->value('username'),
                'created_at' => $v['created_at'],
                'v' =>  $v,
                //'role'  =>  $role_list[str_replace('购买用户组:','',$v['memo'])]
                'role'  =>  'K'.str_replace('购买用户组:','',$v['memo'])
            ];
        }
        return $this->success(__('successful'),$data);
    }

    /**
     * @Apidoc\Title("购买")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("role_id", type="string",require=true, desc="要购买的角色ID")
     * @Apidoc\Param("trade_password", type="string",require=true, desc="交易密码")
     */
    function buy(Request $request): Response{
        $user = \support\Jwt::getUser();
        $role_id = (int)$request->post('role_id');
        if($user->role_id > $role_id){
            return $this->fail(__('Your level is too high to purchase this character'));
        }
        if(abs($role_id - $user->role_id) !== 1 && $role_id !==6){
            return $this->fail(__('Your level is too high to purchase this character'));
        }
        $role = \app\model\UserRole::where('id',$role_id)->find();
        if(!$role){
            return $this->fail(__('Role does not exist'));
        }
        if($role->price <=0){
            return $this->fail(__('This character group is not allowed to be sold'));
        }
        if($user->money < $role->price){
            return $this->fail(__('Insufficient balance'));
        }
        \support\Jwt::verify_trade_password($request->post('trade_password'));
        $amount = $role->price;
        $power = bcmul($amount,config('site.suanli_rate'),4);
        \app\model\User::where('id',$user->id)->save(['role_id'=>$role_id]);
        \app\model\User::money($user->id,-$amount,\app\enum\BalanceType::PURCHASE_ROLE,'购买用户组:'.$role_id);
        \app\model\User::score($user->id,$power,\app\enum\BalanceType::POWER_ADD,'购买用户组:'.$role_id);
        
        cache_add('user_power_total_'.$user->id,$power);
        Hook('user.roleup', $user);
        $data = [
            'role_id'   => $role_id,
            'user_id'   => $user->id,
            'parent_id' => $user->parent_id,
            'amount'    => $amount,
        ];
        Hook('role.buy', $data);
        return $this->success(__('successful'));
    }
}