<?php
/** wap
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Mobile\Controller;
use Common\Controller\HanchaoController;
class ShopBaseController extends HanchaoController {
	public function _initialize(){
		parent::_initialize ();
        if(!checksiteauth('MenDian|DingHuo')){ exit;}
        GLOBAL $PurchaseCategory;
        if(empty($PurchaseCategory))$PurchaseCategory=getcache('PurchaseCategory');
        $shops_info=$this->shops_info=session('shops_info');
        define('MID',$shops_info['shop_id']);
 		define('PAGE_CONFIG','%UP_PAGE% %DOWN_PAGE%');
		$autologin = cookie('autologin');
    	$this->TEMPLATE_PATH=__ROOT__.substr(APP_PATH,1).'Mobile/'.C('DEFAULT_V_LAYER').'/'.C('DEFAULT_THEME').'/';
        $this->baseheaderjs='';
        //关联微信
        $wxopenid=$this->getopenid();//获取当前微信id
        if($wxopenid && $wxopenid!='kong'){$autosignwx=I('get.autosignwx');//是否绑定当前微信
            //已登录并且没有绑定微信自动绑定微信
            if($this->shops_info['id'] && empty($this->shops_info['wxid']) && !empty($autosignwx)){$this->locktowx($wxopenid);$this->autowxlogin($wxopenid,$this->shops_info['id']);}
            $memberinfo=$this->getwxuserinfo($wxopenid);
            if($this->shops_info['id'] && empty($this->shops_info['wxid']) && empty($autosignwx)){
                if(!$memberinfo)$this->baseheaderjs="<script>if(confirm('您确定要将当前微信绑定当前用户吗?')){location.href='".U('Mobile/Index/index',array('autosignwx'=>1))."';}else{location.href='".U('Mobile/Index/index',array('noautosignwx'=>1))."';}</script>";
            }
			
            //微信没有登录  自动登录
           if(empty($this->shops_info['id']) && $memberinfo){$this->autologinupdate($memberinfo);$this->autowxlogin($wxopenid,$memberinfo['id']);}
		   if($this->shops_info['id'] > 0){$this->assign('MID',$this->shops_info['id']);}else{$this->assign('MID',0);};
        }
        //其它自动登录  
        if($autologin && !$this->shops_info['id']){     
        	$autostr=explode('|',authcode($autologin,'DECODE'));$ip=get_client_ip();
        	if($ip==$autostr[1]){
        	   $checkip=get_client_ip(1);
        	   $map['id']=$autostr[0];
        	   $map['username']=$autostr[2];
        	   $map['last_ip']=$checkip;
               $memberinfo = M('Member')->where($map)->field(true)->find();
               if($memberinfo){$this->autologinupdate($memberinfo);}else{cookie('autologin',null);}
       	    }else{cookie('autologin',null);}
        }
        $header_cates = D('Common/PurchaseCategory')->getcatelist();//分类
        $this->assign('header_cates',$header_cates);
	  	$result = D('Common/Area')->init();//初始化地区信息
    }
	private function getopenid(){
        if(!is_weixin())return false;
        $openid='';
        $wxopenid=I('param.openid');
        if($wxopenid){session('wxopenid',$wxopenid);}
        if(I('get.noautosignwx')){session('wxopenid','kong');}
        $openid=session('wxopenid');
        if(empty($openid)){
            $openid = get_openid();session('wxopenid',$openid);
        }
        return $openid;
    }
	private function locktowx($sessionwxuname=''){
        $autosignwx=I('get.autosignwx');
        if(empty($sessionwxuname) || $sessionwxuname=='kong' || empty($this->member_info['id']) || !empty($this->member_info['wxid']) || empty($autosignwx))return false;
        $where=array('id'=>$this->member_info['id']);
        M('Member')->where($where)->save(array('wxid'=>$sessionwxuname));
        $member_info=$this->member_info;
        $member_info['wxid']=$sessionwxuname;
        $member_info['member_info_auth_sign'] = data_auth_sign($member_info);
        session('member_info',$member_info);        
    }
    private function getwxuserinfo($openid=''){
        if(empty($openid))$openid=session('wxopenid');
        if(empty($openid))return false;
        $memberinfo=M('Member')->where("wxid='".$openid."'")->field(true)->find();
        if(empty($memberinfo)){
            $memberid=M('OauthMember')->where("openid='".$openid."' and _from='weixin'")->getField('lock_to_id');
            if($memberid)$memberinfo=idtoname($memberid,'Member','*');
        }return $memberinfo;
    }
    protected function autowxlogin($sessionwxuname,$id=''){
		if(empty($sessionwxuname))return false;//微信自动登录
        $OMember = M('OauthMember');$ipid=get_client_ip(1);
		if(empty($id))$id=$this->member_info['id'];
        $res=$OMember->where("`_name`='".$sessionwxuname."'")->field('login_times')->find();
        $login_times=$res['login_times'];
        if($login_times){
            $data = array(
					'last_login_time'	 => NOW_TIME,
					'last_login_ip'		 => $ipid,
					'login_times'		 => $login_times + 1,
			);
			$OMember->where("_from='weixin' and (_name='{$sessionwxuname}' || openid='{$sessionwxuname}')")->save($data);
        }else{
            $data = array(
					'_from'				 => 'weixin',
					'_name'				 => $sessionwxuname,
					'head_img'			 => '',
					'create_time'		 => NOW_TIME,
					'lock_to_id'		 => $id?$id:MID,
					'last_login_time'	 => NOW_TIME,
					'last_login_ip'		 => $ipid,
					'login_times'		 => 1,
					'status'			 => 1,
					'access_token'		 => 0,
					'expires_date'		 => 0,
					'openid'			 => $sessionwxuname,
				);
			$OMember->add($data);
        }
    }
    protected function autologinupdate($memberinfo){
		if(empty($memberinfo))return false;//自动登录
        $memberinfo['member_info_auth_sign'] = data_auth_sign($memberinfo);
        session('member_info', $memberinfo);$userdata=array();
        $userdata['id'] = $memberinfo['id'];
        $userdata['login_count'] = array('exp', 'login_count+1');
        $userdata['last_login'] = NOW_TIME;
        $userdata['last_ip'] = get_client_ip(1);
        M('Member')->save($userdata);                    
        if(C('MEMBER_UC')){//uc同步登录
            $uc = new \Ucenter\Client\Client();
            $re = $uc->uc_get_user($autostr[2]);
            if($re[0]>0){echo $uc->uc_user_synlogin($re[0]);}
       }
    }
}
?>