<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use fast\Tree;
use think\Validate;
use think\Db;
use addons\third\model\Third;
use app\api\model\Realname;
use app\api\model\UserKeyword;
use app\common\controller\Wechat;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','get_session_key','authority','getPhoneNumber','workSubsidyContent','recruitSubsidyContent'];
    protected $noNeedRight = '*';

    // 用户列表
    public $user_list = [];
    // 可查看几级下级
    public $lower_num = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * @ApiWeigh    (99)
     * @ApiTitle    (劳务管理-个人信息)
     * @ApiSummary  (劳务管理-个人信息)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1606137472",
        "data": {
            "user": { //用户信息
                "id": 1, //用户ID
                "nickname": "admin", //昵称
                "mobile": "13888888888", //手机号
                "avatar": "/uploads/20201123/8894d62100f2f920ffb2f38063b63f2d.jpg", //原始头像地址
                "is_work": "0", //是否在职:0=否,1=是
                "work_subsidy": "2.00", //工时补贴价格(元/时)
                "work_subsidy_month": "600.00", //工时月工资(元/月)
                "recruit_subsidy_month": "300.00", //招聘月工资(元/月)
                "url": "/u/1",
                "realname_status": "0",  // 实名认证状态:-1=未申请,0=申请中,1=通过,2=未通过
                "full_avatar": "http://www.recruit.top/uploads/20201123/8894d62100f2f920ffb2f38063b63f2d.jpg", //完整头像地址
            },
            "recruit_subsidy": {
                "hour": "1.00", //招聘补贴价格(元/时)
                "day": "10.00", //招聘补贴价格(元/天)
                "month": "300.00" //招聘补贴价格(元/月)
            }
        }
    })
     */
    public function index()
    {
        $user = $this->auth->getUser();
        // 格式化头像
        $user->full_avatar = cdnurl($user->avatar,true);
        // 实名认证状态
        $realname = Realname::get(['user_id'=>$this->auth->id]);
        $user->realname_status = empty($realname) ? '-1' : $realname['status'];
        $user->visible(['id','avatar','nickname','mobile','is_work','work_subsidy','work_subsidy_month','recruit_subsidy_month'])->append(['realname_status','full_avatar']);
        // 招聘补贴
        $recruit_subsidy = [
            'hour' => sprintf("%.2f",config('site.recruit_subsidy')),
            'day' => sprintf("%.2f",config('site.recruit_subsidy') * 10),
            'month' => sprintf("%.2f",config('site.recruit_subsidy') * 10 * 30),
        ];
        $this->success('成功', compact('user','recruit_subsidy'));
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * @ApiWeigh    (97)
     * @ApiTitle    (编辑资料)
     * @ApiSummary  (编辑资料)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="avatar", type="string", required=false, description="头像")
     * @ApiParams (name="nickname", type="string", required=false, description="昵称")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1604282876",
        "data": null
    })
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->param('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $nickname = $this->request->param('nickname');
        if(!$avatar && !$nickname){
            $this->error('修改内容不合法');
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiWeigh    (95)
     * @ApiTitle    (实名认证)
     * @ApiSummary  (实名认证)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="realname", type="string", required=true, description="姓名")
     * @ApiParams   (name="idcard", type="string", required=true, description="身份证号")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="idcard_front", type="string", required=true, description="上传身份证正面")
     * @ApiParams   (name="idcard_back", type="string", required=true, description="上传身份证反面")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": null
    })
     */
    public function realname()
    {
        $post = $this->request->param();
        empty($post['realname']) && $this->error('请填写姓名');
        empty($post['idcard']) && $this->error('请填写身份证号');
        empty($post['realname']) && $this->error('请填写姓名');
        empty($post['mobile']) && $this->error('请填写手机号');
        empty($post['idcard_front']) && $this->error('请上传身份证正面');
        empty($post['idcard_back']) && $this->error('请上传身份证反面');
        $realname = Realname::get(['user_id'=>$this->auth->id]);
        if(empty($realname)){
            $realname = new Realname;
        }
        $realname->allowField(true)->save(array_merge([
            'user_id' => $this->auth->id,
            'status' => '0'
        ],$post));
        $this->success('提交申请成功');
    }

    /**
     * @ApiWeigh    (93)
     * @ApiTitle    (code获取session_key和openid)
     * @ApiSummary  (code获取session_key和openid)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="小程序code")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "session_key": "1qyMwZRVdlBmQLwRYtYSgA==",
            "token": "9e4648c7-c640-4e41-b758-dd1a8ef7a7ae",
        }
    })
     */
    public function get_session_key()
    {
        $param = $this->request->param();
        $validate = new \think\Validate([
            'code' => 'require'
        ]);
        $validate->message([
            'code.require' => 'code参数错误!'
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 获取小程序配置
        $app = Wechat::miniProgram();
        $sessionKey = $app->auth->session($param['code']);
        if(empty($sessionKey['session_key'])) {
            $this->error($sessionKey['errmsg']);
        }
        // 判断用户是否授权
        $where = [
            'openid' => $sessionKey['openid']
        ];
        $user = Third::where($where)->find();
        $sessionKey['token'] = '';
        if($user) {
            $this->auth->direct($user['user_id']);
            $sessionKey['token'] = $this->auth->getToken();
        }
        $this->success('成功',$sessionKey);
    }

    /**
     * @ApiWeigh    (91)
     * @ApiTitle    (用户授权登录)
     * @ApiSummary  (用户授权登录)
     * @ApiMethod   (POST)
     * @ApiParams   (name="sessionKey", type="string", required=true, description="小程序sessionKey")
     * @ApiParams   (name="iv", type="string", required=true, description="小程序iv")
     * @ApiParams   (name="encryptData", type="string", required=true, description="小程序encryptData")
     * @ApiParams   (name="user_id", type="inter", required=false, description="扫码获取的用户ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "token": "9e4648c7-c640-4e41-b758-dd1a8ef7a7ae",
        }
    })
     */
    public function authority()
    {
        $param = $this->request->param();
        $validate = new \think\Validate([
            'sessionKey' => 'require',
            'iv' => 'require',
            'encryptData' => 'require'
        ]);
        $validate->message([
            'sessionKey.require' => 'sessionKey参数错误!',
            'iv.require' => 'iv参数错误!',
            'encryptData.require' => 'encryptData参数错误!'
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 获取小程序配置
        $app = Wechat::miniProgram();
        $user_info = $app->encryptor->decryptData($param['sessionKey'], $param['iv'], $param['encryptData']);
        // 判断用户是否授权
        $user_model = new \app\common\model\User();
        $where = [
            'openid' => $user_info['openId']
        ];
        $third = Third::where($where)->find();
        Db::startTrans();
        try {
            if($third) {
                $ip = request()->ip();
                $time = time();
                // 更新用户信息
                $user = $user_model->get($third['user_id']);
                // 账号被删除重新添加
                if(!$user){
                    $user = $user_model;
                    $user->id = $third['user_id'];
                    $user->nickname = $user_info['nickName'];
                    $user->avatar = $user_info['avatarUrl'];
                    $user->status = 'normal';
                    $user->joinip = $ip;
                    $user->jointime = $time;
                    $user->pid = $this->model->get($param['user_id']) ? $param['user_id'] : 0; //上级ID
                }
                // 更新信息
                if(!empty($user_info['avatarUrl']) && empty($user['avatar'])){
                    $user->avatar = $user_info['avatarUrl'];
                }
                $user->gender = $user_info['gender'] == 2 ? 0 : $user_info['gender'];
                $user->logintime = $time;
                $user->loginip = $ip;
                $user->prevtime = $time;
                $result = $user->save();
                $user_id = $third['user_id'];
            } else {
                $ip = request()->ip();
                $time = time();
                $user_insert = [
                    'nickname' => $user_info['nickName'],
                    'gender' => $user_info['gender'] == 2 ? 0 : $user_info['gender'],
                    'avatar' => $user_info['avatarUrl'],
                    'status' => 'normal',
                    'jointime' => $time,
                    'joinip' => $ip,
                    'logintime' => $time,
                    'loginip' => $ip,
                    'prevtime' => $time,
                    'pid' => $this->model->get($param['user_id']) ? $param['user_id'] : 0 //上级ID
                ];
                $result = $user_model->save($user_insert);
                $user_id = $user_model->getLastInsID();
                // 生成小程序二维码
//                $minicode = makeQrcode($user_id,'user_qrcode'.$user_id.'.png','pages/clock/clock');
//                $user_model->isUpdate(true)->save(['qrcode'=>$minicode],['id'=>$user_id]);
                $third_insert = [
                    'user_id'       => $user_id,
                    'platform'      => 'wechat',
                    'openid'        => $user_info['openId'],
                    'openname'      => isset($user_info['nickName']) ? $user_info['nickName'] : '',
                    'access_token'  => '',
                    'refresh_token' => '',
                    'expires_in'    => '',
                    'logintime'     => $time,
                    'expiretime'    => 0,
                ];
                Third::create($third_insert);
            }
            $login = $this->auth->direct($user_id);
            if(!$result || !$login) {
                Db::rollback();
                $this->error('授权登录失败');
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $return = [
            'token' => $this->auth->getUserinfo()['token']
        ];
        $this->success('授权登录成功',$return);
    }

    /**
     * @ApiWeigh    (89)
     * @ApiTitle    (用户授权获取手机号)
     * @ApiSummary  (用户授权获取手机号)
     * @ApiMethod   (POST)
     * @ApiParams   (name="sessionKey", type="string", required=true, description="小程序sessionKey")
     * @ApiParams   (name="iv", type="string", required=true, description="小程序iv")
     * @ApiParams   (name="encryptData", type="string", required=true, description="小程序encryptData")
     * @ApiParams   (name="openid", type="string", required=true, description="openid")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "phoneNumber": "13580006666", //用户绑定的手机号(国外手机号会有区号)
            "purePhoneNumber": "13580006666", //没有区号的手机号
            "countryCode": "86", //区号
            "watermark": {
                "appid": "APPID",
                "timestamp": TIMESTAMP
            }
        }
    })
     */
    public function getPhoneNumber()
    {
        $param = $this->request->param();
        $validate = new \think\Validate([
            'sessionKey' => 'require',
            'iv' => 'require',
            'encryptData' => 'require',
            'openid' => 'require'
        ]);
        $validate->message([
            'sessionKey.require' => 'sessionKey参数错误!',
            'iv.require' => 'iv参数错误!',
            'encryptData.require' => 'encryptData参数错误!',
            'openid.require' => 'openid参数错误!'
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 获取小程序配置
        $app = Wechat::miniProgram();
        $data = $app->encryptor->decryptData($param['sessionKey'], $param['iv'], $param['encryptData']);
        // 新用户绑定手机号
        $third = Third::where('openid',$param['openid'])->find();
        if(!empty($data['phoneNumber']) && $third){
            Db::name('user')->where('id',$third['user_id'])->update(['mobile'=>$data['phoneNumber']]);
        }
        $this->success('授权成功',$data);
    }

    /**
     * @ApiWeigh    (87)
     * @ApiTitle    (工时补贴介绍)
     * @ApiSummary  (工时补贴介绍)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
        "code": 1,
        "msg": "成功",
        "time": "1606124276",
        "data": "<p>工时补贴富文本详情介绍</p>" //工时补贴介绍
    })
     */
    public function workSubsidyContent()
    {
        $this->success('成功',config('site.work_subsidy_content'));
    }

    /**
     * @ApiWeigh    (85)
     * @ApiTitle    (招聘补贴介绍)
     * @ApiSummary  (招聘补贴介绍)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
        "code": 1,
        "msg": "成功",
        "time": "1606124276",
        "data": "<p>招聘补贴富文本详情介绍</p>" //招聘补贴介绍
    })
     */
    public function recruitSubsidyContent()
    {
        $this->success('成功',config('site.recruit_subsidy_content'));
    }

    /**
     * @ApiWeigh    (85)
     * @ApiTitle    (分享)
     * @ApiSummary  (分享)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的token")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "url": "http://www.recruit.top/uploads/job/1.png", //职位海报地址
        }
    })
     */
    public function userPoster()
    {
        $user = \app\api\model\User::get($this->auth->id);
        empty($user['avatar']) && $this->error('请先上传头像');
        !url_exists($user['avatar']) && $this->error('头像失效,请更新头像');
        // 本地路径
        $dir = 'uploads/user';
        if (!file_exists($dir)){
            mkdir($dir,0777,true);
        }
        
        // 用户小程序码
        $qrcode = $dir.'/qrcode_'.$user['id'].'.png';
        if(!file_exists($qrcode)){
            $response = Wechat::miniProgram()->app_code->getUnlimit($user['id'], [
                'page'  => 'pages/indexone/indexone',
                'width' => 280, //最小宽度280
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs($dir, str_replace($dir.'/','',$qrcode));
            }
            // 280不满足,再缩小
            \think\Image::open($qrcode)->thumb(169,169,\think\Image::THUMB_CENTER)->save($qrcode);
        }

        //将用户头像保存到本地
        $avatar = $dir.'/avatar_'.$user['id'].'.png';
        file_put_contents($avatar,file_get_contents($user['avatar']));
        \think\Image::open($avatar)->thumb(64,64,\think\Image::THUMB_CENTER)->save($avatar);
        createRoundImg($avatar);

        $path_ttf = ROOT_PATH.'public/assets/fonts/PingFang.ttf';
        $filename = $dir.'/'.$user['id'].'.png';

        $image = \think\Image::open(ROOT_PATH.'public/assets/img/miniProgram/user_back.png');
        // 昵称居中
        $nickname = $user['nickname'];
        $size = 12;
        $box1 = imagettfbbox($size, 0, $path_ttf, $nickname);
        $box1_minx = min($box1[0], $box1[2], $box1[4], $box1[6]);
        $box1_maxx = max($box1[0], $box1[2], $box1[4], $box1[6]);
        /* 计算文字初始坐标和尺寸 */
        $w = $box1_maxx - $box1_minx;
        $box1_minx += ($image->width() - $w) / 2;
        $image->water($avatar,[156,52])
            ->text($nickname,$path_ttf,$size,'#020202',[$box1_minx,131])
            ->water($qrcode,[103,181])
            ->save($filename);
        $url = request()->domain().'/'.$filename.'?v='.time();
        $this->success('成功',compact('url'));
    }

    /**
     * @ApiWeigh    (83)
     * @ApiTitle    (下级)
     * @ApiSummary  (下级)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiParams   (name="is_work", type="string", required=false, description="是否在职:0=否,1=是")
     * @ApiParams   (name="keyword", type="string", required=false, description="关键字搜索")
     * @ApiReturn   ({
        "code": 1,
        "msg": "成功",
        "time": "1606359935",
        "data": {
            "total": 2, //总人数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{
                "id": 3, //用户ID
                "nickname": "admin2", //昵称
                "mobile": "13888888888", //手机号
                "avatar": "http://www.recruit.top/uploads/20201123/8894d62100f2f920ffb2f38063b63f2d.jpg", //头像
                "is_work": "0", //是否在职
                "is_complete": "0", //补贴是否完成:0=否,1=是
            }]
        }
    })
     */
    public function lowerList()
    {
        $user = $this->auth->getUser();
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $is_work = $this->request->param('is_work'); //是否在职:0=否,1=是
        $keyword = $this->request->param('keyword');
        $this->user_list = $this->model->where('status','normal')->field('id,pid')->select();
        $this->lower_num = $user['lower_num'];
        $childrenIds = $this->getChildrenIds($user['id']);
        $where['id'] = ['in',$childrenIds];
        if($is_work != ''){
            $where['is_work'] = $is_work;
        }
        // 关键字
        if(!empty($keyword)){
            // 记录搜索关键词
            if($this->auth->id){
                $has = UserKeyword::where('user_id',$this->auth->id)
                    ->where('keyword',$keyword)
                    ->find();
                if(!$has){
                    $keyword_list = UserKeyword::order('createtime asc')->select();
                    // 超过10条的删除
                    if(count($keyword_list) > 10){
                        UserKeyword::where('id',$keyword_list[0]['id'])->delete();
                    }
                    UserKeyword::create([
                        'user_id' => $this->auth->id,
                        'keyword' => $keyword
                    ]);
                }else{
                    $has->updatetime = time();
                    $has->save();
                }
            }
            $where['nickname'] = ['like','%'.$keyword.'%'];
        }
        $data = $this->model
            ->where($where)
            ->order('createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                if(Validate::regex($v['mobile'], "^1\d{10}$")){
                    $v['mobile'] = substr_replace($v['mobile'],'*****',3,5);
                }
                $v->visible(['id','avatar','nickname','is_work','mobile','is_complete']);
            })->toArray();
        $this->success('成功',$data);
    }

    /**
     * @ApiWeigh (81)
     * @ApiTitle    (搜索历史)
     * @ApiSummary  (搜索历史)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=false, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1606218663",
        "data": [ //关键词
            "nihao"
        ]
    })
     */
    public function keywordList()
    {
        $list = UserKeyword::where('user_id',$this->auth->id)
            ->order('updatetime desc')
            ->limit(10)
            ->column('keyword');
        $this->success('成功',$list);
    }

    /**
     * @ApiWeigh (79)
     * @ApiTitle    (搜索历史-清空)
     * @ApiSummary  (搜索历史-清空)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=false, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1601351666",
        "data": null
    })
     */
    public function keywordClear()
    {
        UserKeyword::where('user_id',$this->auth->id)->delete();
        $this->success('清空搜索历史成功');
    }

    /**
     * @ApiWeigh    (77)
     * @ApiTitle    (下级的下级)
     * @ApiSummary  (下级的下级)
     * @ApiMethod   (POST)
     * @ApiParams   (name="user_id", type="inter", required=true, description="下级ID")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiParams   (name="is_work", type="string", required=false, description="是否在职:0=否,1=是")
     * @ApiReturn   ({
        "code": 1,
        "msg": "成功",
        "time": "1606216278",
        "data": {
            "user": { //下级用户信息
                "id": 1, //ID
                "nickname": "admin", //昵称
                "mobile": "13888888888", //手机号
                "avatar": "http://www.recruit.top/uploads/20201123/8894d62100f2f920ffb2f38063b63f2d.jpg", //头像
                "is_work": "0", //是否在职:0=否,1=是
                "is_complete": "0", //补贴是否完成:0=否,1=是
            },
            "list": { //下级的下级
                "total": 3, //总数据
                "per_page": 15,
                "current_page": 1,
                "last_page": 1,
                "data": [{ //下级的下级用户信息
                    "id": 2, //用户ID
                    "nickname": "admin1", //昵称
                    "mobile": "300.00", //手机号
                    "avatar": "", //头像
                    "is_work": "1", //是否在职:0=否,1=是
                    "is_complete": "0", //补贴是否完成:0=否,1=是
                }]
            }
        }
    })
     */
    public function lowersList()
    {
        $user_id = $this->request->param('user_id');
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $is_work = $this->request->param('is_work'); //是否在职:0=否,1=是
        $this->user_list = $this->model->where('status','normal')->field('id,pid')->select();
        empty($user_id) && $this->error('缺少必需参数');
        $user = $this->model->get($user_id);
        empty($user) && $this->error('下级用户信息不存在');
        $this->lower_num = $user['lower_num'];
        $childrenIds = $this->getChildrenIds($user['id']);
        $where['id'] = ['in',$childrenIds];
        if($is_work != ''){
            $where['is_work'] = $is_work;
        }
        $list = $this->model
            ->where($where)
            ->order('createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                if(Validate::regex($v['mobile'], "^1\d{10}$")){
                    $v['mobile'] = substr_replace($v['mobile'],'*****',3,5);
                }
                $v->visible(['id','avatar','nickname','is_work','mobile','is_complete']);
            })->toArray();
        if(Validate::regex($user['mobile'], "^1\d{10}$")){
            $user['mobile'] = substr_replace($user['mobile'],'*****',3,5);
        }
        $user->visible(['id','avatar','nickname','is_work','mobile','is_complete']);
        $this->success('成功',compact('user','list'));
    }

    /**
     * 读取指定节点的所有孩子节点ID
     * @param int     $myid     节点ID
     * @param int $level 可以查看几级子级
     * @return array
     */
    private function getChildrenIds($myid,$level = 1)
    {
        if($level > $this->lower_num){
            return [];
        }
        $newarr = [];
        foreach ($this->user_list as $value) {
            if (!isset($value['id'])) {
                continue;
            }
            if ($value['pid'] == $myid) {
                $newarr[] = $value['id'];
                $newarr = array_merge($newarr, $this->getChildrenIds($value['id'],$level+1));
            }
        }
        return $newarr;
    }
}