<?php

/**
 * 控制器:后台系统登陆控制器
 * 错误代码：015
 * date:2019-08-28
 */

namespace app\modules\manage\v1\controllers;

use app\modules\common\Helper;
use Yii;
use yii\web\Controller;

class ManagerController extends MiddleController {
	/**
	 * 返回
	 * @param $code
	 * @param string $info
	 * @param string $controller
	 * @param string $total
	 */
	protected function response($code, $info = '', $total = '', $controller = 'manager') {
		return parent::response($code, $info, $total, $controller);
	}
	public function actionDebuginfo() {
		$data = $this->rec_role;
		return $this->response('login_succ', $data);
	}
	/**
	 * [actionLogin description]
	 * @apiDoc
	 * @api     v1/manager/login
	 * @group   manager
	 * @name    登陆
	 * @desc    平台运营后台登陆入口
	 * @method  POST
	 * @param username string 账号 noreq
	 * @param password string 密码 noreq
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
	 {
	"code": "0",
	"msg": "登录成功",
	"info": {
	    "operator_id": "1",
	    "username": "admin",
	    "login_key": "8410643a7ac698157e608dc3c27301ac",
	    "operator_name": "john-admin",
	    "operator_title": "管理员",
	    "phone": "18980647855",
	    "is_freezed": "0",
	    "role_id": "1",
	    "permission": [
	        {
	            "permission_id": "1",
	            "function_code": "permissiongroup",
	            "function_name": "系统管理",
	            "permission_name": "权限管理-查询",
	            "path_info": "permissiongroup/search/"
	        },
	        {
	            "permission_id": "2",
	            "function_code": "permissiongroup",
	            "function_name": "系统管理",
	            "permission_name": "权限管理-新增",
	            "path_info": "permissiongroup/newrc/"
	        }
	    ]
	}
	}
	 */
	public function actionLogin() {
		//参数有效性验证
		if (!isset($this->para['username']) || empty($this->para['username'])) {
			return $this->response('para_miss', '账号为空');
		}
		if (!isset($this->para['password']) || empty($this->para['password'])) {
			return $this->response('para_miss', '密码为空');
		}
		//---------------------------检测账户信息-----------------------
		$username = $this->para['username'];
		//检查账户是否因密码错误锁定
		$redis = Yii::$app->redis;
		$username_redis = strtoupper($this->para['username']);
		$redis_key_locked = md5($username_redis . "_" . "LOCKED");

		$is_pwderror_locked = $redis->get($redis_key_locked);
		if ($is_pwderror_locked) {
			return $this->response('account_error', '账户被锁定1小时，请稍后再登录');
		}

		$conn = Yii::$app->db;
		$sql_extra = ' and is_del=0';
		$sql_chk_username = "select * from {{%operator}} where username=:username " . $sql_extra;
		$cmd = $conn->createCommand($sql_chk_username);
		$cmd->bindValue(':username', $username);
		$rec_username = $cmd->queryOne();

		if (is_array($rec_username) && !empty($rec_username)) {
			$password = $this->para['password'];
			$salt = $rec_username['salt'];
			$pwd_server = md5($password . '_' . $salt);

			$sql_chk_account = "select * from {{%operator}} where username=:username and password=:password " . $sql_extra;
			$cmd = $conn->createCommand($sql_chk_account);
			$cmd->bindValue(':username', $username);
			$cmd->bindValue(':password', $pwd_server);
			$rec_account = $cmd->queryOne();

			if (is_array($rec_account) && !empty($rec_account)) {
				//登录成功，清空密码错误次数
				$redis_key_pwderror = md5($username_redis . "_" . "PWDERROR");
				$num_pwderror = $redis->get($redis_key_pwderror);
				if ($num_pwderror) {
					$redis->del($redis_key_pwderror);
				}
				//账号和密码都正确，检测锁定状态
				$is_freezed = $rec_account['is_freezed'];
				if ($is_freezed == 1) {
					//----------记录登录日志----------
					$login_log['operator_id'] = $rec_account['operator_id'];
					$login_log['username'] = $rec_account['username'];
					$login_log['terminal_type'] = $this->para['terminalType'];
					$login_log['addtime'] = time();
					$login_log['addip'] = Helper::getUserIp();
					$login_log['log_type'] = 'freezed';
					$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

					return $this->response('account_error', '账户已冻结');
				} else {
					//----------记录登录日志----------
					$login_log['operator_id'] = $rec_account['operator_id'];
					$login_log['username'] = $rec_account['username'];
					$login_log['terminal_type'] = $this->para['terminalType'];
					$login_log['addtime'] = time();
					$login_log['addip'] = Helper::getUserIp();

					//状态正常，生成并写入login_key
					$operator_id = $rec_account['operator_id'];
					$login_key_gen = $this->write_login_key($operator_id);
					$sql_get_wrote_login_key = "select * from {{%operator}} where operator_id=:operator_id " . $sql_extra;
					$cmd = $conn->createCommand($sql_get_wrote_login_key);
					$cmd->bindValue(':operator_id', $operator_id);
					$rec_login = $cmd->queryOne();
					//var_dump($rec_login);
					if ($login_key_gen != $rec_login['login_key']) {
						$login_log['log_type'] = 'login_key_write_error';
						$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

						return $this->response('server_error', '登录key写入失败');
					} else {
						//员工的权限
						$role_perm = array();
						if (!empty($rec_login['group_id'])) {
							$sql_group = "select `permission` from {{%permission_group}} where group_id ='" . $rec_login['group_id'] . "' ";
							$cmd = $conn->createCommand($sql_group);
							$role_group = $cmd->queryOne();

							$permissions = $role_group['permission'];

							if ($permissions != '') {
								$sql_permission = "select permission_id,function_code,function_name,permission_name,path_info from {{%permission}} where permission_id in(" . $permissions . ") and is_used = 1 ";
								$cmd = $conn->createCommand($sql_permission);

								$role_perm = $cmd->queryAll();
							} else {
								$login_log['log_type'] = 'no_permission';
								$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

								return $this->response('data_error', '权限组未设置权限');
							}
						} else {
							$login_log['log_type'] = 'no_permission_group';
							$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

							return $this->response('data_error', '该员工未分配到权限组');
						}

						$data = array();
						$data['operator_id'] = $rec_login['operator_id'];
						$data['username'] = $rec_login['username'];
						$data['login_key'] = md5($rec_login['login_key'] . '_' . $operator_id);
						$data['operator_name'] = $rec_login['operator_name'];
						$data['operator_title'] = $rec_login['operator_title'];
						$data['phone'] = $rec_login['phone'];
						$data['is_freezed'] = $rec_login['is_freezed'];
						$data['role_id'] = $rec_login['role_id'];
						$data['permission'] = $role_perm; //具体权限
						//把登录key写入redis

						//登录用户ID记录session，方便记录用户操作
						$session = Yii::$app->session;
						$session['operator_id'] = $data['operator_id'];

						$value = array('operator_id' => $operator_id, 'gentime' => time());
						$s_value = serialize($value);
						$redis_key = md5($data['login_key'] . "_" . "REPUCAR_MANAGE_USER");
						$redis->set($redis_key, $s_value);
						$redis->expire($redis_key, LOGIN_EXP_TIME);

						$login_log['log_type'] = 'login_succ';
						$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

						return $this->response('login_succ', $data);
					}
				}
			} else {
				//----------记录登录日志----------
				$login_log['operator_id'] = $rec_username['operator_id'];
				$login_log['username'] = $rec_username['username'];
				$login_log['password_error'] = $this->para['password'];
				$login_log['terminal_type'] = $this->para['terminalType'];
				$login_log['addtime'] = time();
				$login_log['addip'] = Helper::getUserIp();
				$login_log['log_type'] = 'pwd_error';
				$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();
				/**
				 * 密码错误次数及锁定功能
				 */
				$redis_key_pwderror = md5($username_redis . "_" . "PWDERROR");
				$num_pwderror = $redis->get($redis_key_pwderror);
				if ($num_pwderror) {
					$num_pwderror = $num_pwderror + 1;
					if ($num_pwderror >= PWDERROR_NUM) {
						//错误达到4次
						//清空错误次数，执行锁定
						$redis->del($redis_key_pwderror);

						$redis_key_locked = md5($username_redis . "_" . "LOCKED");
						$redis->set($redis_key_locked, 1);
						$redis->expire($redis_key_locked, PWDERROR_LOCK_TIME); //锁定1小时
						return $this->response('account_error', '密码错误次数达到上限，账号被锁定1小时');
					}
					$redis->set($redis_key_pwderror, $num_pwderror);
				} else {
					$num_pwderror = 1;
					$redis->set($redis_key_pwderror, $num_pwderror);
					$redis->expire($redis_key_pwderror, PWDERROR_EXP_TIME); //24小时内
				}
				$num_pwderror_try = PWDERROR_NUM - $num_pwderror;
				return $this->response('account_error', '密码不正确，您还有' . $num_pwderror_try . '次机会');
			}
		} else {
			//----------记录登录日志----------
			//$login_log['operator_id'] = $rec_account['operator_id'];
			$login_log['username'] = $this->para['username'];
			$login_log['password_error'] = $this->para['password'];
			$login_log['terminal_type'] = $this->para['terminalType'];
			$login_log['addtime'] = time();
			$login_log['addip'] = Helper::getUserIp();
			$login_log['log_type'] = 'not_exist';
			$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

			return $this->response('account_error', '账号不存在');
		}
	}

