<?php
/**
  * @class 基类
  * @author soul
  */
class baseAction
{
	public $supData = null;
	public $ypNoticeCatId = 1012;
	//只能调用/static/目录下的 js | css | 控件[webuploader、datetimepicker、ueditor、zTree]
    private $HEAD_CSSJS = ['css'=>['css/seller.css', 'css/order.css'], 'js'=>['js/seller.js', 'js/order.js'], 'plugin'=>[]];

	public function __construct()
	{
		$Params = mvc::$URL_PARAMS;
		LibFc::useMainDb();
		//是否为简版目录
		mvc::$cfg['isSuper'] = 0;
		//是否为联动版公众号或者商城
		mvc::$cfg['isGzhShop'] = 0;
		//是否有机器人
		mvc::$cfg['robotArr'] = [];
		//是否开启店铺同步设置
		mvc::$cfg['hasShopSynch'] = 0;
		//登录校验
		$nowFun = mvc::$URL_CLASS.'/'.mvc::$URL_METHOD;
		//忽略登录的接口
		$ignoreLoginFunArr = ['index/imgcode','index/checkImgcode', 'index/sendMobilecode', 'index/checkMobilecode', 
			'user/login', 'user/status','user/logout', 'user/ajaxLogin', 'user/loginByQQ', 'user/loginByWx','user/checkUnique','user/getPassword','user/ajaxSetPassword', 'user/ajaxBindMobile', 'user/getLoginEwm', 'user/checkEwmIsLogin','shop/updateMdErpProduct','shop/updateBdErpProduct','shop/updateMdProCount'
		];
		LibTpl::Set('HEAD_CSSJS', $this->HEAD_CSSJS);
		if(empty($_SESSION['_shopid'])){
			//自动登录
			if(!empty($_COOKIE['_unitag'])){
				$LibPjlApi = new LibPjlApi();
				$res = $LibPjlApi->Get('base/login', [], ['type'=>'unitag', 'unitag'=>$_COOKIE['_unitag']], true);
				if($res['status'] && !empty($res['data'])){
					$this->initLogin($res['data'], 1);
				}else{
					$this->clearLogin();
				}
			}
		}
		//API接口访问统计报表URL  /tj/ypBrandCharts?level=brand&token=xxxx
		if(!empty($Params['token']) && mvc::$URL_CLASS == 'tj'){//&& empty($_SESSION['_shopid']) 
			$MainBase = new MainBase();
			$now = time();
			$where = sprintf(" and aut_token='%s' and aut_etime>%d and au_status=1 and au_btime<%d and au_etime>%d", LibFc::Escape($Params['token']), $now, $now, $now);
			$res = $MainBase->get('api_user_token join api_user on au_appkey = aut_appkey', ['au_uid', 'au_act', 'au_comname'], $where, true);
			if(empty($res['data'])){
				exit('token失效，请重新获取');
				//LibTpl::Error('token无效', mvc::$cfg['SELF_URI'].'user/login'); 
			}
			$tokenInfo = $res['data'];
			$_SESSION['_loginby'] = 'API';
			$_SESSION['_shopid'] = $tokenInfo['au_uid'];
			$_SESSION['_shopowner'] = true;
			$_SESSION['supData'] = [
				'shop_id'=>$_SESSION['_shopid'],
				'shop_report_industry'=>time()+7200	
			];
		}

		if(empty($_SESSION['_shopid']) && !in_array($nowFun, $ignoreLoginFunArr))
			Header("Location: ".mvc::$cfg['SELF_URI'].'user/login?goto='.urlencode(LibFc::nowUrl()));
		if($_SESSION['_loginby'] == 'API'){
			$this->supData = $_SESSION['supData'];
		}else if(!empty($_SESSION['_shopid'])){
			if($nowFun == 'user/login') Header("Location: ".mvc::$cfg['SELF_URI']);
			
			$B2cBase=new B2cBase();
			$res = $B2cBase->get('sh_super join sh_shop on shop_id = ssu_shop_id', ['*'],  sprintf(" and ssu_shop_id=%d", $_SESSION['_shopid']), true);
			$res['data']['ssu_module']=!empty($res['data']['ssu_module'])?explode(',',$res['data']['ssu_module']):[];
			$adminfield = $res['data']['shop_mod_adminfield']?explode(',',$res['data']['shop_mod_adminfield']):[];
			$modArr = [
				'mod3_kw'=>'功率','mod3_cc'=>'排量','mod3_engine'=>'发动机','mod3_transmission'=>'变速器',
				'mod3_fuel'=>'燃料','mod3_body'=>'车身形式','mod3_front_brake'=>'前制动器','mod3_rear_brake'=>'后制动器',
				'mod3_parking_brake'=>'驻车制动','mod3_drive'=>'驱动方式','mod3_start_stop'=>'自动启停','mod3_chassis'=>'底盘'
			];
			$temp = [];
			foreach ($adminfield as $key => $val) {
				$temp[$val] = $modArr[$val];
			}
			$res['data']['shop_mod_adminfield'] = $temp;
			
			$this->supData = $res['data'];
			LibTpl::Set('supArr', $this->supData);
			
			//店铺同步设置
			$res = $B2cBase->get('sh_shop_synch',["count(*) as count"],sprintf(" and sss_shop_id_to = %d",$_SESSION['_shopid']),true);
			mvc::$cfg['hasShopSynch'] = $res['data']['count']??0;

			mvc::$cfg['isSuper'] = in_array('super', $_SESSION['_shoptype']) ? 1: 0;
			mvc::$cfg['isGzhShop'] = in_array('gzhShop', $_SESSION['_shoptype']) ? 1: 0;
			mvc::$cfg['hasModule'] = '';
			if(in_array('user',$this->supData['ssu_module']) && in_array('price',$this->supData['ssu_module']))
			{
				mvc::$cfg['hasModule'] = 'all';
			}
			else
			{
				if(in_array('user',$this->supData['ssu_module']))
					mvc::$cfg['hasModule'] = 'user';
				if(in_array('price',$this->supData['ssu_module']))
					mvc::$cfg['hasModule'] = 'price';
			}
			mvc::$cfg['LOGUSER'] = $_SESSION['LOGUSER'];
			
		}

	}
	

