<?php
namespace Admin\Controller;
use Think\Controller;

class IndexController extends BasicController {

    public function index() {
		$this->assign('title', '首页');
		$this->assign('action_name', '首页');
    	$this->display("index");
    }

	//后台登陆页面
	public function login() {
		if(IS_POST) {
			$params['username'] = I('post.username', '', 'htmlspecialchars');
			$params['password'] = md5(I('post.password', '', 'htmlspecialchars'));

			$adminuser = M('admin');
			//查询是否存在该账户
			$admin_userinfo = $adminuser->where($params)->find();
			if(count($admin_userinfo) > 0) {
				session('adminuid', $admin_userinfo['id']);
				session('admin_name', $admin_userinfo['username']);
				session('role', $admin_userinfo['role']);
				echo 0;
			} else {
				echo 1;
			}
			exit;
		}

        $this->assign('title', '登陆');
		$this->display("login");
	}

	//退出
	public function logout() {
		session('adminuid',null);
		session('admin_name',null);
		session('role',null);
        echo "<script>location.href='/admin/Index/login'</script>";
	}

    //修改密码
    public function updPwd() {
        if(IS_POST) {
            $oldpwd = I('post.oldpwd', '', 'htmlspecialchars');
            $newpwd = I('post.newpwd', '', 'htmlspecialchars');
            $rnewpwd = I('post.rnewpwd', '', 'htmlspecialchars');
            $username = session('admin_name');
            $uid = session('adminuid');
            $admin = M('admin');
            $userInfo = $admin->where("username='".$username."' and password='".md5($oldpwd)."'")->find();
            if(count($userInfo) <= 0) {
                echo -1;//原密码有误
                exit();
            }
            if($newpwd != $rnewpwd) {
                echo -2;//两次密码不一致
                exit();
            }
            $data['password'] = md5($newpwd);
            $admin->where("id='".$uid."'")->save($data);
            session('adminuid',null);
            echo 1;
            exit();
        }

        $this->assign('title', '修改密码');
        $this->display('updPwd');
    }

}