<?php
namespace app\api\controller;
use Shopwwi\WebmanFilesystem\FilesystemFactory;
use Shopwwi\WebmanFilesystem\Facade\Storage;
use app\model\User as UserModel;
use app\model\Realname as RealnameModel;
use support\Request;
use support\Response;
use taoser\facade\Validate;
use support\think\Db;
use hg\apidoc\annotation as Apidoc;

/**
 * 用户相关
 */
class UserController extends BaseController{
    /**
     * 不需要鉴权的方法
     * @var array
     */
    public $noNeedAuth = ['*'];

    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    public $noNeedLogin = [];
    /**
     * @Apidoc\Title("个人资料")
     * @Apidoc\Method("GET")
     * @Apidoc\Desc("GET为获取用户信息,POST为修改数据")
     * @Apidoc\Param("nickname", type="string",require=true, desc="昵称")
     */
    public function profile(){
        $data = \support\Jwt::getUser();
        if(Request()->method() == 'POST'){
            $nickname = input('nickname');
            $gender = input('gender',null);
            $faceURL = input('faceURL',null);
            $birth = input('birth',null);
            $save_data =[];
            if($nickname){
                $save_data['nickname'] = $nickname;
            }
            if($gender){
                $save_data['sex'] = $gender;
            }
            if($faceURL){
                $save_data['avatar'] = $faceURL;
            }
            if($birth){
                $save_data['birthday'] = datetime($birth/1000,'Y-m-d');
            }
            if(!empty($save_data)){
                \support\Jwt::getUser()->save($save_data);
            }
            return $this->success(__('successful'));
        }
        $data= Hook('user.profile',$data);
        return $this->success(__('successful'),$data[0]);
    }
    /**
     * @Apidoc\Title("修改密码")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("password", type="string",require=true, desc="旧密码")
     * @Apidoc\Param("newpassword", type="string",require=true, desc="新密码")
     * @Apidoc\Param("renewpassword", type="string",require=true, desc="新密码")
     */
    public function change_password(){
        $password = input('password');
        $newpassword = input('newpassword');
        $renewpassword = input('renewpassword');
        if (!$password || !$newpassword || !$renewpassword) {
            return $this->error(__('Invalid parameters'));
        }
        if ($newpassword !== $renewpassword) {
            return $this->error(__('Invalid parameters'));
        }
        try{
            \support\Jwt::changepwd($newpassword,$password);
            return $this->success(__('Reset password successful'));
        } catch (\Throwable $e) {
            return $this->error($e->getMessage());
        }
    }
    /**
     * 修改交易密码
     * @Apidoc\Method("POST")
     * @Apidoc\Param("password", type="string",require=true, desc="旧密码(新设时可用为空)")
     * @Apidoc\Param("newpassword", type="string",require=true, desc="新密码")
     * @Apidoc\Param("renewpassword", type="string",require=true, desc="新密码")
     */
    public function change_trade_password(){
        $password = input('password');
        $newpassword = input('newpassword');
        $renewpassword = input('renewpassword');
        if (!$newpassword || !$renewpassword || $newpassword !== $renewpassword) {
            return $this->error(__('Invalid parameters'));
        }
        try{
            \support\Jwt::change_trade_pwd($newpassword,$password);
            return $this->success(__('Reset trade password successful'));
        } catch (\Throwable $e) {
            return $this->error($e->getMessage());
        }
    }
    /**
     * 根据关键字查询用户列表
     * @Apidoc\Method("POST")
     * @Apidoc\Param("kw", type="string",require=true, desc="关键字")
     */
    function getuserlist(){
        $kw = Input('kw');
        $user_id = \support\Jwt\JwtToken::getCurrentId();
        $list = [];
        if($kw){
            //$list = User::where('id','<>',\support\Jwt\JwtToken::getCurrentId())->whereLike('nickname|username|email','%'.$kw.'%')->limit(0,10)->order('id asc')->field('id,username')->select();
            
            //$list = User::where('id','<>',\support\Jwt\JwtToken::getCurrentId())->whereLike('username','%'.$kw.'%')->limit(0,10)->order('id asc')->field('id,username,username as name')->select();
            $list = UserModel::whereLike('username','%'.$kw.'%')->where('id','<>',$user_id)->limit(0,10)->order('id asc')->field('id,username,username as name')->select();
            // foreach($list as $k=>$v){

            // }
        }
        
        return $this->success(__('successful'),$list);
    }
    /**
     * 头像上传
     * @Apidoc\Method("POST")
     * @Apidoc\Param("file", type="File", require=true, desc="文件")
     */
    public function avatar(Request $request)
    {
        //单文件上传
        $file = $request->file('file0');
        try {
            $result = Storage::adapter('public')->path('upload/avatar')->size(1024*1024*5)->extYes(['image/jpeg','image/png'])->processUpload($file,function ($image){
                $image->resize(200,200);
                return $image;
            },true);
            \support\Jwt::getUser()->save([
                'avatar' => '/'.$result->file_name, 
            ]);
            //$result->ss = cdnurl($result->url);
            //P($result);
            return $this->success(__('successful'),$result);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    function realname(Request $request): Response
    {
        /**
         * @var UserModel $user
         */
        $user = \support\Jwt::getUser();
        if($request->method() == 'POST'){
            $data = [
                'realname'  =>  Input('realname'),
                'idcard'  =>  Input('idcard'),
                'user_id'   =>  $user->id,
            ];
            log_alert($data);
            if(!$data['realname'] || !$data['idcard']){
                return $this->error(__('Incoret param'));
            }
            if($user->realname_verify == 1){
                return $this->error(__('You have verified'));
            }
            if(RealnameModel::where('idcard',$data['idcard'])->where('user_id','<>',$user->id)->count()){
                return $this->error(__('ID card already exists'));
            }
            Db::startTrans();
            try {
                RealnameModel::create($data);
                $user->realname_verify = 1;
                $user->save();
                if($user->parent_id && cache('invite_'.$user->parent_id.'_'.date('Ymd')) < 1){
                    \app\model\User::currency1($user->parent_id,40,\app\enum\BalanceType::INVITE_NEW_USER);
                    cache('invite_'.$user->parent_id.'_'.date('Ymd'),1);
                }
                Db::commit();
                return $this->success('ok',$user);
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error(__($e->getMessage()));
            }
        }else{
            $user->realname = RealnameModel::where('user_id',$user->id)->find();
            return $this->success('ok',$user);
        }
    }
    /**
     * find
     * @Apidoc\Method("POST")
     * @Apidoc\Param("userIDs", type="array", require=true, desc="userIDs")
     */
    function find(Request $request): Response
    {
        $userIDs = Input('userIDs');
        //$res = $request->IM->user->getUsersInfo($userIDs);
        $list = Db::name('user')->
            whereIn('id',$userIDs)
            ->paginate(Input('limit',10));
        $list->each(function($user){
            unset($user['password']);
            unset($user['trade_password']);
            //unset($user['avatar']);
            unset($user['online']);
            unset($user['token']);
            unset($user['prev_time']);
            unset($user['loginfailure']);
            unset($user['successions']);
            unset($user['maxsuccessions']);
            unset($user['currency1']);
            unset($user['currency2']);
            unset($user['currency3']);
            unset($user['currency4']);
            unset($user['currency5']);
            unset($user['currency6']);
            unset($user['currency7']);
            unset($user['currency8']);
            unset($user['currency9']);
            return $user;
            //$user->hidden(['password']);
        });

        return $this->success('ok',$list);
    }
    /**
     * search
     * @Apidoc\Method("POST")
     * @Apidoc\Param("keyword", type="string", require=true, desc="关键字")
     * @Apidoc\Param("searchtype", type="string", require=true, desc="搜索类型")
     */
    function search(Request $request): Response
    {
        $keyword = Input('keyword');
        $searchtype = Input('searchtype');
        $fields = 'id,avatar,username,nickname,avatar,sex,email,mobile,birthday,bio';
        $model = Db::name('user')->field($fields)->where('status',1);
        if($searchtype =='id'){
            $model = $model->where('id',$keyword);
        }else{
            $model = $model->whereLike('username','%'.$keyword.'%');
        }
        $list = $model->paginate(Input('limit',10));
        return $this->success('ok',$list);
    }
}