<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-25 17:23
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace app\api\controller\v1;

use app\BaseController;
use app\model\api\Member;
use app\model\Api\SiteProduct;
use app\model\api\SmsYzm;
use app\Request;
use library\services\UtilService;
use library\utils\AdvertUtils;
use library\utils\Icon;
use library\utils\Sms;
use think\facade\Db;

class Login extends BaseController
{

    public function aaa(){
        $icon = new Icon;
        $icon->mkIcon(app()->getRootPath().'public/1.png');
    }

    /**
     * 登录中心
     * @param Request $request
     */
    public function l(Request $request) {
      [$userName,$passWord]  = UtilService::getMore([
            ['userName','','empty','请输入账户账号'],
            ['passWord','','empty','请输入登录密码']
        ],$request,true);
        //获取登录
        $meberInfo = Member::login($userName,$passWord,$request->site['sassid']);
        if(empty($meberInfo)) {
            return app('json')->fail(Member::getErrorInfo('用户名错误，请重新输入'));
        }

        //生成令牌
        $token = Member::createToken($meberInfo, $request->site['secret_key']);
        if(empty($token)) {
            return app('json')->fail(Member::getErrorInfo());
        }

        Member::where('uid',$meberInfo['uid'])->save(['lasttime'=>time()]);
        $data['uid'] = $meberInfo['uid'];
        $data['ip'] = $request->ip();
        $data['time'] = time();
        Db::name("login_record")->insert($data);
        return app('json')->success([
            'token' => $token,
            'user_info' => [
                'mobile'      => $meberInfo->getData('mobile'),
                'name'      => $meberInfo->getData('name'),
                'avatar'    => $meberInfo->getData('avatar'),
                'money'     => $meberInfo->getData('money'),
                'openid'     => $meberInfo->getData('openid')
            ],
        ]);
    }

    /**
     * 注册1号
     * @param Request $request
     */
    public function reg1(Request $request) {
        [$mobile,$yzm]  = UtilService::getMore([
            ['mobile','','empty','请输入手机号码'],
            ['yzm','']
        ],$request,true);
        //判断验证码
        $bool = (new SmsYzm)->VerCode($mobile,$yzm,'yzm',$request->site['sassid']);
        if(!$bool) {
            return app('json')->fail(SmsYzm::getErrorInfo("验证码错误"));
        }
        //判断是否被注册了
        $count = (new Member)->where('mobile',$mobile)->where('sassid',$request->site['sassid'])->count();
        if($count > 0) {
            return app('json')->fail("用户已经被注册，请勿重复操作!");
        }
         //生成MD5
        $param = ['mobile'=>$mobile,'sassid'=>$request->site['sassid'],'time'=>time()];
        $secret_key = $request->site['secret_key'];
        $token =base64_encode( @crypto_encrypt(json_encode($param), $secret_key));
        return app('json')->success([
            'token' => $token
        ]);
    }


    /**
     * 注册2
     * @param Request $request
     */
    public function reg2(Request $request) {
        $post  = UtilService::getMore([
            ['token','','empty','参数错误'],
            ['password','','empty','请输入正确的密码'],
            ['nickname',''],
            ['avatar',''],
            ['tjUid',''],
            ['weixin_name','']
        ],$request);

        $time = time();
        $secret_key = $request->site['secret_key'];
        $tokenData = @json_decode(@crypto_decrypt(base64_decode($post['token']), $secret_key),true);
        //注册token大于30分钟或者超过30分钟
        if(empty($tokenData) ||  ($time - $tokenData['time']) > 30 * 60){
            return app('json')->fail("注册过期,请重新注册");
        }

        //判断是否被注册了
        $count = (new Member)->where('mobile',$tokenData['mobile'])->where('sassid',$request->site['sassid'])->count();
        if($count > 0) {
            return app('json')->fail("用户已经被注册!");
        }
        //推荐码
        if(!empty($post['tjUid'])){
            $tjuid =  crypto_decrypt(base64_decode($post['tjUid']),$request->site['secret_key']);
            $save['i_uid'] = $tjuid;
        }
        $save['mobile'] = $tokenData['mobile'];
        $save['username'] = '';
        $save['password'] = md5($post['password']);
        $save['nickname'] = $post['nickname'];
        $save['name'] = '';
        $save['avatar'] = $post['avatar'];
        $save['regip'] = $request->ip();
        $save['regtime'] = $time;
        $save['lasttime'] = $time;
        $save['sassid'] = $request->site['sassid'];
        $save['weixin_name'] = $post['weixin_name'];
        $save['status'] = 1;
        $uid = (new Member)->insertGetId($save);
        $meberInfo = Member::where('uid',$uid)->find();
        //生成令牌
        $token = Member::createToken($meberInfo, $request->site['secret_key']);
        return app('json')->success([
            'token' => $token,
            'user_info' => [
                'mobile'      => $meberInfo->getData('mobile'),
                'name'      => $meberInfo->getData('name'),
                'avatar'    => $meberInfo->getData('avatar'),
                'money'     => $meberInfo->getData('money')
            ],
        ]);
    }


