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

class User_service {

	public $uid;
	public $username;
	public $level;
	public $end_time;
	public $userinfo;
	public $score;


	public function __construct(){
		$this->ci = &get_instance();
		$this->uid = 0;
		$this->username = 'guest';
		$this->status = 0;
		$this->level = 0;
		$this->end_time = 0;
		$this->score = 0;
		$this->end_timestamp = 0;
		$this->ci->load->model('user_model');
		$this->ci->load->library('Qrcode');
	}


	public function checkLogin($auth = '', $authkey = ''){
		if(empty($auth)){
			$auth = $this->ci->input->post('auth');
		}
		if(!$auth){
			return false;
		}
		$this->ci->load->helper('discuz_helper');
		$key = empty($authkey) ? ODZ_AUTHKEY : $authkey;

        $auth = daddslashes(explode("\t", authcode($auth,'DECODE', $key)));
        list($password, $uid) = empty($auth) || count($auth) < 2 ? array('', '') : $auth;

        $user = $this->ci->user_model->getUserFromDiscuz($uid);
        if(!empty($user) && $user['password'] == $password){
        	$this->uid = $user['uid'];
        	$this->username = $user['username'];
        	$this->status = 1;
        	return $user['groupid'];
        }

        return false;
	}


	public function getScore(){

		if(empty($this->uid)){
			return 0;
		}

		$score = $this->ci->user_model->getScoreFromDiscuz($this->uid);
		$this->ci->load->model('score/shopInfo_model', 'shop');
		$shopinfo = $this->ci->shop->getShopInfo();
		$this->score = $score['extcredits'.$shopinfo['type']];
		return $this->score;		
	}

	public function getUserInfo($uid = 0){
		$this->uid = $uid == 0 ? $this->uid : $uid;
		$userinfo = $this->ci->user_model->getByUid($this->uid);

		if(empty($userinfo)){
			$this->status = -1;
			return false;
		}

		$this->level = $userinfo['level'];
		//高级权益
		if($this->level = 2){
			if($userinfo['end_time'] < time()){
				$this->ci->user_model->updateByUid(array('level' => 1), $userinfo['uid']);
				$this->level = 1;
			}
			$this->end_timestamp = empty($userinfo['end_time']) ? 0 : $userinfo['end_time'];
			$this->end_time = empty($userinfo['end_time']) ? 0 : date('Y-m-d H:i:s', $userinfo['end_time']);
		}
		$this->username = $userinfo['username'];
		return $userinfo;
	}

    //获取一组用户的用户组等级样式
    function usergroup_level_by_uids($uids) {
        $user_level = array();
        $users_level_style = array();
        $user_level = $this->get_usergroup_levels($uids);
        if (!empty($user_level)) {
            foreach ($user_level as $uid => $userinfo) {
                $users_level_style[$uid] = $this->get_user_level_style($userinfo);
            }
        }
        return $users_level_style;
    }

    //用户组等级(discuz)
    function usergroup_level($uid){
        $userinfo = array();
        $users_group = array();
        $userinfo = $this->ci->user_model->getUserFromDiscuz($uid);
        if(empty($userinfo)){
            return false;
        }
        $usergroupid = $userinfo['groupid'];

        $gender = $this->ci->user_model->get_user_gender_from_discuz($uid);
        $gender = $gender['gender'];
        // print_r($_G['cache']['usergroups']);exit;
        $level = 0;
        $usergroup = $this->ci->user_model->get_usergroup_from_discuz();

        foreach($usergroup as $key => $val){
            if($val['type'] == 'member'){
                if($val['creditslower'] <= 0){
                    $val['level'] = $level;
                }else{
                    $level++;
                    $val['level'] = $level;
                }
            }
            $users_group[$val['groupid']] = $val;
        }

        $result = array();
        if(array_key_exists($usergroupid, $users_group)){
            $result = $users_group[$usergroupid];
            $result['gender'] = $gender;
        }

        return $this->get_user_level_style($result);

        /*if($result['type'] == 'system' || $result['type'] == 'special'){
            if($result['gender'] == 0){
                $usergroup_str = "<div class='admin_name_type admin_gl_n'>".$result['grouptitle']."</div>";
            }elseif($result['gender'] == 1){
                $usergroup_str = "<div class='admin_name_type admin_gl_m'>".$result['grouptitle']."</div>";
            }else{
                $usergroup_str = "<div class='admin_name_type admin_gl_w'>".$result['grouptitle']."</div>";
            }
        }else{
            if($result['gender'] == 0){
                $usergroup_str = "<div class='user_name_type user_gl_n'><div class='user_name_type_left'><img src='assets/images/leaveV.png'><span>".$result['level']."</span></div><span class='user_name_type_right'>".$result['grouptitle']."</span></div>";
            }elseif($result['gender'] == 1){
                $usergroup_str = "<div class='user_name_type user_gl_m'><div class='user_name_type_left'><img src='assets/images/leaveV.png'><span>".$result['level']."</span></div><span class='user_name_type_right'>".$result['grouptitle']."</span></div>";
            }else{
                $usergroup_str = "<div class='user_name_type user_gl_w'><div class='user_name_type_left'><img src='assets/images/leaveV.png'><span>".$result['level']."</span></div><span class='user_name_type_right'>".$result['grouptitle']."</span></div>";
            }
        }

        return $usergroup_str;*/
    }