	//写入登陆key
	private function write_login_key($operator_id) {
		$login_key = $this->gen_login_key();
		$conn = Yii::$app->db;
		$arr_update = array(
			'login_key' => $login_key,
		);
		$conn->createCommand()->update('{{%operator}}', $arr_update, ['operator_id' => $operator_id])->execute();
		return $login_key;
	}

	/**
	 * [actionDetail 后台用户明细]
	 * @apiDoc
	 * @api     v1/manager/detail
	 * @group   manager
	 * @name    用户明细
	 * @desc    平台管理后台用户明细
	 * @method  POST
	 * @param operator_id int 用户ID req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "0",
		"msg": "操作成功",
		"info": {
		"operator_id": "1",
		"username": "admin",
		"operator_name": "john-admin",
		"operator_title": "管理员",
		"phone": "18980647855",
		"is_freezed": "0",
		"permission": [
		    {
		        "permission_id": "1",
		        "function_code": "permissiongroup",
		        "function_name": "系统管理",
		        "permission_name": "权限管理-查询",
		        "path_info": "permissiongroup/search/"
		    },
		    {
		        "permission_id": "2",
		        "function_code": "permissiongroup",
		        "function_name": "系统管理",
		        "permission_name": "权限管理-新增",
		        "path_info": "permissiongroup/newrc/"
		    }
		],
		"group_id": "1",
		"role_id": "1"
		}
		}
	 */
	public function actionDetail() {

		if (!isset($this->para['operator_id']) || empty($this->para['operator_id']) || !is_numeric($this->para['operator_id'])) {
			return $this->response('para_miss', '员工ID为空');
		}
		$conn = Yii::$app->db;
		$operator_id = intval($this->para['operator_id']);
		$sql = "select * from {{%operator}} where operator_id=:operator_id and is_del=0 ";
		$cmd = $conn->createCommand($sql);
		$cmd->bindValue(':operator_id', $operator_id);
		$rec = $cmd->queryOne();

		if (empty($rec)) {
			return $this->response('data_error', '员工记录不存在');
		}
		//员工的权限
		$role_perm = array();
		if (!empty($rec['group_id'])) {
			$sql_group = "select `permission` from {{%permission_group}} where group_id ='" . $rec['group_id'] . "' ";
			$cmd = $conn->createCommand($sql_group);
			$role_group = $cmd->queryOne();

			$permissions = $role_group['permission'];

			if ($permissions != '') {
				$sql_permission = "select permission_id,function_code,function_name,permission_name,path_info from {{%permission}} where permission_id in(" . $permissions . ") and is_used = 1 ";
				$cmd = $conn->createCommand($sql_permission);

				$role_perm = $cmd->queryAll();
			}
		}

		$data = array();
		$data['operator_id'] = $rec['operator_id'];
		$data['username'] = $rec['username'];
		$data['operator_name'] = $rec['operator_name'];
		$data['operator_title'] = $rec['operator_title'];
		$data['phone'] = $rec['phone'];
		$data['is_freezed'] = $rec['is_freezed'];
		$data['permission'] = $role_perm;
		//$data['notes'] = (string)$rec['notes'];
		$data['group_id'] = (string) $rec['group_id'];
		$data['role_id'] = (string) $rec['role_id'];

		return $this->response('deal_succ', $data);
	}