    public function mreg(Request $request) {
        $post  = UtilService::getMore([
            ['mobile','','empty','请输入正确的手机号码'],
            ['code','','empty','请输入正确的验证码'],
            ['passWord','','empty','请输入正确的密码'],
            ['tjUid',''],
            ['weixin','']
        ],$request);


        //判断验证码
        $bool = (new SmsYzm)->VerCode($post['mobile'],$post['code'],'yzm',$request->site['sassid']);
        if(!$bool) {
            return app('json')->fail(SmsYzm::getErrorInfo("验证码错误"));
        }
        //判断是否被注册了
        $count = (new Member)
                        ->where('mobile',$post['mobile'])
                        ->where('sassid',$request->site['sassid'])
                        ->count();
        if($count > 0) {
            return app('json')->fail("用户已经被注册，请勿重复操作!");
        }
        //推荐码
        if(!empty($post['tjUid'])){
            $tjuid =  crypto_decrypt(base64_decode($post['tjUid']),$request->site['secret_key']);
            $save['i_uid'] = $tjuid;
        }
        $time = time();
        $save['mobile'] = $post['mobile'];
        $save['username'] = '';
        $save['password'] = md5($post['passWord']);
        $save['nickname'] = '';
        $save['name'] = '';
        $save['avatar'] = '';
        $save['regip'] = $request->ip();
        $save['regtime'] = $time;
        $save['lasttime'] = $time;
        $save['sassid'] = $request->site['sassid'];
        $save['weixin_name'] = $post['weixin_name'];
        $save['status'] = 1;
        $uid = (new Member)->insertGetId($save);
        $meberInfo = Member::where('uid',$uid)->find();
        //生成令牌
        $token = Member::createToken($meberInfo, $request->site['secret_key']);
        return app('json')->success([
            'user_info' => [
                'mobile'      => $meberInfo->getData('mobile'),
                'name'      => $meberInfo->getData('name'),
                'avatar'    => $meberInfo->getData('avatar'),
                'money'     => $meberInfo->getData('money')
            ],
        ]);
    }


    /**
     * 获取验证码
     * @param Request $request
     */
    public function yzm(Request $request) {
        [$mobile,$time,$token]  = UtilService::getMore([
            ['mobile','','empty','请输入手机号码'],
            ['time',''],
            ['token','']
        ],$request,true);
        $secret_key = $request->site['secret_key'];
        $outStr = @crypto_decrypt(base64_decode($token), $secret_key);
        if($mobile != $outStr) {
            return app('json')->fail("获取验证码失败！");
        }
        $lastTime = 120;//
        $time     = time();
        $smsTime = (new SmsYzm)->where('mobile',$mobile)
                                ->where("action","yzm")
                                ->order("time desc")
                                ->value("time");
        //验证码
        if (!empty($smsTime) && abs($time - $smsTime) < $lastTime) {
            $data['status'] = 2;
            $data['time']   = $time - $smsTime;
            return app('json')->success($data);
        }
        //发送验证码
        $code = randString(6, true);
        $send = (new Sms)->SmsCode($mobile, "718562",$request->site['sassid'], array("1" => $code,"2"=>"30"));

        if ($send['status'] == 1) {
            $savedata['mobile'] = $mobile;
            $savedata['code'] = $code;
            $savedata['action'] = 'yzm';
            $savedata['time'] = time();
            $savedata['sassid'] = $request->site['sassid'];
            (new SmsYzm)->insert($savedata);
            $data['status'] = 1;
        } else {
            $data = $send;
        }
        if($data['status'] == 1) {
            return app('json')->success("发送成功", ['status'=>1,'time'=>$lastTime]);
        } else {
            return app('json')->fail($data['error']);
        }
    }

