<?php
/** App base控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <xiaoq@570035208.com>
 */

/** 注意事项
 * 1.注意客户端与服务端控制器与方法名称的大小写（控制器首字母大写）记录在method_array方法中
 * 2.返回值统一放在$return['data']中,报错信息放在$return['msg']中
 * 3.返回值$return['status']中 1代表正常数据 2代表获取的数据为空 3代表登录信息错误 
 * 4.需要登录验证的方法和控制器统一用$this->checkuserauth()验证，验证成功则返回用户数据
 */
namespace App\Controller;
use Common\Controller\HanchaoController;
class BaseController extends HanchaoController {
	public function _initialize(){
		parent::_initialize ();
		$this->pagesize = C('WEB_DEFAULT_PAGE') > 0 ? C('WEB_DEFAULT_PAGE') :10;//网站默认分页
        if(I('pagesize'))$this->pagesize=I('pagesize');
        $this->notallowmod = array('admin','config','oauth_member');//不允许操作的模块
        $this->ControllerName = CONTROLLER_NAME; //控制器			
		$this->ActionName = ACTION_NAME; //方法
        $this->AC_ID=$_SERVER['HTTP_X_APICLOUD_APPID']; 
		$this->AppKey=$_SERVER['HTTP_X_APICLOUD_APPKEY'];
        $this->check();
    }
    //
    //允许执行的控制器与方法
    private function method_array($key=''){
        $method_array = array(
            //添加控制器和方法
			'Member'=>array('index','checkmobile','member_list','member_add','member_infor','member_grade_add','grade_list','get_memberinfo','del_grade','get_grade','integral_reward','get_mrlist','many_points','save_reward','many_points_add','get_many_point_info','del_many_points','member_carelist','get_careinfo','add_membercare','check_care','send_membercare','member_discount','get_gradeinfo','change_status','get_member','sub_recharge','member_invite','calculation','my_extension','save_config','del_care','get_memberpack','daogou','get_suppliers','get_memberattr','add_member_attribute','get_memberattrinfo','save_labels','add_label','get_memberattr_new','member_bind','member_bind_add'),//会员中心
            'Ajax'=>array('upload','shops','linkage','add_card','is_upd_card','particulars','add_coupon','list_coupon','update_coupon_data','update_card','create','share_url','save_wx','update_config_data','card_update','config_guan','wx_keyword','del_wx_keyword','url_navtype','wx_keyword_add','select_keyword','wx_keyword_upd','wx_menu_list','wx_menu_add','select_menu','wx_menu_upd','wx_menu_del','updatemenu','coupon_issue','coupon_if','logo'),
            'Decca'=>array('index','add_receipt','get_info'),
            'Cashier'=>array('cashier_list','login_name_sn','index','cashier_add','cashier_del','statistics','turn_over_list','record_list','add_turnover','turn_over_content','get_print_info','exchange_print_info','print_recharge_info','get_shop_config','get_message_list','get_message_count','message_read','get_active','return_goods','return_goods_print'),
            'Shops'=>array('index','get_pid','save_shops','shop_list_arr','shops_list','check','shops_change','get_root_data','get_chinaums_img'),//门店
            'PaymentReceived'=>array('get_calculator','get_more_score','add_order','check_code','get_coupon','check_paysuccess','count_use_score','get_orderinfo','print_order','check_mm_paysuccess'),
            'UCenter'=>array('index','get_account','set_account','set_password','get_shops_info','set_shops_item','get_cashier_info'),
            'ShopLog'=>array('money_list','info','bill','order_tui','explo'),
			'Message'=>array('index'),
            'Takeout'=>array('location_index','add_cart','goods_info'),
			//商品
			'Goods'=>array('goods_list','get_cate','goods_info','save_goods','delete_goods','category_lists','goods_lists','unit_lists','delete_category','category_info','save_category','attr_lists','attr_info','save_attr','save_attr_options','set_all_options','package_add','package_list','get_package','package_send','get_member_package','get_package_service','sub_hx_package','service_list','service_info','service_cate_list','save_service_category','save_service','select_hx','service_hx','select_thm','check_goods','select_gift','check_gift','service_jilu','thm_jilu','gift_jilu'),
            'Pay'=>array('go_buy','notify'),
            'OrderInfo'=>array('index','get_order_status','order_info','order_manage','order_take','deliver_goods','tui_goods','submit_service','xstui_goods'),
            'Article'=>array('index','content','news'),
			'CashierSet'=>array('moling_before','update_moling','tone_before','update_tone','cash_before','update_cash','tpl_before','update_tpl','set_shop_prints','set_jizhong_config'),
            'InvoicingOrder'=>array('search_goods','get_category','category_two_lists','get_order_list','get_order_info','confirm_prepare_goods','confirm_goods','cancel_order','get_print_info','sub_order_stock','transfer_add_before','transfer_add','bad_add','stocktaking_add_before','stocktaking_add','other_goods','get_suppliers','bad_list','bad_info','bad_print_info','stocktaking_list','stocktaking_info','warning','stock_confirm_order','add_order','check_paysuccess','save_pay_img','get_return_order','get_return_goods','get_shopmoney'),
            'Statistics'=>array('index','member_trend','member_buy_rate','consume','order','goods_sales','recharge'),
            'ThreeOrder'=>array('index','order_info','order_manage','three_category','quickedit','save_quickedit'),
			'GiftCard'=>array('gift_card_info','add_gift_card_order','get_sale_list','get_order_info'),//礼品卡
            'ShopsRoleAuth'=>array('auth_login'),
            'Face'=>array('member_customer_list','member_customer_info','change_membertype'),
            'CallLog'=>array('call_list','call_info'),
            'Login'=>array('dologin'),
            //end
        );
        //不需要登录验证的控制器与方法
        $this->notchecklogin = array(
            'Ajax'=>array('upload','shops','linkage','add_card','is_upd_card','particulars','add_coupon','list_coupon','update_coupon_data','update_card','create','share_url','save_wx','update_config_data','card_update','config_guan','wx_keyword','del_wx_keyword','url_navtype','wx_keyword_add','select_keyword','wx_keyword_upd','wx_menu_list','wx_menu_add','select_menu','wx_menu_upd','wx_menu_del','updatemenu','coupon_issue','coupon_if','logo'),
            'Login'=>array('dologin')
        );
        return empty($key)?$method_array:$method_array[$key];
    }
    //检测请求是否合法
	private function check(){
	    $return['status']=3;
        //请求日志
        //file_put_contents('applog/'.$ControllerName.'/'.$ActionName.'-'.date("YmdHis").'.txt',var_export($_REQUEST,true));
		if(!in_array( $this->ControllerName, array_keys($this->method_array()))){		  
            $return['msg']='请求的控制器('. $this->ControllerName.')不存在';
            $this->ajaxReturn($return);
		}
        if(!in_array( $this->ActionName, $this->method_array($this->ControllerName))){		  
            $return['msg']='请求的方法('.$this->ActionName.')不存在';
            $this->ajaxReturn($return);
		}
        if(empty($this->AC_ID)){
            $return['msg']='APPID不能为空';
		    $this->ajaxReturn($return);
        }
        if(!in_array($this->AC_ID,C('AC_ID')) && $this->AC_ID!=C('AC_ID')){
            $return['msg']='APPID不匹配';
		    $this->ajaxReturn($return);
        }
        if(empty($this->AppKey)){
            $return['msg']='APPKEY不能为空';
		    $this->ajaxReturn($return);
        }
        $appkeyarr=explode('.',$this->AppKey);
        $sign=$appkeyarr[0];//签名
        $timestamp=$appkeyarr[1];
        $method = 'c='.$this->ControllerName.'&a='.$this->ActionName;
		$my_sign=SHA1($method.$this->AC_ID.$timestamp.C('HANCHAO_KEY'));	
		if($my_sign!=$sign){
		  $return['msg']='签名不正确-------'.$method.$this->AC_ID.$timestamp.C('HANCHAO_KEY');
		  $this->ajaxReturn($return);
        }
        //验证登录信息是否合法
        $notcheckloginarr = array();
        foreach($this->notchecklogin as $k=>$v){
            foreach($v as $val){$notcheckloginarr[] = $k.$val;}
        }
        if(!in_array($this->ControllerName.$this->ActionName,$notcheckloginarr)){
            $paramdata=I('param.');
            if($paramdata['is_root']==1){
                $this->checkrootauth();
            }else{
                $this->checkshopauth();
            }
        }
        return true;	
	}
    public function checkshopauth(){
        $return['status'] = 3;
        $return['msg']='获取登录信息错误,请重新登录!';
        $paramdata=I('param.');
        $paramdata['sid']=intval($paramdata['sid']);

        if(empty($paramdata['sid']) || empty($paramdata['token'])){
		    $this->ajaxReturn($return);
        }
        $accountinfo=idtoname($paramdata['sid'],'ShopsAccount','*','id',false);
        if($accountinfo['password']!=$paramdata['token']){
		    $this->ajaxReturn($return);
        }
        return $accountinfo;
    }
    public function checkrootauth(){
        $return['status'] = 3;
        $return['msg']='获取登录信息错误,请重新登录!';
        $paramdata=I('param.');
        $paramdata['root_id']=intval($paramdata['root_id']);
        if(empty($paramdata['root_id']) || empty($paramdata['root_token'])){
		    $this->ajaxReturn($return);
        }
        $admininfo=idtoname($paramdata['root_id'],'Admin','*','id',false);  
        if($admininfo['password']!=$paramdata['root_token']){
		    $this->ajaxReturn($return);
        }
        return $admininfo;
    }
    public function format_content($content){
        if(empty($content))return false;
        $content=h($content);
        $baseurl='http://'.$_SERVER['HTTP_HOST'].__ROOT__;
        $contentarr = $content;
        preg_match_all("/<img(.*)(src=\"[^\"]+\")[^>]+>/isU", $contentarr, $arr);
        $images = array();
        foreach($arr[0] as $key=>$val){
            $match = array();
            preg_match('/<img.*?src="(.*?)".*?>/is',$val,$match);
            if(str_exists($match[1],'http')||str_exists($match[1],'https')){
                $images['images']['images'.$key] = $match[1];
            }else{
                $images['images']['images'.$key] = $baseurl.$match[1];
            }
            
            $contentarr = str_replace($val,'<img v-lazy="this.xqimages.images'.$key.'">',$contentarr);
        }
        $images['content'] = $contentarr;
        return $images;
    }
    /****/
    function StrToparamArray($str=''){
        $str=html_entity_decode($str);
        if(is_string($str)&&!empty($str)){
            $data = array();
            $arr = explode('^',$str);
            foreach ($arr as $val) {
                if(empty($val))continue;
                $d = array();
                $d = explode('/=/',$val);
                if(is_string($d[1])){
                    $tobj = array();
                    $tarr = explode('@',$d[1]);
                    foreach ($tarr as $v) {
                        if(empty($v))continue;
                        $dt = explode('___',$v);
                        $tobj[$dt[0]] = $dt[1];
                    }
                    $data[$d[0]] = $tobj;
                }else{
                    $data[$d[0]] = $d[1];
                }
            }
            return $data;
        }
        return array();
    }
}
?>