<?php

namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
class PublicController extends AdminBaseController {

	public function _initialize(){}

	//后台登陆界面
	public function login() {
		$site_info = cmf_get_site_info();
		
		$website_logo = cmf_get_image_url($site_info['website_logo']);
		$backstage_website_icon = cmf_get_image_url($site_info['backstage_website_icon']);
		$backstage_website_background = cmf_get_image_url($site_info['backstage_website_background']);
		$this->assign('site_info',$site_info);
		$this->assign('website_logo',$website_logo);
		$this->assign('backstage_website_icon',$backstage_website_icon);
		$this->assign('backstage_website_background',$backstage_website_background);
		$admin_user_info = session('admin_user_info');
		if (!empty($admin_user_info)) {
			//已经登录
			return redirect(url("admin/Index/index"));
		} else {
			$site_admin_url_password = config("cmf_SITE_ADMIN_URL_PASSWORD");
			$upw = session("__CMF_UPW__");
			if (!empty($site_admin_url_password) && $upw != $site_admin_url_password) {
				return redirect(cmf_get_root() . "/");
			} else {
				session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__", true);
				return $this->fetch(":login");
			}
		}
	}

	//登录验证
	public function doLogin() {
		$dlsj = $this->request->param();
		//判断数据是否为空
		$name = $dlsj['username'];
		if (empty($name)) {
			$this->error("请输入用户名！");
		}
		$pass = $dlsj['password'];
		if (empty($pass)) {
			$this->error("请输入密码！");
		}
		$captcha = $dlsj['yzm'];
		if (empty($captcha)) {
			$this->error("请输入验证码！");
		}
		//验证码
		if (!cmf_captcha_check($captcha)) {
			$this->error("验证码错误");
		}
		if (strpos($name, "@") > 0) {//邮箱登陆
			$where['user_email'] = $name;
		} else {
			$where['user_login'] = $name;
		}
		$result = Db::name('user')->where($where)->find();
		if (!empty($result)) {
			if (cmf_compare_password($pass, $result['user_pass'])) {
				// if ($result["id"] != 1 && empty($result['status'])) {
				// 	$this->error("用户不存在！");
				// }
				$result['last_login_ip'] = get_client_ip(0, true);
				$result['last_login_time'] = time();
				Db::name('user')->update($result);
				$token = cmf_generate_user_token($result["id"], 'web');
				if (!empty($token)) {
					session('token', $token);
				}
				cookie("admin_username", $name, 3600 * 24 * 30);
				session('admin_user_info', $result);
				session('ADMIN_ID',$result['id']);
				$this->success("登录成功！",url("admin/Index/index"));
			} else {
				$this->error('密码不正确！');
			}
		} else {
			$this->error('用户不存在！');
		}
	}

	//后台管理员退出
	public function logout() {
		session('admin_user_info', null);
		return redirect(url('/admin', [], false, true));
	}

}