	//初始化用户登录数据
	protected function initLogin($userData, $remember)
	{
		$_SESSION['_loginby'] = '';
		$B2cBase=new B2cBase();
		$res = $B2cBase->get('sh_shop', ['shop_id'], sprintf(" and shop_uid=%d and shop_status = 1", $userData['u_id']), true);
		$workRealName = '';
		if(!empty($res['data']))
		{
			$_SESSION['_shopid'] = $res['data']['shop_id'];
			$_SESSION['_shopowner'] = true;
			$_SESSION['_mobliechk'] = $userData['u_mobile_check'];
		}
		else
		{
			//是否为店铺职员
			$res = $B2cBase->get('sh_worker', ['wor_shop_id', 'wor_rule_ids','wor_real_name'], sprintf(" and wor_uid=%d and wor_status=1 limit 1", $userData['u_id']), true);
			if(!empty($res['data']))
			{
				$_SESSION['_mobliechk'] = 'Y';
				$_SESSION['_shopid'] = $res['data']['wor_shop_id'];
				$_SESSION['_shopowner'] = false;
				$_SESSION['_rules'] = explode(',', $res['data']['wor_rule_ids']);
				$workRealName = $res['data']['wor_real_name'];
			}
		}
		if(!empty($_SESSION['_shopid']))
		{
			$_SESSION['_unitag'] = $userData['unitag'];
			$_SESSION['_userid'] = $userData['u_id'];
			$_SESSION['_username'] = $userData['u_name'];

			$time = !empty($remember)? time()+86400*30: null;
			setcookie('_unitag', $_SESSION['_unitag'], $time, '/');

			$_SESSION['_shoptype'] = [];
			$res = $B2cBase->get('sh_super', ['ssu_id'], sprintf(" and ssu_status=1 and ssu_shop_id=%d and ssu_etime >=%d", $_SESSION['_shopid'], time()), true);
			if(!empty($res['data']))
				$_SESSION['_shoptype'][] = 'super';
			$res = $B2cBase->get('sh_shop_app', ['aps_shop_id'], sprintf(" and aps_status=1 and aps_shop_id=%d and aps_etime >=%d", $_SESSION['_shopid'], time()), true);
			if(!empty($res['data']))
				$_SESSION['_shoptype'][] = 'gzhShop';

			$B2cShop = new B2cShop();
			$shopData = $B2cShop->getShopInfo($_SESSION['_shopid']);
			LibTpl::Set('shopData', $shopData['data']);

			$_SESSION['LOGUSER']['uid'] = $_SESSION['_userid'];
			if($workRealName){
				$_SESSION['LOGUSER']['urname'] = $workRealName;
			}else{
				$_SESSION['LOGUSER']['urname'] = $userData['u_real_name']?$userData['u_real_name']:($userData['u_nickname']?$userData['u_nickname']:$userData['u_name']);
			}
			return true;
		}
		else
		{
			if(ISAJAX)
			{
				LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'您尚未开通目录！', 'code'=>'noSuper']);
			}
			else
			{
				LibTpl::Error('您尚未开通目录！', mvc::$cfg['SELF_URI'].'user/login');
				exit;
			}
		}
	}
	
	protected function clearLogin()
	{
		unset($_SESSION['_unitag']);
		unset($_SESSION['_userid']);
		unset($_SESSION['_shopid']);
		unset($_SESSION['_username']);
		unset($_SESSION['_pjltoken']);
		setcookie('_unitag', '', time()-3600, '/');
	}

	//对URI解密
	protected function decodeUri($str)
	{
		$str = base64_decode($str);
		$LibEncry = new LibEncry();
		$uri = $LibEncry->decode($str);
		parse_str($uri, $uriArr);
		return $uriArr;
	}
	
	//对URI加密
	protected function encodeUri($str)
	{
		$LibEncry = new LibEncry();
		return base64_encode($LibEncry->encode($str));
	}
	
	//权限检测
	public function checkRule($ruleId, $exit = true)
	{
		if(!empty($_SESSION['_shopowner']) || in_array($ruleId, $_SESSION['_rules']))
		{
			return true;
		}
		else
		{
			if(ISAJAX)
			{
				LibFc::ajaxJsonEncode(['status'=>false, 'data'=>'无权限操作，拒绝访问', 'noRule']);
			}
			else if($exit)
			{
				LibTpl::Error('无权限操作，拒绝访问');
				exit;
			}
			else
			{
				return false;
			}
		}
	}
}