    public function get_user_level_style($userinfo) {
        $style_str = '';
        if ($userinfo['type'] == 'system' || $userinfo['type'] == 'special') {
            if ($userinfo['gender'] == 0) {
                $style_str = "<div class='admin_name_type admin_gl_n'>".$userinfo['grouptitle']."</div>";
            } elseif ($userinfo['gender'] == 1){
                $style_str = "<div class='admin_name_type admin_gl_m'>".$userinfo['grouptitle']."</div>";
            } else {
                $style_str = "<div class='admin_name_type admin_gl_w'>".$userinfo['grouptitle']."</div>";
            }
        } else {
            if ($userinfo['gender'] == 0) {
                $style_str = "<div class='user_name_type user_gl_n'><div class='user_name_type_left'><img src='assets/images/leaveV.png'><span>".$userinfo['level']."</span></div><span class='user_name_type_right'>".$userinfo['grouptitle']."</span></div>";
            } elseif ($userinfo['gender'] == 1){
                $style_str = "<div class='user_name_type user_gl_m'><div class='user_name_type_left'><img src='assets/images/leaveV.png'><span>".$userinfo['level']."</span></div><span class='user_name_type_right'>".$userinfo['grouptitle']."</span></div>";
            } else {
                $style_str = "<div class='user_name_type user_gl_w'><div class='user_name_type_left'><img src='assets/images/leaveV.png'><span>".$userinfo['level']."</span></div><span class='user_name_type_right'>".$userinfo['grouptitle']."</span></div>";
            }
        }
        return $style_str;
    }


	public function encrypt($msg){
		$this->ci->load->helper('discuz_helper');
        return  authcode($msg,'ENCODE', ODZ_AUTHKEY);
	}

	public function decode($codeauth){
		if(empty($codeauth)){
			return false;
		}

		$this->ci->load->helper('discuz_helper');
        $result = authcode($codeauth,'DECODE', ODZ_AUTHKEY);
        $result = explode('|', $result);


        if(empty($result[0])){
        	return false;
        }
        $this->uid = $result[0];
        return array('uid' => $result[0], 'createtime' => $result[1]);

	}


	public function codeImage(){

		$this->ci->load->helper('url');   
        $path = 'uploads/qrcode/';
        $filename = 'qrcode_'.$this->uid.'.png';

        if(file_exists($path.$filename)){
			return base_url($path.$filename);
		}


		$str = "{$this->uid}|".time();
		$str = $this->encrypt($str);
		$str = '2,'.$str;
        
        $errorCorrectionLevel = 'L';//容错级别   
        $matrixPointSize = 6;//生成图片大小    
        //生成二维码图片
        
        $this->ci->qrcode->png($str,$path.$filename,$errorCorrectionLevel,$matrixPointSize, 2);
        return base_url($path.$filename);
        //echo "<img src='".base_url($filename)."' />";
		//return 'http://qr.liantu.com/api.php?text='.$str;
	}


	public function buy($duration, $ordernumber, $uid = 0, $type){
		$userinfo = $this->getUserInfo($uid);
		$time = time();
		//未开通或已经过期
		$data['level'] = 2;
		if($userinfo['level'] == 1 || $userinfo['end_time'] < $time){
			$data['start_time'] = $time;
			$data['end_time'] = strtotime('+'.$duration.' day', $time);
		}

		//续期
		if($userinfo['level'] == 2){
			$data['end_time'] = strtotime('+'.$duration.' day', $userinfo['end_time']);
		}
		$data['type'] = $type;
	

		$this->ci->load->model('cardorder_model', 'order');
		$this->ci->order->updateOrderStatus($ordernumber, CardOrder_Model::SUCCESS);
		$this->ci->user_model->updateByUid($data, $this->uid);

	}


	public function formatUserinfo($userinfo){
		$user = array(
                'username' => $userinfo['username'],
                'uid' => $userinfo['uid'],
                'level' => $userinfo['level'],
                'end_time' => date('Y-m-d H:i:s', $userinfo['end_time']),
                'end_timestamp' => $userinfo['end_time']

            );

		return $user;
	}


	//用户组等级(discuz)
   public function get_usergroup_levels($uids=array()){
        $userinfo = array();
        $usergroupids=array();
//        $groupids = array();
        $genders=array();
        $usergroups=array();
        $userinfo = $this->ci->user_model->getUsersFromDiscuz($uids);
        if(empty($userinfo)){
            return false;
        }
        foreach ($userinfo  as $king => $box) {
        	$usergroupids[$box['uid']] = $box['groupid'];
            /*if (!in_array($box['groupid'], $groupids)) {
                $groupids[] = $box['groupid'];
            }*/
        }
        $gender = $this->ci->user_model->get_users_gender_from_discuz($uids);
        foreach ($gender as $ke => $val) {
        	$genders[$val['uid']]=$val['gender'];
        }
        // $gender = $gender['gender'];
        // print_r($_G['cache']['usergroups']);exit;
        $level = 0;
        $usergroup = $this->ci->user_model->get_usergroup_from_discuz();
        foreach($usergroup as $key => $val){
            if($val['type'] == 'member'){
                if($val['creditslower'] <= 0){
                    $val['level'] = $level;
                }else{
                    $level++;
                    $val['level'] = $level;
                }
            }
            $usergroup[$key] = $val;
        }
        foreach ($usergroup as $he => $da) {
        	$usergroups[$da['groupid']]=$da;
        }
        $result = array();
        foreach ($usergroupids as $key => $value) {
        if(array_key_exists($value,$usergroups)){
            $result[$key] = $usergroups[$value];
            $result[$key]['gender'] = $genders[$key];
        }	
        }
        return $result;
    }
	









}