	/**
	 * [actionLogout 退出登陆]
	 * @apiDoc
	 * @api     v1/manager/logout
	 * @group   manager
	 * @name    退出
	 * @desc    平台管理后台用户退出登陆
	 * @method  POST
	 * @param operator_id int 用户ID req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "0",
		"msg": "操作成功",
		"info": "登出成功"
		}
	 */
	public function actionLogout() {
		if (!isset($this->para['operator_id']) || empty($this->para['operator_id']) || !is_numeric($this->para['operator_id'])) {
			return $this->response('para_miss', '员工id为空或不是数字');
		}
		$operator_id = $this->para['operator_id'];
		$conn = Yii::$app->db;
		$sql_admin = "select operator_id, username, login_key from {{%operator}} where operator_id=:operator_id and is_del = 0 ";
		$cmd = $conn->createCommand($sql_admin);
		$cmd->bindValue(':operator_id', $operator_id);
		$rec_user = $cmd->queryOne();
		if (empty($rec_user)) {
			return $this->response('account_error', '员工记录不存在');
		}
		$login_key_md5 = md5($rec_user['login_key'] . '_' . $operator_id);
		$redis = Yii::$app->redis;
		$redis_key = md5($login_key_md5 . "_" . "REPUCAR_MANAGE_USER");
		$redis->del($redis_key);

		$arr_update = array(
			'login_key' => '',
		);
		$conn->createCommand()->update('{{%operator}}', $arr_update, ['operator_id' => $operator_id])->execute();

		//----------记录登录日志----------
		$login_log['operator_id'] = $rec_user['operator_id'];
		$login_log['username'] = $rec_user['username'];
		//$login_log['password_error'] = $this->para['password'];
		$login_log['terminal_type'] = $this->para['terminalType'];
		$login_log['addtime'] = time();
		$login_log['addip'] = Helper::getUserIp();
		$login_log['log_type'] = 'logout';
		$conn->createCommand()->insert('{{%operator_loginlog}}', $login_log)->execute();

		return $this->response('deal_succ', '登出成功');
	}