    /**
     * 忘记密码验证码
     * @param Request $request
     */
    public function forgetYzm(Request $request){
        [$mobile,$time,$token]  = UtilService::getMore([
            ['mobile','','empty','请输入手机号码'],
            ['time',''],
            ['token','']
        ],$request,true);
        $secret_key = $request->site['secret_key'];
        $outStr = @crypto_decrypt(base64_decode($token), $secret_key);
        if($mobile != $outStr) {
            return app('json')->fail("获取验证码失败！");
        }
        //count
        $count = (new Member)->where('mobile',$mobile)->where('sassid',$request->site['sassid'])->count();
        if($count <= 0) {
            return app('json')->fail("账号未注册！");
        }
        $lastTime = 120;//
        $time     = time();
        $smsTime = (new SmsYzm)->where('mobile',$mobile)
            ->where("action","forget_yzm")
            ->order("time desc")
            ->value("time");
        //验证码
        if (!empty($smsTime) && abs($time - $smsTime) < $lastTime) {
            $data['status'] = 2;
            $data['time']   = $time - $smsTime;
            return app('json')->success($data);
        }
        //发送验证码
        $code = randString(6, true);
        $send = (new Sms)->SmsCode($mobile, "718570",$request->site['sassid'], array("1" => $code));

        if ($send['status'] == 1) {
            $savedata['mobile'] = $mobile;
            $savedata['code'] = $code;
            $savedata['action'] = 'forget_yzm';
            $savedata['time'] = time();
            $savedata['sassid'] = $request->site['sassid'];
            (new SmsYzm)->insert($savedata);
            $data['status'] = 1;
        } else {
            $data = $send;
        }
        if($data['status'] == 1) {
            return app('json')->success("发送成功", ['status'=>1,'time'=>$lastTime]);
        } else {
            return app('json')->fail($data['error']);
        }
    }

    /**
     * 账号找回第一
     * @param Request $request
     */
    public function forget1(Request $request) {
        [$mobile,$yzm]  = UtilService::getMore([
            ['mobile','','empty','请输入手机号码'],
            ['yzm','']
        ],$request,true);
        //判断验证码
        $bool = (new SmsYzm)->VerCode($mobile,$yzm,'forget_yzm',$request->site['sassid']);
        if(!$bool) {
            return app('json')->fail(SmsYzm::getErrorInfo("验证码错误"));
        }
        //判断是否被注册了
        $count = (new Member)->where('mobile',$mobile)->where('sassid',$request->site['sassid'])->count();
        if($count <= 0) {
            return app('json')->fail("找不到账号!");
        }
        //生成MD5
        $param = ['mobile'=>$mobile,'sassid'=>$request->site['sassid'],'time'=>time()];
        $secret_key = $request->site['secret_key'];
        $token =base64_encode( @crypto_encrypt(json_encode($param), $secret_key));
        return app('json')->success([
            'token' => $token
        ]);
    }

    /**
     * 账号找回第二
     * @param Request $request
     */
    public function forget2(Request $request) {
        $post  = UtilService::getMore([
            ['token','','empty','参数错误'],
            ['password','','empty','请输入正确的密码']
        ],$request);
        $time = time();
        $secret_key = $request->site['secret_key'];
        $tokenData = @json_decode(@crypto_decrypt(base64_decode($post['token']), $secret_key),true);
        //注册token大于30分钟或者超过30分钟
        if(empty($tokenData) ||  ($time - $tokenData['time']) > 30 * 60){
            return app('json')->fail("操作已过期，返回重新操作");
        }
        //判断是否被注册了
        $data = (new Member)->where('mobile',$tokenData['mobile'])->where('sassid',$request->site['sassid'])->find();
        if(empty($data)) {
            return app('json')->fail("找不到账号!");
        }

        $save['password'] = md5($post['password']);
        (new  Member)->where('uid',$data['uid'])->save($save);
        return app('json')->success("找回成功！");
    }

}