<?php
/**
 * 公共基础控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Controller;
use Think\Controller;

class HanchaoController extends Controller {
	public function _initialize(){
	   header("content-Type: text/html; charset=utf-8");
       $this->cache_model=explode(',',HANCHAO_CACHE_MODEL);//后台缓存模型
       $this->config=S('DB_CONFIG_DATA');// 读取数据库中的配置 /
       if(!$this->config){$this->config = api('Config/lists');S('DB_CONFIG_DATA',$this->config);}C($this->config); //添加配置
       $seoinfo['before_title']='';
       $seoinfo['tplseo_title']=$this->config['WEB_SITE_TITLE'];
       $seoinfo['tplseo_keywords']=$this->config['WEB_SITE_KEYWORD'];
       $seoinfo['tplseo_description']=$this->config['WEB_SITE_DESCRIPTION'];
       $this->assign($seoinfo);
       $this->assign("NOW_TIME",NOW_TIME);
       $this->member_info=session('member_info');if(empty($this->member_info))$this->autologin();
        $this->shops_info=session('shops_info');if(empty($this->shops_info))$this->autologin();
       $eid=I('get.eid');if(!empty($eid) && empty($this->member_info))cookie('ExtensionId',$eid);//邀请注册
       //zjn 2019.1.18 start
       $lshop_id = I('get.lshop_id');
       if(intval($lshop_id)>0)cookie('lshop_id',intval($lshop_id));//小店id
       if(empty($lshop_id) && ($this->member_info['is_littleshop']==1 || $this->member_info['parent_id'])){
          $lmap['uid']=$this->member_info['id'];
          $lmap['status']=1;
          $lshop_id=M('LittleShop')->where($lmap)->getField('id');
          if(intval($lshop_id)>0)cookie('lshop_id',intval($lshop_id));//小店id
          if(empty($lshop_id) && $this->member_info['parent_id']){
            $lmap['uid']=$this->member_info['parent_id'];
            $lshop_id=M('LittleShop')->where($lmap)->getField('id');
            if(intval($lshop_id)>0)cookie('lshop_id',intval($lshop_id));//小店id
          }
       }
       // end-------
       
       $extension=I('get.extension');if(!empty($extension))cookie('ExtensionKey',$extension);//长链接参数
        $tokerid=I('get.uid');
        if((CONTROLLER_NAME =='Collection' || CONTROLLER_NAME =='Index') && ACTION_NAME=='kaquan_cont' && !empty($tokerid))cookie('TokerId',$tokerid);//拓客id（优惠券分享的id）
        //判断站点是否有效
        $site_info=session('site_info');

        if(empty($site_info)){
            $map=array();
            $map['site_id']=C('appid');
            $map['status']=1;
            $site_info=M("SiteInfo")->where($map)->field('end_time,pack_name,package,type_id,type_name,is_try')->find();
            session('site_info',$site_info);
        }
        if (empty($site_info)) {
            echo "该站点登录超时!";exit;
        }
       $this->loadmodule_lang();
	}
	private function loadmodule_lang(){
	   $js_file=ROOT_PATH.'/'.CACHE_PATH.MODULE_NAME.'/lang.js';
       if(!file_exists($js_file)){
        $str = "var LANG = {";
		foreach(L() as $k=>$lang_row){$str .= "\"".$k."\":\"".str_replace("nbr","\\n",addslashes($lang_row))."\",";}
		$str = substr($str,0,-1);
		$str .="};";        
        file_put_contents($js_file,$str);}
	}
    /**
     * 通用分页列表数据集获取方法
     *
     *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
     *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
     *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
     *
     * @param sting|Model  $model   模型名或模型实例
     * @param array        $where   where查询条件(优先级: $where>$_REQUEST>模型设定)
     * @param array|string $order   排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
     *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
     *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
     *
     * @param array        $base    基本的查询条件
     * @param boolean      $field   单表模型用不到该参数,要用在多表join时为field()方法指定参数
     * @return array|false
     * 返回数据集
     */
    public function lists ($model,$where=array(),$order='',$base = '',$field=true,$pagesize='',$return='list',$pageconfig='',$pagetype=''){
        $options    =   array();
        $REQUEST    =   (array)I('request.');
        if(is_string($model)){$model  =   M($model);}
        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);
        $pk         =   $model->getPk();
        if($order===null){//order置空           
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){$options['order'] = $order;}
        unset($REQUEST['_order'],$REQUEST['_field']);
        $options['where'] = array_filter(array_merge( (array)$base,(array)$where ),function($val){
            if($val===''||$val===null){return false;}else{return true;}
        });
        unset($REQUEST['_order'],$REQUEST['_field'],$options['where']['_order'],$options['where']['_field']);
        $pp= C('VAR_PAGE');if(empty($pp))$pp='p';
        if(!empty($options['where'][$pp]))unset($options['where'][$pp]);
        if(!empty($options['where']['__hash__']))unset($options['where']['__hash__']);
        if( empty($options['where'])){unset($options['where']);}
        $options      =   array_merge( (array)$OPT->getValue($model), $options );           
        $result['_total']=$total        =   !empty($options['where'])?$model->where($options['where'])->count():$model->count();
        if($pagesize)$listRows = intval($pagesize);
        else{$listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 20;}
        if($total>=$listRows){
            if(!empty($REQUEST['__hash__']))unset($REQUEST['__hash__']);if(!empty($REQUEST['search']))unset($REQUEST['search']);
        $page = new \Common\Vendor\Page($total, $listRows, $REQUEST);
        if(defined('PAGE_CONFIG') && empty($pageconfig))$pageconfig=PAGE_CONFIG;
        if(empty($pageconfig))$pageconfig='%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%';
        $page->setConfig('theme',$pageconfig);
  if($pagetype==1 || MODULE_NAME=='Mobile'){$page->prevshow=true;$page->nextshow=true;$page->setConfig('prev','上一页');$page->setConfig('next','下一页');}
        $result['_page']=$p =$page->show();$this->assign('_page', $p? $p: '');        
        $options['limit'] = $page->firstRow.','.$page->listRows;
        }else{
            $options['limit'] ='0,'.$listRows;
            $this->assign('_page','');
        }
        $this->assign('_total',$total);
        $model->setProperty('options',$options);
        $result['list']=$model->alias("OAO__")->field($field)->select();
        return $return?$result[$return]:$result;
    }
	
    private function autologin(){//自动登录       
        $autologin = cookie('autologin');
        if($autologin && empty($this->member_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;
               //$membermod=D('Member/Member');
			   $membermod=D('Common/Login');
               $memberinfo = M('Member')->where($map)->field(true)->find();
               if($memberinfo){//判断是否存在该用户
                    $this->member_info=$memberinfo;
                    $membermod->loginupdate($memberinfo);
                    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]);}
                    }
               }else{
                cookie('autologin',null);
               }
       	 }else{
        	cookie('autologin',null);
       	 }
      }
    }
}

?>