	/**
	 * [actionEditpwd 修改密码]
	 * @apiDoc
	 * @api     v1/manager/editpwd
	 * @group   manager
	 * @name    修改密码
	 * @desc    平台管理后台用户修改密码
	 * @method  POST
	 * @param operator_id int 用户ID req
	 * @param pwd_old string 旧密码 req
	 * @param pwd_new string 新密码 req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
	 {
		"code": "0",
		"msg": "操作成功",
		"info": "密码修改成功"
		}
	 */
	public function actionEditpwd() {
		//参数有效性验证
		if (!isset($this->para['operator_id']) || empty($this->para['operator_id']) || !is_numeric($this->para['operator_id'])) {
			return $this->response('para_miss', '员工ID为空');
		}
		if (!isset($this->para['pwd_old']) || empty($this->para['pwd_old'])) {
			return $this->response('para_miss', '旧密码为空');
		}
		if (!isset($this->para['pwd_new']) || empty($this->para['pwd_old'])) {
			return $this->response('para_miss', '新密码为空');
		}

		$conn = Yii::$app->db;
		$operator_id = intval($this->para['operator_id']);
		//检测数据是否存在
		$sql = "select * from {{%operator}} where operator_id=:operator_id ";
		$cmd = $conn->createCommand($sql);
		$cmd->bindValue(':operator_id', $operator_id);
		$rec = $cmd->queryOne();
		if (empty($rec)) {
			return $this->response('data_error', '员工记录不存在');
		}
		//旧密码是否正确
		$pwd_old = $this->para['pwd_old'];
		$salt = $rec['salt'];
		$pwd_old_server = md5($pwd_old . '_' . $salt);
		if ($pwd_old_server != $rec['password']) {
			return $this->response('data_error', '原密码错误');
		}
		//生成新密码
		$pwd_new = $this->para['pwd_new'];
		$salt = $rec['salt'];
		$pwd_server = md5($pwd_new . '_' . $salt);

		$arr_operator_update = array(
			"password" => $pwd_server,
			"updatetime" => time(),
			"updateip" => Helper::getUserIp(),
		);

		$conn->createCommand()->update('{{%operator}}', $arr_operator_update, ['operator_id' => $operator_id])->execute();

		//----------记录操作日志----------
		$action_log = array();
		$action_log['operator_id'] = $this->rec_role['operator_id'];
		$action_log['username'] = $this->rec_role['username'];
		$action_log['route'] = Yii::$app->request->absoluteUrl;
		$action_log['terminal_type'] = $this->para['terminalType'];
		$action_log['data_before'] = serialize($rec);
		$action_log['data_after'] = serialize($arr_operator_update);
		$action_log['addtime'] = time();
		$action_log['addip'] = Helper::getUserIp();
		$conn->createCommand()->insert('{{%operator_actionlog}}', $action_log)->execute();

		$conn->close();
		return $this->response('deal_succ', '密码修改成功');
	}
}
