<?php
// +----------------------------------------------------------------------
// | 微版本 [ windsns框架系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2010~2028 http://www.windsns.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.weinuo.net ) 常州微诺信息科技有限公司 ● 微版本开发团队
// +----------------------------------------------------------------------
// | Author: liu21st <3339882530@qq.com>
// +----------------------------------------------------------------------
// | frame: windsns框架；版权所有，侵权必究！
// +----------------------------------------------------------------------
namespace app\m\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontendwap;
use app\common\library\Ems;
use app\common\library\Sms;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use think\Db;


class User extends Frontendwap
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }


    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

  
    public function index()
    {
        $this->view->assign('title', __('User center'));
        $huihuauserid = $this->auth->getUserinfo()['user_id'];
        $winssns_nowuserid   = Db::name('user')-> where('id',$huihuauserid)->select();
        $this->assign('winssns_nowuserid', $winssns_nowuserid);
        $usercirclesum = Db::name('circlecontent')->where(['user_id' => $huihuauserid,'circle_state' => 1])->count();// 查询这个用户下所有发帖的数量
  	    $this->assign('usercirclesum', $usercirclesum);
        return $this->view->fetch();
    }


    public function register()
    {
        $url = $this->request->request('url', '');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
                } elseif ($captchaType == 'email') {
                    $captchaResult = Ems::check($mobile, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }


    public function login()
    {
        $url = $this->request->request('url', '');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'require|token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }


    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), url('user/index'));
    }


    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        
        $userid = $this->auth->getUserinfo()['user_id'];//获取这个用户的ID
        $uidinfos = Db::name('user')->where('id',$userid)->select();
        $this->assign('uidinfos', $uidinfos);
        
        return $this->view->fetch();
    }

    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }


        public function eituserinfosdo()
    {
  

        $userid = $this->auth->getUserinfo()['user_id'];//获取这个用户的ID
       $windsns_userinfoseit['username']=  input('post.username'); // 获取用户名
       
       $windsns_userinfoseita = $windsns_userinfoseit['username'];
       
       $windsns_userinfoseit['nickname']=  input('post.nickname'); // 获取昵称
       $windsns_userinfoseit['bio']=  input('post.bio'); // 获取自我介绍 
        
      if(!$windsns_userinfoseita){
    		return $this->view->fetch('windsns_userdonull');//不能为空！
    	}else{
    		
    		 $wedid = Db::name('user')->where('id', $userid)->update($windsns_userinfoseit);// 
    		
    		return $this->view->fetch('windsns_userdook');//操作成功！
    		
    	}
        
        
    }


    public function userpost()
    {
        $this->view->assign('title', __('我的帖子'));
        $userid = $this->auth->getUserinfo()['user_id'];;//获取这个会员的ID
        $windsns_postlist = Db::name('circlecontent') -> alias('a')->join('ws_circle_group w','a.circleid = w.wscircleid') -> where(['user_id'=>$userid,'w.circle_state'=>1]) -> order('aid', 'desc')->paginate(10); //列表
        $page = $windsns_postlist->render();
    	$this->assign('windsns_postlist', $windsns_postlist);
        $this->assign('page', $page);
        
        
        $usercirclesum = Db::name('circlecontent')->where(['user_id' => $userid,'circle_state' => 1])->count();// 查询这个用户下所有发帖的数量
  	 
        
        if($usercirclesum > 1 or $usercirclesum == 1){
        	
        	 return $this->view->fetch('windsns_mypost');
        
        }else{
        	
        	 return $this->view->fetch('windsns_mypostnull');
        	
        }

        
       
    }
 
    

       public function windsns_post_del($postid)
    {
        $urlwinsdsns_postid  =  input('get.postid'); 
        $shanchu = Db::name('circlecontent')->where('aid',$urlwinsdsns_postid)->delete();
        $shanchua = Db::name('circleattachment')->where('aid',$urlwinsdsns_postid)->delete();
         if($shanchu){
            return $this->view->fetch('windsns_delok');
         }else{
          	return $this->view->fetch('windsns_userdono');
			exit;
         }
        
        
        
    }


    public function service()
    {
        $this->view->assign('title', __('客服在线'));
        return $this->view->fetch('windsns_service');
    }

    
    
    
    
    
    
    
    
    
    
}




