<?php
/**
  * 系统公共函数库
  * @Copyright (C) 2016 汉朝 All rights reserved.
  * @License http://www.hanchao9999.com
  * @Author xiaogg <xiaogg@sina.cn>
  */
const HANCHAO_CACHE_MODEL ='AuthRule,ArticleCat,Nav,Type,ShopsCategory,PurchaseCategory';
/**
  *数组转换为字符串 用于 tag
  */
function arraytostr($array) {
    if(!is_array($array))return $array;
    foreach($array as $k=>$v){$retarr[]=$k.'|'.$v;}
    if($retarr)$return=implode(',',$retarr);
    return $return;
}
/**
  *字符串转换为数组 用于 tag
  */
function strtoarray($str,$type='key') {
    if(is_array($str))return $str;
    if(empty($str))return false;
    $array=array();$typekey='key';
    if(str_exists($str,'typeid_')) {
        $typeid=floor(strtr($str,array('typeid_'=>'','temp_'=>'')));
        if(str_exists($str,'temp_')){$type='temp';}
        if($typeid)$array=gettypeson($typeid,$type);
    }
    if(!$array) {
        $str=str_replace(PHP_EOL,',',$str);
        $strarr=array_map('trim',explode(',', $str));
        $array =array_values(array_filter($strarr));
    }
    foreach ($array as $k=> $v) {
        if (strpos($v, '|')) {$varr = explode('|', $v);
            $return[$varr[0]] = str_exists($varr[1],'LAN_')?L(str_replace('LAN_','',$varr[1])):$varr[1];
        }else{
           if(strpos($v,':')){
                $varr = explode(':', $v);
                $return[$varr[0]] = str_exists($varr[1],'LAN_')?L(str_replace('LAN_','',$varr[1])):$varr[1];
           }else{
                $arrkey=$typekey=='key'?$k:$v;
                $return[$arrkey] =str_exists($v,'LAN_')?L(str_replace('LAN_','',$v)):$v;
           }
       }
    }
    return $return;
}
/**
  *获取类别的所有下级
  */
function gettypeson($typeid, $type = 'key'){
    $options=array();$types = getcache('Type');
    foreach ($types as $key => $r){
        if ($r['pid'] == $typeid){if ($type=='key')$k = $key;else $k = $r[$type];$options[$k] = $r['name'];}
    }
    return $options;
}
function gettypevalue($typeid,$field='name',$where='id',$pid=''){
    $types=getcache('Type');
    if($where=='id' || $where=='temp'){
        $typeids=is_array($typeid)?$typeid:(str_exists($typeid,',')?explode(',',$typeid):array($typeid));
        $valarr=array();$newtypes=array();
        if($where=='temp'){
            foreach($types as $k=>$v){
                if($pid){
                    if($pid==$v['pid'] && isset($v['temp']))$newtypes[$v['temp']]=$v;
                }else{
                    if(isset($v['temp']))$newtypes[$v['temp']]=$v;
                }
            }
        }else{$newtypes=$types;}
        foreach($typeids as $v){
            if(isset($newtypes[$v][$field]))$valarr[]=$newtypes[$v][$field];
        }
        return implode(',',$valarr);
    }
    foreach($types as $k=>$v){
        if($pid && $pid!=$v['pid'])continue;
        if($v[$where]==$typeid){return $field=='*'?$v:$v[$field];}
    }
    return false;
}
//获取导航
function nav_list($navtype=0,$pid=0,$return=''){
    $name='Nav';
    $nav_list=format_array2tree(getcache($name),$pid);
    $nowurl=strtolower(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME);$baseurl='';
    $now_url=strtolower($_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:$_SERVER['PHP_SELF']);
    $hovernav=$hovernavtrue='0';
    foreach($nav_list as $k => $v){
        if($navtype!=$v['navtype']){unset($nav_list[$k]);continue;}
        if(!str_exists($v['url'],'http://')){
            $realurl=strtolower(geturl($v['url']));
            $create_url=strtr($v['url'],array('?'=>'/','='=>'/','&'=>'/'));
            if(str_exists($now_url,$create_url) || str_exists($now_url,$realurl) || str_exists($now_url,str_replace('Home/','',$create_url)))$hovernav=$k;
            if(empty($hovernav)){
                $urlinfo=parse_url(strtolower($v['url']));
                $basearr=explode('/',$urlinfo['path']);         
                if(count($basearr)==1)$baseurl=MODULE_NAME."/".CONTROLLER_NAME."/".$urlinfo['path'];            
                elseif(count($basearr)==2)$baseurl=MODULE_NAME."/".$urlinfo['path'];else  $baseurl=$urlinfo['path'];
                $baseurl=strtolower($baseurl);
                if($nowurl==$baseurl && !$hovernav){$hovernav=$k;}
            }
        }
    }
    $nav['list']=$nav_list;
    $nav['hover']=$hovernav;
    $nav['hovernavtrue']=$hovernavtrue;
    return $return?$nav[$return]:$nav;
}
//获取缓存
function getcache($name=''){
    if(empty($name))return false;
    $patharr=array('GoodsCategory','PurchaseCategory');
    $cachedata=in_array($name,$patharr)?F('../'.$name):F($name);
    if($cachedata)return $cachedata;
    else{return savecache($name,1);}
}    
function format_array2tree($cachedata,$pid=0){
    if(empty($cachedata))return false;
    $Tree = new \Common\Vendor\Tree();
    $Tree->init($cachedata);
    return $Tree->get_tree_array($pid);
}   
/**
 * 验证权限
 * @param $str 权限字符串 , 并且 |或者
 */
function checksiteauth($str=''){
	if(empty($str))return false;
	$authlist=M('SiteInfo')->where('id=1 and status=1')->cache(true)->getField('package_auth');
    if(empty($authlist))return false;
	$auth=explode(',',strtolower($authlist));
    $str=strtolower($str);
    if(strpos($str,',')){//必须全满足才可以
        $arr=explode(',',$str);
        foreach($arr as $v){
            if(!in_array($v,$auth))return false;
        }return true;
    }
    if(strpos($str,'|')){//有一个满足就可以
        $arr=explode('|',$str);
        foreach($arr as $v){
            if(in_array($v,$auth))return true;
        }return false;
    }
    return in_array($str,$auth);
}
//保存缓存
function savecache($name = '', $type = ''){    
    $cache_model=explode(',',HANCHAO_CACHE_MODEL);//后台缓存模型
    if(!in_array($name,$cache_model))return false;
    if(!defined('RUNTIME_FILE'))define('RUNTIME_FILE',APP_PATH.'Runtime/');
    if(file_exists(RUNTIME_FILE))unlink(RUNTIME_FILE);
    $Model = M($name);$list=$data= array();
    $allpas=array('GoodsCategory','ArticleCat','PurchaseCategory');
    $patharr=array('GoodsCategory','PurchaseCategory'); 
    if ($name == 'User'){
        $list = $Model->where("status=1")->field(true)->select();		
        foreach ($list as $v){unset($v['password']);$data[$v['id']] = $v;}
        F($name, $data);
    }else if (in_array($name,array('Payment','Oauth'))){
        $list = $Model->where("status=1")->field(true)->select();
        foreach ($list as $v){$data[$v['code']] = $v;}F($name, $data);
    }else if ($name == 'AuthRule'){
        $list = $Model->field(true)->order('sort,id desc')->select();
        foreach ($list as $key => $val){
            $data[$val['id']] = $val;
        }F($name, $data);
        $AdminGroup = M('AuthGroup')->where('status=1')->field('id,rules')->select();
        foreach ($AdminGroup as $groupValue) {
	$ruleCache = F("admin_rule_{$groupValue['id']}");
	if (empty($ruleCache)){
              if(empty($groupValue['rules'])) $groupValue['rules']=0;
        	   $ruleData = $Model->where("id IN({$groupValue['rules']})  AND status=1")->order('sort,id desc')->getField('id,name,title,show_status,type,condition,pid,sort,icon');
        	   F("admin_rule_{$groupValue['id']}",$ruleData);
          }
          unset($ruleCache);
        }
        unset($AdminGroup);
    }else{
        $allfields=$Model->getDbFields();
        $pkid = $Model->getPk();
        $order='';
        $map=array();
        if(in_array('status',$allfields))$map['status'] = 1;
        if(in_array('sort',$allfields))$order.='sort,';
        $order.=$name=="Area"?$pkid:$pkid.' desc';
        $list = $Model->field($allfields)->where($map)->order($order)->select();
        foreach ($list as $key => $val){
            $data[$val[$pkid]] = $val;
            if(in_array($name,$allpas)){
                $data[$val[$pkid]]['allparent']=getallparent($val[$pkid],'',$name);
                $allson=getallson($val[$pkid],$name);
                $data[$val[$pkid]]['allson']=implode(',',$allson);
            }
        }
        in_array($name,$patharr)?F('../'.$name,$data):F($name, $data);
    }
    // var_dump($data);
    if(!empty($type)){unset($list);return $data;}
    else{unset($list,$data);return true;}
}
//获取链接规则
function geturlrules($device){
    $map=array();
    $map['status']=1;
    $map['_string'] = "device like '%,".$device.",%' or device='".$device."'";
    $data=M('UrlRules')->where($map)->field(true)->select();
    return $data;
}
/**
  * 万能获取字段 idtoname
  * @param  integer $uid 用户ID
  * @return string
  */
function idtoname($id,$mod='GoodsCategory',$field='name',$sekey='id',$cache=true){
    if(empty($id))return false;$mod=trim($mod);
    if($mod=='GoodsCategory'){GLOBAL $GoodsCategory;if(!empty($GoodsCategory))$cachemod=$GoodsCategory;}
    if(empty($cachemod))$cachemod=getcache($mod);
    if($cachemod && $sekey=='id'){
        return $field=='*'?$cachemod[$id]:$cachemod[$id][$field];
    }else{
        if($field=='*')$field=true;
        $where[$sekey]=$id;
        $fieldstr=str_exists($field,';')?str_replace(';',',',$field):$field;
        if(str_exists($field,','))$fieldstr="`".str_replace(',','`,`',$fieldstr)."`";
        if($cache===true)$cache='idtoname'.$id.$mod.$field.$sekey;
        $result=M($mod)->where($where)->field($fieldstr)->cache($cache)->find();
        if($cache && is_string($result) && substr($result,0,6)=='SELECT')return false;
        return ($field=='*' || str_exists($field,','))?$result:idtonamevalue($result,$field);
    }
}
/**
  *idtoname辅助
  */
function idtonamevalue($value,$field){
    if(empty($value) || empty($field))return false;
    $array=explode(';',$field);
    foreach($array as $v){
        if($value[$v])return $value[$v];
    }
    return false;
}
/**
  * 获取所有子ID
  * @param string $pid
  * @param string $mod 模块
  * @param array $param 参数
  * @param int $length 最大层级
  */
function getallson($pid,$modname='Category',$me='1',$length=5){
    if(empty($pid))return false;
    $mod=M($modname);
    if($me)$son[$pid] = $pid;else $son='';
    $pids[]=$pid;$i=0;    
    do{
        if(empty($pids))break;
        $map=array('pid'=>array('in',$pids));
        $sondata=$mod->where($map)->cache(true)->field('id,pid')->select();
        $pids=array();
        if($sondata){
            foreach ($sondata as $v) { 
               $son[] = $v['id'];$pids[]= $v['id'];
            }
        }++$i;if($i==$length)$sondata=array();
    }while (!empty($sondata));
    return $son;
}
/**
  * 获取父ID
  * @param int $id 本身ID
  * @param array $arrparentid 附加的父ID
  * @param string $mod 模型名称
  * @param int $length 最大层级
  **/
function getallparent($id, $arrparentid = '',$mod='Category',$length=5) {
    if(empty($id))return false;
    if(!empty($arrparentid) && !is_array($arrparentid))$arrparentid=explode(',',$arrparentid);
    $ids =isset($arrparentid)?$arrparentid: array();$i=0;
    do{
        $pidinfo = M($mod)->where('id='.$id)->cache(true)->field('pid')->find();
        $ids[] = $id = intval($pidinfo['pid']); 
        ++$i;if($i==$length)$id=0;  
    }while($id!=0);    
    return implode(',',$ids);
}
/**
  * 用于linkage获取关联值
  * @param int $id 本身ID
  * @param string $mod 模型名称
  * @return string
  **/
function linkagevalue($id,$mod='Area'){
    $length=C('ZONE_LEVEL');
    if(empty($id) || str_exists($id,','))return false;    
    $ids[]=$id;$i=0;
    do{
        $map=array();
        $map['id']=$id;
        $map['pid']=array('gt',1);
        $pidinfo = M($mod)->where($map)->cache(true)->field('pid')->find();
        $ids[] = $id = intval($pidinfo['pid']); 
        ++$i;if($i==$length)$id=0;  
    }while($id!=0);
    $id_arr=array_filter($ids);krsort($id_arr);
    return implode(',',$id_arr);
}
/**
 * 多个ID查询名称 主要用于多地区id获取名称
 * @param array $ids id数组或字符
 * @param $model 数据库
 * @param $field 要查询的字段
 * @param $where
 * @param $pre 分隔符号
 */
function idstonames($ids,$model='Area',$field="name",$where='id',$pre=','){
    if(empty($ids))return false;
    $map=array();    
    $map[$where]=is_array($ids) || strpos($ids,',')?array('in',$ids):$ids;
    $names=M($model)->where($map)->cache(true)->getField($field,true);
    return $names?implode($pre,$names):'';
}
/**
  * 记录行为日志，并执行该行为的规则
  * @param string $action 行为标识
  * @param string $model 触发行为的模型名
  * @param int $record_id 触发行为的记录id
  * @param int $user_id 执行行为的用户id
  * @param int $mark 自定义备注
  * @return boolean
  */
function action_log($action = null, $model = null, $record_id = null, $user_id = null,$mark=null){
    if(empty($action) || empty($model) || empty($record_id)){return '参数不能为空';}
    if(empty($user_id)){$user_id = is_login();}    
    $action_info = M('Action')->getByName($action);//查询行为,判断是否执行
    if($action_info['status'] != 1){return '该行为被禁用或删除';}
    //插入行为日志
    $data['action_id']      =   $action_info['id'];
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   get_client_ip(1);
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   NOW_TIME;
    //解析日志规则,生成日志备注
    if(!empty($action_info['log'])){
        if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   NOW_TIME;
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>NOW_TIME);
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){$replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{$replace[] = $log[$param[0]];}
            }$data['remark'] =   str_replace($match[0], $replace, $action_info['log']);
        }else{$data['remark'] =   $action_info['log'];}
    }else{$data['remark']     =   '操作url：'.$_SERVER['REQUEST_URI'];} //未定义日志规则，记录操作url
    if(!empty($mark))$data['mark']=$mark; 
    M('ActionLog')->add($data);
    if(!empty($action_info['rule'])){
        $rules = parse_action($action, $user_id);//解析行为
        $res = execute_action($rules, $action_info['id'], $user_id);//执行行为
    }
}
/**
  * 解析行为规则
  * 规则定义  table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
  * 规则字段解释：table->要操作的数据表，不需要加表前缀；
  * field->要操作的字段；
  * condition->操作的条件，目前支持字符串，默认变量{$self}为执行行为的用户
  * rule->对字段进行的具体操作，目前支持四则混合运算，如：1+score*2/2-3
  * cycle->执行周期，单位（小时），表示$cycle小时内最多执行$max次
  * max->单个周期内的最大执行次数（$cycle和$max必须同时定义，否则无效）
  * 单个行为后可加 ； 连接其他规则
  * @param string $action 行为id或者name
  * @param int $self 替换规则里的变量为执行用户的id
  * @return boolean|array: false解析出错 ， 成功返回规则数组
  * @author huajie <banhuajie@163.com>
  */
function parse_action($action = null, $self){
    if(empty($action)){return false;}
    //参数支持id或者name
    if(is_numeric($action)){$map = array('id'=>$action);}else{$map = array('name'=>$action);}    
    $info = M('Action')->where($map)->find();//查询行为信息
    if(!$info || $info['status'] != 1){return false;}
    //解析规则:table:$table|field:$field|condition:$condition|rule:$rule[|cycle:$cycle|max:$max][;......]
    $rules = $info['rule'];
    $rules = str_replace('{$self}', $self, $rules);
    $rules = explode(';', $rules);
    $return = array();
    foreach ($rules as $key=>&$rule){
        $rule = explode('|', $rule);
        foreach ($rule as $k=>$fields){
            $field = empty($fields) ? array() : explode(':', $fields);
            if(!empty($field)){$return[$key][$field[0]] = $field[1];}
        }
        //cycle(检查周期)和max(周期内最大执行次数)必须同时存在，否则去掉这两个条件
        if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){
            unset($return[$key]['cycle'],$return[$key]['max']);
        }
    }
    return $return;
}
/**
  * 执行行为
  * @param array $rules 解析后的规则数组
  * @param int $action_id 行为id
  * @param array $user_id 执行的用户id
  * @return boolean false 失败 ， true 成功
  */
function execute_action($rules = false, $action_id = null, $user_id = null){
    if(!$rules || empty($action_id) || empty($user_id)){return false;}
    $return = true;
    foreach ($rules as $rule){//检查执行周期        
        $map = array('action_id'=>$action_id, 'user_id'=>$user_id);
        $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600);
        $exec_count = M('ActionLog')->where($map)->count();
        if($exec_count > $rule['max']){continue;}
        $modname=ucfirst($rule['table']);
        $Model = M($modname);//执行数据库操作
        $field = $rule['field'];
        $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule']));
        $fieldarr=array('points'=>'3','usepoints'=>'4','money'=>'1','frozen_money'=>'2');
        if(isset($rule['rule']) && in_array($modname,array('Member')) && in_array($field,array_keys($fieldarr))){
            $value=str_replace($field,'',$rule['rule']);            
            account_change($user_id,$value,$fieldarr[$field],5);
        }
        if(!$res){$return = false;}
    }
    return $return;
}
/**
  * 获取资金变更对应数组
  * @param $key
  * @param $field
  */
function account_changetype($key='',$field=''){
    $array=array(
    1=>array('field'=>'money','name'=>"资金"),
    2=>array('field'=>'frozen_money','name'=>"冻结资金"),
    3=>array('field'=>'points','name'=>C('RANK_INTEGRAL_NAME')),
    4=>array('field'=>'usepoints','name'=>C('SELL_INTEGRAL_NAME')),
   // 5=>array('field'=>'credit','name'=>'信用'),
   // 6=>array('field'=>'quota','name'=>'信用额度'),
   7=>array('field'=>'recharge_points','name'=>'累计充值'),
   8=>array('field'=>'comm_money','name'=>'返利佣金'),
    );
    if(empty($key) && empty($field))return $array;
    if(!empty($key) && empty($field))return $array[$key]['name'];
    if(!empty($key) && !empty($field))return $array[$key][$field];
    return false;
}
/**
  * 会员资金积分变动记录
  * @param int $userid 变动会员ID
  * @param int $amount 变动数量
  * @param int $type 变动类型1:money资金2:frozen_money冻结资金3:points累计消费,4:usepoints消费积分,5:credit信用,6:quota借款额度 7：recharge_points 累计充值 8：comm_money 返利佣金
  * @param int $status 操作类型1为充值,2为提现,3管理员变更,4支付,5为系统,8退款,10其他 （11多倍积分13会员关怀14小票抽奖15全民发券领奖  已去掉）
  * @param string $note 操作备注
  * @param int $adminid 操作管理员ID
  * @param boolean $do 是否网站执行 true 网站 false 日志
  * @param int $role 角色角色 0会员 1店铺 2供货商 3平台等等 5导购员  
  * @param int $share_id 分红id
  */
function account_change($userid, $amount ,$type='0', $status='4', $note = '',$adminid='0',$do=TRUE,$role='0',$share_id='0') {
    $allowfields=account_changetype();
    if(empty($allowfields) || !is_array($allowfields))return false;
    if(empty($userid) || empty($amount) || floatval($amount)=='0' || empty($allowfields[$type]))return false;
    $field=$allowfields[$type]['field'];

    switch($role){
        case 0:
            $Member=M('Member');break;
        case 1:
            $Member=M('Shops');break;
        case 2:
            $Member=M('Suppliers');break;
        case 5:
            $Member=M('ShopsAccount');break;
    }
    $where=array();
    $where['id']=$userid;
    $amount=round($amount,2);
    if($amount>0){
        if($do)$Member->where($where)->setInc($field,$amount);
        $data['change_type']='0';
        $data['change_num']=$amount;
    }else{
        if($do)$Member->where($where)->setDec($field,-$amount);
        $data['change_type']=1;
        $data['change_num']=-$amount;
    }$member_info=session('member_info');
    if($do && $userid==$member_info['id'])updatesession($userid);
    $data['uid']=$userid;
    $data['role']=$role;
    //$data['end_num']=$Member->where("`id`='".$userid."'")->getField($field);
    $data['adminid']=$adminid;
    $data['change_time']=NOW_TIME;
    $data['change_desc']=$do?$note:$note;
    $data['type']=$type;
    $data['status']=$status;
    $data['storeid']=$share_id;
    $AccountLog=M('AccountLog');
    if($note!='NULL')$insertid=$AccountLog->add($data);
    unset($data);
    $where['id'] = $userid;
    $member = M('Member')->where($where)->field('code,card_sn,card_id,usepoints,mobile,username,money,id')->find();
    if($type==4 && $member['code']){
        $Weixin = new \Common\Vendor\WeixinCard();
        $data['code'] = $member['code'];
        $data['card_id'] = $member["card_id"];
        $data['bonus'] = $member['usepoints'];
        $data['add_bonus'] = $amount;
        $data['record_bonus'] = $note;
        $Weixin->updateuser($data);
    }elseif($type==1 && $role == 0){
        if($status == 1){
            $status = '充值';
        }elseif($status == 4){
            $status = '消费';
        }elseif ($amount>0) {
            $status = '增加';
        }elseif ($amount<0) {
            $status = '减少';
        }
        $abs_amount = abs($amount);
        $time = date('Y-m-d H:i:s',NOW_TIME);
        $rep_arr=array('[$name]'=>$member['username'],'[$time]'=>$time,'[$status]'=>$status,'[$amount]'=>$abs_amount,'[$money]'=>$member['money']);
        $map = array();
        $map['code'] = 'BALANCE_INFORM_NOTE';
        $sms_theme = M('SmsTheme')->where($map)->field(true)->find();
        $sms_theme['content'] = strtr($sms_theme['content'],$rep_arr);
        $type_array=explode(',',$sms_theme['type']);
        foreach($type_array as $v){
            if($v == 4){
                $data=$sms_theme;
                $data['to']=$member['id'];
                $data['money']=$amount>0?'增加'.$amount:'减少'.-$amount;
                $data['time']=$time;
                $data['url']=U('Mobile/Capital/index','',true,true);
                $data['theme_data']=strtoarray($sms_theme['theme_data']);
                send_method(4,$data);
            }elseif($v == 2){
                if(strpos($sms_theme['content'],'[') !== false){
                    $sms_theme['content'] = $sms_theme['content'];
                }else{
                    $sms_theme['content'] = $sms_theme['content'].'退订回N';
                }
                sendsms($member['mobile'],$sms_theme['content'],'',$userid);
            }
        }
    }
    return $insertid;
}
//更新会员和管理员session
function updatesession($id,$type='member_info'){
    if(empty($id))return false;
    $modulename=str_replace('_','',ucwords(str_replace('_info','',$type)));
    $info=idtoname($id,$modulename,'*','id',false);
    $info[$type.'_auth_sign'] = data_auth_sign($info,$type);
    session($type, $info);
}
/**
  *根据规则变动
  * @param int $userid 变动会员ID
  * @param int $id     规则ID
  * @param int $note   备注
  */
function rolechange($userid,$id,$note=''){
    if(empty($userid) || empty($id))return false;
    $PointsRule=getcache('PointsRule');
    $role=$PointsRule[$id];if(empty($role))return false;
    if(empty($note))$note=$role['name'];
    account_change($userid, $role['value'] ,$type,5, $note);
    if($type==3){account_change($userid, $role['value'] ,4,5, $note);}return true;
}
//计算手续费
function getfeemoney($money,$fee='',$type=''){
    if($fee<=0)return 0;
    $money_fee=sprintf("%.2f",$money*$fee/100);
    if($type)return $money+$money_fee;else return $money_fee;
}
/**
  *发送信息方法调用
  *$type  1是发送邮件，2是发送短信，3是发送站内信，4是发送微信消息，5是发送app消息,6小程序
  *$data  $data['to']是给谁发  $data['from']是谁发送的  $data['title']发送消息标题   $data['content']发送内容  $data['type']只针对站内信（1是会员，2是店铺，3是供货商）
  */
function send_method($type,$data){
    if(empty($data))return false;
    if(empty($type))$type=1;
    switch($type){
        case 1:
            if(empty($data['to']) || empty($data['from']) || empty($data['title']) || empty($data['content'])) return false;
            $result=sendmail($data['to'],$data['from'],$data['title'],$data['content'],'',$data['verify_code'],$data['touid']);
            return $result;
        break;
        case 2:
      //  print_r($type);print_r($data);exit;
            if(empty($data['to']) || empty($data['content'])) return false;
            $result=sendsms($data['to'],$data['content'],$data['verify_code'],$data['touid'],$data);
            return $result;
        break;
        case 3:
            if(empty($data['to']) || empty($data['content'])) return false;
            $result=sendsitesms($data['to'],$data['content'],$data['title'],$data['from'],$data['type']);
            return $result;
        break;
        case 4:
            if(empty($data['to']) || empty($data['content'])) return false;
            $result=sendwxmsg($data['to'],$data['content'],'text','uid',$data);
            return $result; 
        break; 
        case 5:
            if(empty($data)) return false;
            $map=array();
            $map['touid']=$data['to'];
            $map['type']=2;
            $map['status']=0;
            $count=M("Message")->where($map)->count();
            $param=array('type'=>3,'txt'=>$count);
            $ids=getpushids();            
            if(!empty($ids[1]))$result = pushSend($ids[1],$data['content'],$data['push_type'],1,$param);
            if(!empty($ids[2]))$result = pushSend($ids[2],$data['content'],$data['push_type'],2,$param);
            return $result;
        break;
        case 8:
            if(empty($data['to']) || empty($data['pay_id'])) return false;
            $map=array();
            $map['id']=$data['pay_id'];
            $pay_info=M("PayLog")->where($map)->field(true)->find();
            $data['wxsmall_formid_cache']=$pay_info['wxsmall_formid_cache'];
            $data['order_id']=$pay_info['order_id'];
            $data['order_sn']=$pay_info['order_sn'];
            $data['user_id']=$pay_info['user_id'];
            $data['order_total_price']=$pay_info['order_total_price'];
            $result=D("Common/OrderInfo")->send_wxsmall_message($data);
            return $result;
            break;
        default:
        break;
    }
}
function sendwxsmallmsg($data=array()){
    if(empty($data)) return false;
}
/**
  *发送信息 根据模板定义的内容发送消息 
  */
function sendbytheme($data,$theme='',$url=''){
    if(empty($theme) || empty($data['to']))return '发送失败';
    $data['site_name']=C('WEB_SITE_NAME');
    $data['site_url']=geturl('Home/Index/index','',true,true);
    //主页链接
    $data['url']=$url?$url:$data['site_url'];
    if($data['type']==2) {//给店铺发消息的时候
    }else{
        $memberinfo = session('member_info');
        if (empty($data['username'])) {$data['username'] = $memberinfo['username'];}
    }
    $themeinfo=idtoname($theme,'SmsTheme','name,content,type,theme_id,theme_data,theme_remark,code,status','code');
    if($themeinfo && $themeinfo['status']==0)return '已关闭此短信发送';
    $data['theme_id']=$themeinfo['theme_id'];
    $data['theme_data']=strtoarray($themeinfo['theme_data']);
    $data['theme_remark']=$themeinfo['theme_remark'];
    $type_array=explode(',',$themeinfo['type']);
    if(!empty($themeinfo['content'])){
        $View= new Think\View();
        $View->assign('data',$data);
        $data['content']=trim($View->fetch('',htmlspecialchars_decode($themeinfo['content'])));
    }else{$data['content']=$data['content'];}
    if(empty($data['title'])) $data['title']=$themeinfo['name'];
    if(empty($data['verify_code'])) $data['verify_code']='';
    foreach ($type_array as $v) {
		$result=send_method($v,$data);
	}
    if($result['status']==1){$msg='发送成功';}else{$msg='发送失败 错误:'.$result['msg'];}
    return $msg;
}
/**
   *发送站内信息
   */
function sendsitesms($to,$content='',$title='',$from='0',$type=1){
    $to=intval($to);
    if(empty($to) || empty($content))return false;
    $data['content']=$content;
    $data['title']=$title?$title:$content;
    $data['touid']=$to;
    $data['fromuid']=$from;
    $data['addtime']=NOW_TIME;
    $data['type']=$type;//1会员2店铺3供货商
    return M('Message')->add($data);
}
/**
  * 系统短信发送函数sendsms('13812345678','内容');
  * @param string $to    接收短信手机 多个用,分开
  * @param string $body    邮件内容
  * @param string $verify_code 验证码
  * @param array $param 附加参数
  * @return boolean 
  */
function sendsms($to,$body='',$verify_code='',$uid='',$param=''){
    if(empty($to) || empty($body))return false;
    $sendtype=C('SMS_SEND_TYPE');
    if(strpos($body,'【')===false){
        $body=$body.'【'.C('WEB_SITE_NAME').'】';
    }
    if($uid==''){
        if(is_numeric($to) && strlen($to) ==11)
            $uid = M('Member')->where('mobile='.$to)->getField('id');
    }
    if($sendtype==1){
        $result=$param['is_yingxiao']?dosendsmsyx($to,$body,$param):dosendsms($to,$body,$param);
        $result['is_send']=1;
    }else{
        $result['status']=0;$result['is_send']='0';
        $result['msg']='已经添加到短信列队!';
    }
    $data=array();
    $memberinfo=session('member_info');
    $admininfo=session('admin_info');
    $data['to']=$to;
    $data['content']=$body;
    $data['is_send']=$result['is_send'];
    $data['is_success']=$result['status'];
    $data['result']=$result['msg'];
    $data['send_type']=0;
    $data['uid']=isset($uid)?$uid:$memberinfo['id'];
    $data['adminid']=isset($admininfo['id'])?$admininfo['id']:0;
    $data['addtime']=$data['updatetime']=$data['sendtime']=NOW_TIME;
    if(!empty($verify_code)) $data['verify_code']=$verify_code;
    M('SmsLogs')->add($data);
    $back['status']=$result['status'];
    $back['msg']=$result['msg'];
    return $back;
}
/**
  * 执行发送短信
  * @param string $to 接收手机号
  * @param string $body 发送内容
  * @param array $param 附加参数
  */
function dosendsmsyx($to,$body='',$param=''){
    if(empty($to) || empty($body))return false;
    $sms =new \Common\Vendor\Sms('Hanchaosmsyx');
    $data=$param;
    $data['phone']=$to;
    $data['content']=$body;
    return $sms->send($data);
}
/**
  * 执行发送短信
  * @param string $to 接收手机号
  * @param string $body 发送内容
  * @param array $param 附加参数
  */
function dosendsms($to,$body='',$param=''){
    if(empty($to) || empty($body))return false;
    $sms =new \Common\Vendor\Sms;
    $data=$param;
    $data['phone']=$to;
    $data['content']=$body;
    return $sms->send($data);
}
/**
  * 系统邮件发送函数sendmail('xiaogg@sina.cn','xiaogg','标题','内容');
  * @param string $to    接收邮件者邮箱
  * @param string $name  接收邮件者名称
  * @param string $subject 邮件主题 
  * @param string $body    邮件内容
  * @param string $attachment 附件列表
  * @return boolean 
  */
function sendmail($to, $name='', $subject = '', $body = '', $attachment = null ,$verify_code='',$uid=''){
    $sendtype=C('SMS_SEND_TYPE');
    if($sendtype==1){
        $sendresult=dosendemail($to,$name,$subject, $body,$attachment);
        if($sendresult){
            $result=true;
            $data['is_send']='1';
            $data['is_success']='1';
            $data['result']='发送成功';
        }else{
            $result=$mail->ErrorInfo;
            $data['is_success']='0';
            $data['is_send']='1';
            $data['result']=$result;
        }
    }else{$data['is_success']='0';$data['result']='已添加到邮件列表';$data['is_send']='0';}
    $memberinfo=session('member_info');
    $admininfo=session('admin_info');
    $data['to']=$to;
    $data['from']=$name;
    $data['title']=$subject;
    $data['content']=$body;
    $data['send_type']=1;
    $data['uid']=isset($uid)?$uid:$memberinfo['id'];
    $data['adminid']=isset($admininfo['id'])?$admininfo['id']:0;
    $data['addtime']=$data['updatetime']=$data['sendtime']=NOW_TIME;
    if(!empty($verify_code)) $data['verify_code']=$verify_code;
    M('SmsLogs')->add($data);
    $back['status']=$data['is_success'];
    $back['msg']=$data['result'];
    return $back;
}
/**
  *执行发送邮件函数
  */
function dosendemail($to, $name='', $subject = '', $body = '', $attachment = null){
     $mail = new \Common\Vendor\PHPMailer\PHPMailer();
     $mail->CharSet = 'UTF-8';$mail->IsSMTP();// 设th定ink使用SMTP服oao务
     //$mail->SMTPDebug  = 0;// 关闭SMTP调试功能1 = errors and messages 2 = messages only 
     //$mail->SMTPSecure = 'ssl';// 使用安全协议
     $mail->SMTPAuth = true;                  // 启用 SMTP 验证功能     
     $mail->Host = C('EMAIL_SMTPHOST');  // SMTP 服务器
     $mail->Port = C('EMAIL_SMTPPORT');  // SMTP服务器的端口号
     $mail->Username = C('EMAIL_SMTPNAME');  // SMTP服务器用户名
     $mail->Password = C('EMAIL_SMTPPASSWORD');  // SMTP服务器密码
     $mail->SetFrom(C('EMAIL_FAJIAN'), C('WEB_SITE_TITLE'));
     $mail->AddReplyTo(C('EMAIL_FAJIAN'), C('WEB_SITE_TITLE'));
     $mail->Subject = $subject;
     $mail->MsgHTML($body);
     $mail->AddAddress($to, $name);
     if(is_array($attachment)){foreach ($attachment as $file){is_file($file) && $mail->AddAttachment($file);}}// 添加附件
     return $mail->Send();
}
//发送微信消息
function sendwxmsg($id,$content,$type='text',$utype='uid',$data=''){
    $wxtype=C('WX_TYPE');
    if($wxtype!=4)return false;
    if(is_numeric($id) && strlen($id) ==11)$id = M('Member')->where('mobile='.$id)->getField('id');
    if($utype=='uid'){
        $uid=$id;
        $map['id']=$id;
        $map['status']='1';
        $openid=M('Member')->where($map)->cache(true)->getField('wxid');
    }elseif($utype=='openid'){
        $openid=$id;if($openid)$uid=idtoname($id,'Member','id','wxid');
    }
    if(empty($openid)) return false;
    $result = array('errcode'=>1);
    $weixin = new \Common\Vendor\WeixinChat;
    if($data['theme_remark'] || ($data['theme_id'] && $data['theme_data'])){
        $contents=array();
        if($data['theme_data']){
            foreach($data['theme_data'] as $k =>$v){
                $contents[$k]=array('value'=>(str_exists($v,'$')?$data[substr($v,1)]:$v),'color'=>'#173177');
            }
        }else{
            $contents = $content;
        }
        $url=$data['url']?$data['url']:geturl('Home/Index/index','',true,true);
        $template_id = $data['theme_id']?$data['theme_id']:$data['theme_remark'];
        $result=$weixin->sendTplMsg($contents,$url,$openid,$template_id);
    }    
    if($result['errcode']!=0)$result=$weixin->sendMsg($content, $openid, $type);
    $memberinfo=session('member_info');
    $admininfo=session('admin_info');
    $data=array();
    $data['openid']=$openid;
    $data['content']=$content;
    $data['type']=$type;
    $data['uid']=isset($uid)?$uid:$memberinfo['id'];
    $data['adminid']=isset($admininfo['id'])?$admininfo['id']:0;
    $data['addtime']=$data['updatetime']=$data['sendtime']=NOW_TIME;
    if(!empty($verify_code)) $data['verify_code']=$verify_code;  
    $data['is_send']=1;
    $data['is_success']=$result['errcode']==0?1:0;
    $data['result']=$result['errmsg'];
    M('WxMsg')->add($data);
    $back['status']=$data['is_success'];
    $back['msg']=$data['result'];
    return $back;
}
/**
 * 获取推送的id列表
 * @param $type 类型0系统消息1线上订单 2货流通知 3第三方订单通知 4被扫到账通知 
 * @param $shopid 仅检索相应shopid
 * @param $setid 对应推送设置id 1app 2pad 0分组返回全部
 */
function getpushids($type=0,$shopid='',$setid=0){
    $field=array('is_message','is_online','is_cargo','is_threeorder','is_pay','is_call','is_face');$search_field=$field[$type];
    if(empty($search_field))return false;
    $map=array();
    $map['status']=1;
    if(!empty($shopid))$map['shop_id']=$shopid;
    if(!empty($setid))$map['push_setid']=$setid;
    $map[$search_field]=1;
    $res= M('PushDevice')->where($map)->field('push_setid,push_id')->select();
    if(empty($res))return false;$ids=array();
    if(empty($setid)){
        foreach($res as $v){$ids[$v['push_setid']][]=$v['push_id'];}
    }else{
        foreach($res as $v){$ids[]=$v['push_id'];}        
    }return $ids;
}
/**
 * 极光推送
 * @param $receive,$content,$m_type,$m_txt,$m_time
 * @param http://docs.jpush.io/server/rest_api_v3_push/ 相关文档参考
 * @param $id  会员id  默认为管理员类
 * @param $content  推送内容
 * @param $type='member'  向普通会员推送 $type='all'  向全体广播
 * @param $channel 渠道
 * @param $param  额外参数
 */
function pushSend($id,$content,$type='',$channel='',$param=array()){
    $admininfo=session('admin_info');
    $memberinfo=session('member_info');
    if($type=='all'){$receive = 'all';}else{
        if(!is_array($id))$id=explode(',',$id);
        $id=array_unique($id);
        $receive['registration_id'] = $id;
    }
    $config=$channel?array('app_id'=>$channel):array();
    $push=new \Common\Vendor\Push('Jpush',$config);
    $result=$push->push($receive,$content,$param);
    //存取操作日志
    if(in_array($type,array('member','app'))){
        $data['uid'] = $memberinfo['id'];
    }elseif($type=='all'){
        $data['allid'] = 1;
    }     
     if(is_numeric($type)){//重新发送
        $data['updatetime']=NOW_TIME;
        $data['is_success']=$result['status']==1?1:0;
        $data['result']=$result['info'];
        $data['errmsg'] = $id;
        $data['adminid']=isset($admininfo['id'])?$admininfo['id']:0;
        M('PushLog')->where('id='.$type)->save($data);
        return $result;
    }
    $data['title']=str_cut($content,20);
    $data['content']=$content;
    $data['addtime']=$data['updatetime']=NOW_TIME;
    $data['is_success']=$result['status']==1?1:0;
    $data['result']=$result['info'];
    $data['errmsg'] = $id;
    $data['adminid']=isset($admininfo['id'])?$admininfo['id']:0;
    M('PushLog')->add($data);
    return $result;
}
/**
 * 极光推送
 * @param $order_id 订单id
 */
function PushReadSend($order_id=0){
    if(empty($order_id))return false;
    $model = M('OrderInfo');
    $map = array();
    $map['id'] = $order_id;
    $map['status'] = 3; 
    $map['pay_status'] = 3;
    $order_info = $model->where($map)->field(true)->find();
    $order_count= $model->where($map)->count();
    if($order_info&&$order_info['sa_id']){
        $content = '';
        if($order_info['pay_code']){
            $payname = idtoname($order_info['pay_code'],'Payment','name','code',false);
            $content = $payname.'到账'.format_decimal($order_info['order_amount']).'元';
            $paramdata=array('type'=>4,'txt'=>$order_count);
            $ids=getpushids(4,$order_info['sa_id']);            
            if(!empty($ids[1]))$result = pushSend($ids[1],$content,'app',1,$paramdata);
            if(!empty($ids[2]))$result = pushSend($ids[2],$content,'app',2,$paramdata);            
        }
    }
    return true;
}
//下载快递文档
function down_file(){
    $express =new \Common\Vendor\Express;
    return $express->com_url();
}
//执行快递查询
function doexpress($order_sn,$code){
    if(empty($code))return false;
    $express =new \Common\Vendor\Express;
    $data['order_sn']=$order_sn;
    $data['code']=$code;
    return $express->process($data);
}
/**
  * 创建像这样的查询: "IN('a','b')";
  * @access   public
  * @param    mix      $item_list      列表数组或字符串
  * @param    string   $field_name     字段名称
  * @return   void
  */
function db_create_in($item_list, $field_name = ''){
    if (empty($item_list)){return $field_name . " IN ('') ";}
    else{
        if (!is_array($item_list)){$item_list = explode(',', $item_list);}
        $item_list = array_unique($item_list);
        $item_list_tmp = '';
        foreach ($item_list AS $item){
            if ($item !== ''){$item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";}
        }
        if (empty($item_list_tmp)){return $field_name . " IN ('') ";}
        else{return $field_name . ' IN (' . $item_list_tmp . ') ';}
    }
}
function strimages($val){//用于多图片上传 格式化
    if(empty($val))return false;
    $arr=strtoarray($val);
    $str='';
    foreach($arr as $key=> $v){
        $str.="<img src='".$v."' style='max-height:90px;max-width:90px;margin-right:3px' align='left' title='".$key."' alt='".$key."'>";
    }
    return $str;
}
//图片格式化成数组 用于多图片上传
function imgstoarray($str='',$other=''){
    $arr[]=array();
    if($str){$arr=strtoarray(',',$str);}
    if($other){$arr[]= $other;}
    return $newarr;
}
//压缩合并css文件
function min_css($urls,$base=''){
    if(empty($urls) && empty($base))return false;
    if(!empty($base) && !is_array($base))$base=explode('|',$base);
    if(!empty($base) && !empty($urls))$urls=array_merge($base,$urls); else{$urls=$urls?$urls:$base;}
    $urls=array_unique(array_filter($urls));
    $url = md5(implode(',',$urls));
    $urlpathbase=RUNTIME_PATH.'statics/';if(!is_dir($urlpathbase))mkdir($urlpathbase,0777);
    if(strlen(__ROOT__)>1)$urlpathbase=str_replace(__ROOT__,'',$urlpathbase);
    $url_path_back = $urlpathbase.$url.'.css';
    $write_file=ROOT_PATH.substr($url_path_back,1);
    if(!file_exists($write_file) || APP_DEBUG){
        $css_content = '';$tplconfigurl=ROOT_PATH.'/Application/'.get_module_name().'/View/'.get_default_theme().'/config.php';
        if(file_exists($tplconfigurl)){$tpl_config = require_once $tplconfigurl;}
        foreach($urls as $url){
            $url=strtr($url,array("__PUBLIC__"=>__ROOT__.'/Public',"THEME_PATH"=>THEME_PATH));
            if(str_exists($url,'./'))$url=format_url($url,5);
            $realfile=format_url($url,2);
            $cssbase= dirname($url).'/';
            $css_content .= str_replace("../",$cssbase."../",file_get_contents($realfile));
        }
        $css_content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css_content); 
        $css_content = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css_content);
        if(!empty($tpl_config['color']))$css_content =strtr($css_content,$tpl_config['color']);
        if(empty($css_content))$css_content='/**/';
        file_put_contents($write_file,$css_content);
    }
    return __ROOT__.substr($url_path_back,1);
}
//压缩合并js文件 如果key中包含min则进行压缩
function min_js($urls,$base=array()){
    if(empty($urls) && empty($base))return false;
    if(!empty($base) && !is_array($base))$base=explode('|',$base);
    if(!empty($base) && !empty($urls))$urls=array_merge($base,$urls);
    else{$urls=$urls?$urls:$base;}
    $urls=array_unique(array_filter($urls));    
    $url = md5(implode(',',$urls));
    $urlpathbase=RUNTIME_PATH.'statics/';if(!is_dir($urlpathbase))mkdir($urlpathbase,0777);
    $js_url = $urlpathbase.$url.'.js';
    $write_file=ROOT_PATH.substr($js_url,1);
    if(!file_exists($write_file)||APP_DEBUG){
        $packer = new \Common\Vendor\Jsmin;$js_content = '';
        foreach($urls as $key=> $url){
            if(str_exists($url,"__PUBLIC__"))$url=str_replace('__PUBLIC__',__ROOT__.'/Public',$url);
            if(str_exists($url,"THEME_PATH"))$url=str_replace('THEME_PATH',THEME_PATH,$url);
            if(str_exists($url,'./'))$url=format_url($url,5);$realfile=format_url($url,2);
            $append_content = oaofile($realfile)."\r\n";
            if(str_exists($key,'min'))$append_content=$packer->minify($append_content);
            $js_content .= $append_content;
        }
        if($js_content)oaofile($write_file,$js_content);
    }
    return __ROOT__.substr($js_url,1);
}
function getjumpurl($jumpUrl='',$extend=''){//获取成功和失败的跳转链接 自动判断是手机还是电脑
    if(!str_exists($jumpUrl,'JUMP_'))return false;
    $urlname=strtr($jumpUrl,array('JUMP_'=>''));
    if(str_exists($urlname,'&')){
       $urlarr=explode('&',$urlname);$extend=str_replace($urlarr[0].'&','',$urlname);$urlname=$urlarr[0];
    }
    $jumurl=ROOT_PATH.'/Application/Common/Data/Jumpdata.php';
    $urldata=require_once($jumurl);
    $type=is_mobile()?'mobile':'home';
    return geturl($urldata[$urlname][$type],$extend);
}
//验证码时间
function check_verify_code($to,$code,$type='0'){//0短信1邮件
    $map['to']=$to;
    $map['verify_code']=$code;
    $map['send_type']=$type;
    $check=M('SmsLogs')->where($map)->field('addtime,is_verify')->order('id desc')->find();
    if(empty($check))return false;
    $youxiaotime=C('MOBILE_TURE_TIME');//短信验证码有效时间
    if($check['is_verify'])return false;
    if($check['addtime']<(NOW_TIME-$youxiaotime))return false;
    $data['is_verify']=1;
    $data['updatetime']=NOW_TIME;
    M('SmsLogs')->where($map)->save($data);    
    return true;
}
//获取模板目录
function getmodtpl($type='show',$pathdir='Intro',$unset='',$module='Home'){
    if(empty($type))$type='show';
    $dir = new \Common\Vendor\Dir;
    $filelist=$dir->getList(APP_PATH.$module.'/View/'.get_default_theme($module).'/'.$pathdir.'/');
    if(empty($filelist))return false;
    $dirlist=array_slice($filelist,2);
	$files=array();
    $files[0]='默认模板';
    foreach($dirlist as $k => $v){
        if(str_exists($v,$type)){$files[$v]= $v;}
    }
    if($unset=='unset'){unset($files[0],$files[1]);}
    return $files;
}
/**
 * 调用广告
 * @param  $adid 广告位ID
 * @param  $catid 分类id
 * @param  $cacheHour 缓存小时数
 * @param  $isjs  是否是js调用
 * @param  $poster_num  广告数
 * @param  $type  分类类型
 * @return string
 */
function showads($adid,$catid='0',$cacheHour=12,$isjs='0',$poster_num='',$type=0){return ;}
/**
 * 获取url
 */
function geturl($name,$param='',$ext=true,$domain=false,$parammore=false,$page=false){
    if(empty($name))return false;
    if(str_exists($name,'http://') || str_exists($name,'https://'))return $name;
    if(!empty($param['URL_MODEL'])){
        $URL_MODEL=$param['URL_MODEL'];unset($param['URL_MODEL']);
    }else{$URL_MODEL='';}
    if(str_exists($name,'url:'))return rulestourl($name,$domain,$URL_MODEL);
    if(!is_array($param) && !empty($param))$param=strtoarray($param);
    if($parammore){
        $getdata=array_filter(I('param.'));
        if($getdata['id']=='index')unset($getdata['id']);
        if($param)$param=array_merge($getdata,$param);
        else $param=$getdata;
    }
    if(!$page && isset($param['p']))unset($param['p']);
    $url=U($name,$param,$ext,$domain,$URL_MODEL);
    return $url;
}
//生成链接
function rulestourl($str,$is_domain=true,$URL_MODEL='',$pram=array()){
    if(str_exists($str,'http://'))return $str;
    if(!str_exists($str,'url:'))return U($str,'',true,$is_domain,$URL_MODEL);
    $arr=explode(':',$str);
    $urlrules=M("UrlRules")->where('id='.$arr[1])->field(true)->find();
    if(empty($urlrules))return false;
    $is_url=array();
    if($urlrules['is_module'] == 1 && !empty($arr[2])){
        $is_url[]=$urlrules['urlparam'].'='.$arr[2];
    }
    if($urlrules['is_param'] == 1 && !empty($arr[3])){
        $is_url[]=$arr[3];
    }
    $isurl=implode('&',$is_url);//将数组拼接成字符串	
	if($pram){
		$pram_str=http_build_query($pram);
		$isurl=$isurl?$isurl.'&'.$pram_str:$pram_str;
	}
    return U($urlrules['theurl'],$isurl,true,$is_domain,$URL_MODEL);
}
//返回链接URL
function return_urlrules($value){
    //Navmodel层要掉用这个函数
    $urlarr[0]=I("url_navtype");
    $urlarr[1]=I("url_modulename");
    $urlarr[2]=I("url_param");
    if(empty($urlarr[0]))return $value;
    return 'url:'.implode(':',$urlarr);
}
/**
  * app分享链接调起app
  * @param  $param 参数 act=goods&id=1
  * @param  $urlscheme 应用标识 <preference name="urlScheme" value="hcshop" />
  * @example <iframe src="hcshop://?act=goods&id=123"></iframe>
  * @author xiaogg <xiaogg@sina.cn>
  */
function appurl($param=array(),$urlscheme=''){
    if(empty($urlscheme))$urlscheme=C('URL_SCHEME','hcshop');
    $urlparam='';
    $getdata=$param?$param:I('get.');
    if($getdata)$urlparam.='?'. http_build_query($getdata);        
    return $urlscheme."://".$urlparam;
}
/**
  *  获得文章列表
  *  @param integer $catid  文章分类ID
  *  @param integer $limit  数量
  *  @param string $order  排序
  *  @param string $sql 扩展sql
  *  @param string $field 要获取的字段
  *  @param Boolean $cache 缓存
  *  @return  array
  */
function article_list($catid,$limit=20,$order='',$sql='',$field='true',$cache=true,$param){
    $map=array();
    $map['status']=1;
//xyy 119
    if(!empty($param['is_tuijian']))
        $map['is_tuijian'] = $param['is_tuijian'];
    if(empty($param['page']))$p = 1;
    else $p = $param['page'];
    $pagesize = $limit;
//xyy 119
    if($catid){
        $sons=idtoname($catid,'ArticleCat','allson');
        $map['catid']=implode('',$sons)==$catid || !$sons?$catid:array('in',$sons);
    }
    if(empty($order))$order='sort desc,id desc';
    if(!empty($sql))$map['_string']=$sql;
    if($field=='true'){
        // $list=M('Article')->where($map)->order($order)->limit($limit)->cache($cache)->field('content',true)->select();
        $list=page_list('Article', $map, $order, true, $pagesize, $join, $p);
    }else{
        if($field=='*')$field=true;
        // $list=M('Article')->where($map)->order($order)->limit($limit)->cache($cache)->field($field)->select();
        $list=page_list('Article', $map, $order, $field, $pagesize, $join, $p);
    }
    return $list;
}
/**
  * 获得指定分类下的品牌
  * @param   int     $cat_id     分类的ID
  * @param   int     $brand_cid  品牌分类的ID
  * @param   boolean     $cache  缓存
  * @return  array
  */
function brand_list($cat_id=0,$brand_cid=0,$cache=true){
    if($cache){$cachename='brand_list'.$cat_id.$brand_cid;$cachecontent=S($cachename);if(!empty($cachecontent))return $cachecontent;}
    $map=$gmap=array();$map['status']=1;
    if(!empty($cat_id)){
        $allson=idtoname($cat_id,'PurchaseCategory','allson');
        $gmap['catid']=str_exists($allson,',')?array('in',$allson):$allson;
        $gmap['status']=1;
        $brandids=M("Goods")->where($gmap)->getField('brand_id',true);
        if(empty($brandids))$brandids=array(0);
        $map['id']=array('in',$brandids);
    }
    if($brand_cid>0)$map['brand_cat_id']=$brand_cid;    
    $list=M("Brand")->where($map)->field(true)->order('sort desc,id desc')->select();
    // if(empty($cat_id))$list = '';
    if($cache){S($cachename,$list);}
    return $list;
}
/**
  * 获取支付方式列表
  * @param string $is_online 	是否在线支付
  * @param string $is_wap	 	是否手机调用
  * @param int $type 0 会员1店铺
  */
function getpayment($is_online=1,$is_wap=0,$notin='',$in='',$type=0){
    $map=array();
    $map['status']=1;
    if($is_online)$map['is_online']=1;
    if($is_wap)$map['is_wap']=1;
    if($notin)$map['code']=array('not in',$notin);
    if($in)$map['code']=array('in',$in);
    $payment=M('Payment')->where($map)->field(true)->cache(true)->order('id desc')->select();
    if($payment){
        foreach($payment as $k=>$v){
        $paylogo=paylogo($v['code']);
        if($paylogo)$payment[$k]['logo']=$paylogo;
        $pay = new \Common\Vendor\Pay($v['code'],$payment[$k]);
        if($type==1 && strtolower($v['code'])=='hanchao'){
          $v['is_shop']=1;
          $payment[$k]['pay_code']=$pay->get_pay_code($v);  
        }else{
          $payment[$k]['pay_code']=$pay->get_pay_code();
        }
        }
    }
    return $payment;
}
/**
  * 获取支付方式的logo
  * @param string $code 支付方式标识
  * @return return string logo url或false
  */
function paylogo($code){
    if(empty($code))return false;
    $logo=COMMON_PATH."Vendor/Pay/Logo/".strtolower($code).".gif";    
    $backlogo=__ROOT__."/Application/Common/Vendor/Pay/Logo/".strtolower($code).".gif";
    if(file_exists($logo))return $backlogo;
    else return false;
}
//获取配送方式列表
function getsendment($where=""){
    $basewhere="status=1";
    if($where)$basewhere.=" and ".$where;
    $payment=M('Shipping')->where($basewhere)->field(true)->cache(true)->order('sort,id desc')->select();
    return $payment;
}
//生成订单号
function createOrderNo($type='1') {
    $conf_code=strtoarray(C('PAY_LOGTYPE'));
    $code=substr($conf_code[$type],0,1);
    return $code.base_order();
}
//生成基础订单号
function base_order(){
    return date('Ymdhis').rand(100,999);
}
/**
  * 当前路径
  * 返回指定栏目路径层级
  * @param $catid 栏目id
  * @param $symbol 栏目间隔符
  */
function catpos($catid,$endwidthbol='1',$modname='GoodsCategory',$urlname="Cate", $symbol=' &gt; '){
    if(empty($catid)){return '';}
    $category = getcache($modname);
    $cateinfo = $category[$catid];
    if(!isset($cateinfo)) return '';
    $pos = '';
    $pos .= '<em>'.$symbol.'</em>';
    $arrparentid = array_unique(array_filter(explode(',', $catid.','.$cateinfo['allparent'])));
    krsort ($arrparentid);$i=1;
    foreach($arrparentid as $v) {
        $url = $category[$v]['url']?$category[$v]['url']:geturl($urlname."/index",array('cat_id'=>$v));
        $pos .= '<a href="'.$url.'" title="'.$category[$v]['name'].'">'.$category[$v]['name'].'</a>';
        if((empty($endwidthbol) && $i<count($arrparentid)) || !empty($endwidthbol))$pos .=$symbol;
        ++$i;
    }
    echo $pos;
}
function clearhomehtml($id=''){
    if(empty($id))return false;
    $config=require('Application/Home/Conf/config.php');
    if(empty($config['HTML_CACHE_ON']))return false;
    $rule=$config['HTML_CACHE_RULES']['Goods:index'][0];
    $file='Application/Html/'.str_replace('{id}',$id,$rule).$config['URL_HTML_SUFFIX'];
    if(file_exists($file)){unlink($file);}
}
/**
  * 获得指定分类下所有底层分类的ID
  * @access  public
  * @param   integer     $cat        指定的分类ID
  * @param   integer     $goods_type        普通商品 5订货商品
  * @return  string
  */
function get_children($cat = 0,$type=0,$goods_type=1){
    if($goods_type==5){
        $catarr=pcat_list($cat,1);
    }else{
        $catarr=cat_list($cat,1);
    }
    if($type)return $catarr;
    return ' g.catid ' . db_create_in($catarr);
}
/**
  * 获得指定分类下的子分类的数组
  * @param   int     $cat_id     分类的ID
  * @param   boolean $re_type    返回的类型: 值为真时返回全部子集,否则返回子级数组id name
  * @return  array
  */
function cat_list($cat_id = 0,$type=0){
   GLOBAL $GoodsCategory;
   if(empty($GoodsCategory))$GoodsCategory=getcache('GoodsCategory');
   if($cat_id){
        $son =  $GoodsCategory[$cat_id]['allson'];
        if(!is_array($son))$son=explode(',',$son);
        if($type)return $son;
        foreach($son as $value){
            $sson = $GoodsCategory[$value];
            $arr['id'] = $sson['id'];
            $arr['name'] = $sson['name'];
            $array[$sson['id']] = $arr;
        }
        return $array;
    }else{return $GoodsCategory;}
}
/**
 * 获得指定订货商品分类下的子分类的数组
 * @param   int     $cat_id     分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回全部子集,否则返回子级数组id name
 * @return  array
 */
function pcat_list($cat_id = 0,$type=0){
    GLOBAL $PurchaseCategory;
    if(empty($PurchaseCategory))$PurchaseCategory=getcache('PurchaseCategory');
    if($cat_id){
        $son =  $PurchaseCategory[$cat_id]['allson'];
        if(!is_array($son))$son=explode(',',$son);
        if($type)return $son;
        foreach($son as $value){
            $sson = $PurchaseCategory[$value];
            $arr['id'] = $sson['id'];
            $arr['name'] = $sson['name'];
            $array[$sson['id']] = $arr;
        }
        return $array;
    }else{return $PurchaseCategory;}
}
/**
  * 获得所有扩展分类属于指定分类的所有商品ID
  * @access  public
  * @param   string $cat_id     分类查询字符串
  * @return  string
  */
function get_extension_goods($cats,$type=0){
    $cats=(!empty($cats))?array('catid'=>array('in',$cats)):$cats;
    $extension_goods_array = M('GoodsCat')->cache(true)->where($cats)->getField('goods_id',true);
    if($type)return $extension_goods_array;
    return db_create_in($extension_goods_array, 'g.id');
}
/**
  *  获得产品列表
  *  @param integer $catid 分类ID
  *  @param string $type 类型 hot new promat 
  *  @param integer $limit 数量
  *  @param string $order 排序
  *  @param string $sql 扩展sql
  *  @param string $field 要获取的字段
  *  @param Boolean $cache 缓存
  *  @return array
  */
function goods_list($catid=0,$type='',$limit='10',$order='',$sql='',$field='true',$cache=true){
    $map['status']=1;
    $map['shop_id']=0;
    if($catid){
        GLOBAL $GoodsCategory;
        $catinfo=$GoodsCategory[$catid];
        $extension_goods_id=get_extension_goods($catid,1);
        if(!empty($catinfo['allson']))$where['cat_id']= array('in',$catinfo['allson']);
        if(!empty($extension_goods_id))$where['id']  = array('in',$extension_goods_id);
        if(!empty($where)){$where['_logic'] = 'or';$map['_complex'] = $where;}
    }
    switch($type){
        case 'hot':$map['is_hot']=1;break;
        case 'best':$map['is_best']=1;break;
        case 'new':$map['is_new']=1;break;
        case 'promote':$map['is_promote']=1;$map['promote_end_date']=array('gt',time());break;        
    }
    if(empty($order))$order='sort desc,id desc';
    if(!empty($sql))$map['_string']=$sql;
    if($field=='true'){
        $list=M('Goods')->where($map)->order($order)->limit($limit)->cache($cache)->field('content',true)->select();
    }else{
        if($field=='*')$field=true;
        $list=M('Goods')->where($map)->order($order)->limit($limit)->cache($cache)->field($field)->select();
    }
    return $list;
}
/**
  * 帮助信息
  * @param   int     $pid     父级分类的ID
  * @return  array
  */
function get_shop_help($pid=4){
    $res = M('Article')->alias('a')->field('c.id,c.name,c.sort,a.id AS article_id,a.title')->JOIN('LEFT JOIN  __ARTICLE_CAT__ c ON a.catid = c.id ')->where('c.pid = '.$pid)->order('c.sort ASC, a.id')->cache(true)->select();
    $arr = array();
    foreach ($res AS $key => $row){
        $arr[$row['id']]['id']= $arr[$row['id']]['cid'] = $row['id'];
        $arr[$row['id']]['cat_name'] = $row['name'];
        $arr[$row['id']]['article'][$key]['article_id'] = $row['article_id'];
        $arr[$row['id']]['article'][$key]['title'] = $row['title'];
        $arr[$row['id']]['article'][$key]['url'] = geturl('Home/Article/show',array('id'=>$row['article_id']));
    }
    return $arr;
}
/**
  * 头部购物车数量
  * @param int $regis 是否允许未登录购买，0不允许未登录购买，1允许未登录购买
  * @return int
  */
function cart_show(){   
    $regis=C('NOT_ADD_CART');
    $sess = session('member_info');
    $cookie_id=cookie('u_cookieid');
    $map=array();
    $map['is_valid']=1;
    if(empty($regis)){
        if($sess['id']){
            $map['user_id']=$sess['id'];
            $cart_count = M('Cart')->where($map)->sum('goods_num');
        }else{
            $cart_count = 0;
        }
    }else{
        if($sess['id']){
            $map['user_id']=$sess['id'];
            $cart_count = M('Cart')->where($map)->sum('goods_num');
        }else{
            if($cookie_id){
                $map['user_id']=0;
                $map['cookie_id']=$cookie_id;
                $cart_count = M('Cart')->where($map)->sum('goods_num');
            }else{
                $cart_count = 0;
            }
        }
    }
    return intval($cart_count);
}
/**
 * 订货头部购物车数量
 * @return int
 */
function pcart_show(){
    $sess = session('shops_info');
    $cookie_id=cookie('u_cookieid');
    if($sess['id']){
        $map['user_id']=$sess['shop_id'];
        $map['is_addcart']=0;
        $map['cart_type'] = 2;
        $cart_count = M('Cart')->where($map)->sum('goods_num');
    }else{
        if($cookie_id){
            $map['user_id']=0;
            $map['cookie_id']=$cookie_id;
            $map['is_addcart']=0;
            $map['cart_type'] = 2;
            $cart_count = M('Cart')->where($map)->sum('goods_num');
        }else{
            $cart_count = 0;
        }
    }
    return intval($cart_count);
}
/**
   * 获得属性的详情
   * @param   integer     $type_id     商品ID
   * @param   integer     $is_search   搜索属性 all为调用全部 0非搜索 1搜索
   * @return  array
   */
function get_type_attr($type_id=array(),$catid=0,$is_search='1',$return=1){
    if(empty($type_id)) return false;
    $cachename="get_type_attr".$catid;
    $cachecontent=S($cachename);
    if($cachecontent)return $cachecontent[$return];
    if($catid){
        GLOBAL $GoodsCategory;
        $catinfo=$GoodsCategory[$catid]; 
        $extension_goods_id=get_extension_goods($catinfo['allson'],1);
        if(!empty($catinfo['allson']))$where['g.cat_id']  = array('in',$catinfo['allson']);
        if(!empty($extension_goods_id))$where['g.id']  = array('in',$extension_goods_id);
        if(!empty($where)){$where['_logic'] = 'or';$map['_complex'] = $where;}else{$map['g.cat_id']=$catid;}
    }
    if($is_search!='all')$map['a.is_search']=$is_search;
    $map['a.type_id']=array('in',$type_id);
    $map['a.status']=1;
    $map['g.status']=1;
    $allattr=M('GoodsAttr')->alias('ga')->JOIN('LEFT JOIN __GOODS__ as g on g.id=ga.goods_id')->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ as a on a.id=ga.attr_id')->where($map)->field('ga.*,a.name,a.options,a.type')->select();
    $attribute=array();
    $goodsattr=array();
    foreach($allattr as $k=>$v){
        if($v['type']=='checkbox'){
            $attribute[]='p'.$v['attr_id'];
            $goodsattr[$v['attr_id']]['id']=$v['attr_id'];
            $goodsattr[$v['attr_id']]['type_id']=$type_id;
            $goodsattr[$v['attr_id']]['name']=$v['name'];
            $v_o=strtoarray($v['options']);
            if($v_o[$v['attr_value']]){
                $goodsattr[$v['attr_id']]['options'][$v['attr_value']]=$v_o[$v['attr_value']];
            }
        }
    }
    $content[0]=$attribute;
    $content[1]=$goodsattr;
    S($cachename,$content);
    return $content[$return];
}
/**
  *获取catid上下级所有分类
  */
function get_cate_type($catid,$googs_type=1){
    if(empty($catid)) return false;
    if($goods_type == 5){
      GLOBAL $PurchaseCategory;
      $catinfo=$PurchaseCategory[$catid]; 
    }else{
      GLOBAL $GoodsCategory;
      $catinfo=$GoodsCategory[$catid]; 
    }
    if($catinfo['type_id']){
        return $catinfo['type_id'];
    }else{
        $all=$catinfo['allparent'].','.$catinfo['allson'];
        $parent=array_filter(array_unique(explode(',',$all)));
        $catinfo['types']='';
        foreach($parent as $v){
            if($PurchaseCategory[$v]['type_id'] && $googs_type==5){
              $catinfo['types'][]=$PurchaseCategory[$v]['type_id'];
            }elseif($GoodsCategory[$v]['type_id'] && $googs_type!=5){
              $catinfo['types'][]=$GoodsCategory[$v]['type_id'];
            }
        }
        return $catinfo['types'];
    }
}
/**
  *获取关联属性
  */
function get_extension_attr($id,$value){
    if(empty($id) || empty($value)) return false;
    $where['attr_id']=$id;
    $where['_string']="FIND_IN_SET('".$value."',attr_value)";
    $ids=M('GoodsAttr')->where($where)->field('goods_id')->cache(true)->select();
    $idsarr=array();
    foreach($ids as $val){
        $idsarr[]= $val['goods_id'];
    }
    return db_create_in($idsarr, 'a.id');
}
/**
  *获取订单的结算价
  * 商品原价提点：（商品原价-商品原价*积分支付的/总商品原价）*佣金比
  */
function get_balance_price($order_id){
    $root=array();
    if(empty($order_id)){return false;}
    $price=0;
    $map['id']=$order_id;
    $order_info=M("OrderInfo")->where($map)->field('shop_id,order_amount,goods_amount,goods_allmoney,discount')->find();
    $o_where['order_id'] = array("like", "%," . $order_id . ",%");
    $pay_info = M("PayLog")->where($o_where)->field(true)->find();
    $og_map['order_id']=$order_id;
    $og_map['status']=array("elt",2);
    $orgoods=M('OrderGoods')->where($og_map)->field('shop_id,goods_id,goods_price,goods_number')->select();
    $save_price=0;
    $goods_rate=0;//商品原价提点
    $real_rate=0;//返佣原价提点
    if($orgoods) {
        foreach ($orgoods as $val) {
            $goods_price = $val['goods_price'] * $val['goods_number'];
            $g_map['is_referral']=1;
            $g_map['id']=$val['goods_id'];
            $save_id=M("Goods")->where($g_map)->count();
            //$is_affiliate=idtoname($val['goods_id'],"Goods",'is_referral,id');
            if (!empty($val['shop_id'])) {
                //1.找出每个商品一级分类的佣金比
                $map['shop_id'] = $val['shop_id'];
                $map['id'] = $val['goods_id'];
                $goods_cate = M("Goods")->where($map)->getField('cat_id');
                if ($goods_cate > 0) {
                    $balance_rate = D("Common/GoodsCategory")->get_parent_pid($goods_cate);
                }
                //2.商品原价提点
                $goods_rate+=($goods_price - $goods_price * $pay_info['use_score_money'] / $order_info['goods_allmoney']) * $balance_rate/100;
                if($save_id>0){//参与返佣
                    $real_rate+=($goods_price - $goods_price * $pay_info['use_score_money'] / $order_info['goods_allmoney']) * $balance_rate/100;
                }
            } else {
                if (!empty($val['goods_attr'])) {
                    $goods_attr_data = unserialize($val['goods_attr']);
                    $where['id'] = array('in', explode('_', $goods_attr_data['key']));
                    $add_shop_balance = M('GoodsAttr')->where($where)->getField('sum(supplier_price)');//属性递加结算价
                }
                $supply_price = idtoname($val['goods_id'], 'Goods', 'supply_price', 'id', false);
                $price += ($add_shop_balance + $supply_price) * $val['goods_number'];
            }
        }
        if($order_info['shop_id']>0){
            //总实际抽成
            $real_money=format_decimal($order_info['order_amount']*$goods_rate/$order_info['goods_allmoney']);
            //返佣抽成
            $root['real_money']=format_decimal($order_info['order_amount']*$real_rate/$order_info['goods_allmoney']);
            //商户结算
            $root['price']=format_decimal($order_info['order_amount']-$real_money);
        }else{
            $root['price']=$price;
            $root['real_money']=format_decimal($order_info['order_amount']-$price);
        }
    }else{
        return false;
    }
    return $root;
}
/**
  *获取订货订单的结算价
  */
function get_balance_suprice($order_id){
    $root=array();
    if(empty($order_id)){return false;}
    $price=0;
    $map['id']=$order_id;
    $order_info=M("OrderInfo")->where($map)->field('shop_id,order_amount,goods_amount,goods_allmoney,discount')->find();
    $o_where['order_id'] = array("like", "%," . $order_id . ",%");
    $og_map['order_id']=$order_id;
    $og_map['status']=array("elt",2);
    $orgoods=M('OrderGoods')->where($og_map)->field('shop_id,goods_id,goods_price,goods_number,supplier_price')->select();
    if($orgoods) {
        foreach ($orgoods as $val) {
            $price += $val['supplier_price'] * $val['goods_number'];
        }
        $root['price']=$price;
    }else{
        return false;
    }
    return $root;
}
/**
 *获取外卖订单的结算价
 *
 */
function get_balance_new_price($order_id){
    $root=array();
    if(empty($order_id)){return false;}
    $map['id']=$order_id;
    $order_info=M("OrderInfo")->where($map)->field(true)->find();
    //余额、网银和手续费
    $root['price']=$order_info['pay_amount']+$order_info['used_money'];
    return $root;
}
/**
  * 获取店铺资金变更对应数组
  * @param $key
  * @param $field
  */
function shop_balancetype($key='',$field=''){
    $array=array(
    1=>array('field'=>'total_revenues','name'=>'余额'),
    2=>array('field'=>'unbalance','name'=>'未结算金额'),
    3=>array('field'=>'onbalance','name'=>'待结算金额'),
    4=>array('field'=>'freeze_price','name'=>'冻结资金 '),
    5=>array('field'=>'deduct_price','name'=>'代扣服务费 '),
    6=>array('field'=>'sale_total_money','name'=>'销售总额 '),
    7=>array('field'=>'total_point','name'=>'积分'),
    );
    if(empty($key) && empty($field))return $array;
    if(!empty($key) && empty($field))return $array[$key]['name'];
    if(!empty($key) && !empty($field))return $array[$key][$field];
    return false;
}
/**
  * 店铺账户变动记录
  * @param int $shop_id 店铺id
  * @param int $change_money 变动金额
  * @param string $type 变动类型1:total_revenues余额2:unbalance未结算3:onbalance待结算,4:freeze_price冻结,5:deduct_price代扣服务费6:销售总额7：total_point积分
  * @param string $status 操作类型1:充值,2:提现,3:订单结算,4:系统结算,5店铺下单6给会员充值 10店铺订货
  * @param int $change_desc 变动描述
  * @param int $order_info 订单信息
  * @param int $adminid 操作管理员ID
  *@param boolean $do 是否网站执行 true 网站 false 日志
  */
function shop_balance_log($shop_id, $change_money=0, $type=0, $status=4, $change_desc='', $order_info='',$adminid=0,$do=TRUE){
    $allowfields=shop_balancetype();
    if(empty($allowfields) || !is_array($allowfields))return false;
	if(empty($shop_id) || empty($change_money) || floatval($change_money)==0 || empty($allowfields[$type]))return false;
	$field=$allowfields[$type]['field'];
	$Shop=M('Shops');$where=array();$where['id']=$shop_id;
    $shop_info=$Shop->where($where)->count();
	if (!$shop_info)return false;
	$change_money=format_decimal($change_money,2,2);
    if ($change_money>0) {
		if($do)$Shop->where($where)->setInc($field,$change_money);//如果$do为true就去改变shops表
		$log_data['change_type']=0;
		$log_data['change_num']=$change_money;
    }else{
        if($do)$Shop->where($where)->setDec($field,-$change_money);//如果$do为true就去改变shops表
		$log_data['change_type']=1;
		$log_data['change_num']=-$change_money;
    }
    $log_data['shop_id']=$shop_id;
	$log_data['type']=$type;
    $log_data['end_num']=$Shop->where("`id`='".$shop_id."'")->getField($field);
	$log_data['status']=$status;
	$log_data['adminid']=$adminid;
    $log_data['order_id']=$order_info['id']?$order_info['id']:0;
    $log_data['change_time']=NOW_TIME;
    if($change_desc){
        $log_data['change_desc']=$do?$change_desc:'[日志]'.$change_desc;
    }else{
        if($change_money>0){
            if($order_info){
                $log_data['change_desc']='订单'.$order_info['order_sn'].'结算入账'.$change_money;
            }else{
                $log_data['change_desc']='入账'.$change_money;
            }
        }else{
            if($order_info){
                $log_data['change_desc']='订单'.$order_info['order_sn'].'支出'.-$change_money;
            }else{
                $log_data['change_desc']='支出'.-$change_money;
            }
        }
    }
    $log_data['sa_id']=$order_info['sa_id'];
    $result = M('ShopbalanceLog')->add($log_data);
    return $result;
}
/**
  *店铺结算
  */
function give_shop_balance($order_id){
    if(empty($order_id)){return false;}
    $order_info=idtoname($order_id,'OrderInfo','*');
    $price_info=get_balance_new_price($order_id);

    $o_type = idtoname($order_id,'OrderInfo','type','id',false);
    if(!$price_info)return false;
    if($order_info['shop_id']){
         $is_balance=idtoname('IS_BALANCE','Config','value','name',false);
        if($is_balance){//自动结算
            //shop_balance_log($order_info['shop_id'],$price_info['price'],6,3,'订单'.$order_info['order_sn'].'收货,店铺销售额增加', $order_info);
            shop_balance_log($order_info['shop_id'],$price_info['price'],1,3,'订单'.$order_info['order_sn'].'收货,店铺余额增加', $order_info);
            shop_balance_log($order_info['shop_id'],-$price_info['price'],2,3,'订单'.$order_info['order_sn'].'收货,未结算总额减少', $order_info);
            shop_balance_log($order_info['shop_id'],$order_info['used_score'],7,3,'订单'.$order_info['order_sn'].'收货,积分总额增加', $order_info);

        }else{
            shop_balance_log($order_info['shop_id'],$price_info['price'],1,3,'订单'.$order_info['order_sn'].'收货,店铺余额增加', $order_info);
            shop_balance_log($order_info['shop_id'],-$price_info['price'],2,3,'订单'.$order_info['order_sn'].'收货,未结算总额减少', $order_info);
            shop_balance_log($order_info['shop_id'],$order_info['used_score'],7,3,'订单'.$order_info['order_sn'].'收货,积分总额增加', $order_info);

        }
    }
    return true;
}
/**
 *获取店铺活动类标签保证金
 * @param $shop_id
 */
function deduct_money($shop_id){}
/**
  *供货商结算
  * @param $order_id
  */
function get_suppliers_balance($order_id){
    if(empty($order_id)){return false;}
    $order_info=idtoname($order_id,'OrderInfo','*');
    $price_info=get_balance_suprice($order_id);  
    if(!$price_info)return false;
    if($order_info['shop_id']){
        if(C('IS_BALANCE')){//自动结算
            supplier_balance_log($order_info['shop_id'],$price_info['price'],1,3,'订单'.$order_info['order_sn'].'收货,余额增加', $order_info);
            supplier_balance_log($order_info['shop_id'],-$price_info['price'],2,3,'订单'.$order_info['order_sn'].'收货,未结算总额减少', $order_info);
        }else{
            supplier_balance_log($order_info['shop_id'],$price_info['price'],3,3,'订单'.$order_info['order_sn'].'收货,待结算总额增加', $order_info);
            supplier_balance_log($order_info['shop_id'],-$price_info['price'],2,3,'订单'.$order_info['order_sn'].'收货,未结算总额减少', $order_info);
        }
    }
    return true;
}
//gyc 2019.1.22
function affiliate($order_id){
	$map = array();
	$map['id'] = $order_id;
	$order_info = M('OrderInfo')->where($map)->field('uid,lshop_id')->find();
	//1113
	$all_money=$all_profit=$all_commission=$fixed=0;//商品金额百分比//利润//固定金额百分比分佣//固定积分或金额时
	$goods_ids = unserialize(C('PRO_GOODS'));
	$g_ids = unserialize($goods_ids['temp']);
	$map = array();
	$map['order_id']=$order_id;
	$map['goods_id']=array('not in',$g_ids);
	$order_goods=M('OrderGoods')->alias('o')
		->where($map)
		->join('__GOODS__ as g on o.goods_id=g.id and g.is_referral>0')
		->field('sum(o.goods_price*o.goods_number) as all_money,sum((o.goods_price-o.supplier_price)*o.goods_number) as all_profit,sum(o.commission*o.goods_number) as all_commission,sum(o.goods_number) as fixed,o.is_referral')
		->group('o.is_referral')
		->select();
	$all_moneys = $all_profits = $fixeds = array();
	foreach ($order_goods as $k => $v) {
		if($v['is_referral'] == 0){//不分佣
			$return['status'] = 1;
			return $return;
		}elseif($v['is_referral'] == 1){//按系统设定
			$all_moneys[$k] = $v['all_money'];
			$all_profits[$k] = $v['all_profit'];
		}elseif($v['is_referral'] == 2){//按固定金额
			$all_moneys[$k] = $all_profits[$k] = $v['all_commission'];
		}
		$fixeds[$k] = $v['fixed']; //数量
	}
	$all_money = array_sum($all_moneys);
	$all_profit = array_sum($all_profits);
	$fixed = array_sum($fixeds);
	$affiliate = unserialize(C('AFFILIATE'));
	$aff_setting= unserialize(C('AFF_SETTING')); //jxr 2019.10.11 
	$pro_level = M('Config')->field('value')->where("name='AFFILIATE_THREE'")->find();
	$pro_level = unserialize($pro_level['value']);
	//判断分销内购
	if($affiliate['config']['is_ngfx']==1){
		$rank_info = ex_level($order_info['uid']);//内购三级
	}else $rank_info=ex_ranks($order_info['uid']);
	if(!empty($rank_info)){
		$pid = $rank_info[1]['id'];
		$ppid = $rank_info[2]['id'];
		$pppid = $rank_info[3]['id'];
	}
	foreach($pro_level['info'] as $k=>$value){
		if($pid && ($rank_info[1]['rank_id']==$value['zhi_level'] || $value['zhi_level']==0)){//一级
			if(($rank_info[2]['rank_id']==$value['jian_level'] || $value['jian_level']==0)){//二级判断
				if(($rank_info[3]['rank_id']==$value['t_level'] || $value['t_level']==0)){//三级判断
					//一级分的钱
					if($pid && ($rank_info[1]['rank_id'] >= $affiliate['config']['ex_level'])){
						if($affiliate['config']['fx_type']==1){//分现金
							if($aff_setting['config']['fx_money_type']==1){//订单金额
								$pid_money = format_decimal($all_money*$value['fen_money']/100);
							}else{//订单利润
								$pid_money = format_decimal($all_profit*$value['fen_money']/100);
							}
							if($pid_money>0){
								$log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠1级('.idtoname($pid,'Member','username;nickname').')推荐人'.' 余额：'.$pid_money;
							}
						}else{//分积分 
							if($aff_setting['config']['fx_money_type']==1){//订单金额
								$pid_point  = intval($all_money*$value['fen_money']/100);
							}else{//订单利润
								$pid_point  = intval($all_profit*$value['fen_money']/100);
							}
							if($pid_point>0){
								$log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠1级('.idtoname($pid,'Member','username;nickname').')推荐人'.' 积分：'.$pid_point;
							}
						}
						//有导购
						if($affiliate['config']['is_dg']==1){//开启导购分佣
							$dg_num = $affiliate['config']['dg_num'];//导购分佣占一级分佣百分比
							$dg_id =idtoname($order_info['lshop_id'],'LittleShop','uid');
							if($dg_id != $order_info['uid']){
								$dg_log='推荐('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠导购人('.idtoname($dg_id,'Member','username;nickname').')';
								if($pid_money>0){
									$dg_moeny =format_decimal($pid_money*$dg_num/100);
									$dg_log.=' 余额：'.$dg_moeny;
									$pid_money=format_decimal($pid_money-$dg_moeny);
									$log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠1级('.idtoname($pid,'Member','username;nickname').')推荐人'.' 余额：'.$pid_money;
								}
								if($pid_point>0){
									$dg_point = intval($pid_point*$dg_num/100);
									$dg_log.=' 积分：'.$dg_point;
									$pid_point=intval($pid_point-$dg_point);
									$log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠1级('.idtoname($pid,'Member','username;nickname').')推荐人'.' 积分：'.$pid_point;
								}
								if($dg_moeny>0 || $dg_point>0)affiliate_log($order_id,1,$dg_id,$dg_moeny,$dg_point,$dg_log);
							}
						}
						//一级分佣
						affiliate_log($order_id,1,$pid,$pid_money,$pid_point,$log);
					}
					
					if($aff_setting['config']['money_type']==1){//订单金额分佣
						if($affiliate['config']['fx_type']==1){//分现金
							if($aff_setting['config']['fx_money_type']==1){//订单金额
								if($ppid && ($rank_info[2]['rank_id'] >= $affiliate['config']['ex_level'])) $ppid_money = format_decimal($all_money*$value['sfen_money']/100);
								if($pppid && ($rank_info[3]['rank_id'] >= $affiliate['config']['ex_level'])) $pppid_money = format_decimal($all_money*$value['tfen_money']/100);
							}else{//订单利润
								if($ppid && ($rank_info[2]['rank_id'] >= $affiliate['config']['ex_level'])) $ppid_money = format_decimal($all_profit*$value['sfen_money']/100);
								if($pppid && ($rank_info[3]['rank_id'] >= $affiliate['config']['ex_level'])) $pppid_money = format_decimal($all_profit*$value['tfen_money']/100);
							}
						}else{//分积分 
							if($aff_setting['config']['fx_money_type']==1){//订单金额
								if($ppid && ($rank_info[2]['rank_id'] >= $affiliate['config']['ex_level'])) $ppid_point  = intval($all_money*$value['sfen_money']/100);
								if($pppid && ($rank_info[3]['rank_id'] >= $affiliate['config']['ex_level'])) $pppid_point  = intval($all_money*$value['tfen_money']/100);
							}else{//订单利润
								if($ppid && ($rank_info[2]['rank_id'] >= $affiliate['config']['ex_level'])) $ppid_point  = intval($all_profit*$value['sfen_money']/100);
								if($pppid && ($rank_info[3]['rank_id'] >= $affiliate['config']['ex_level'])) $pppid_point  = intval($all_profit*$value['tfen_money']/100);
							}
						}
					}else{//上级所获分佣*比例
						/* print_r(22); */
						if($affiliate['config']['fx_type']==1){//分现金
							if($ppid && ($rank_info[2]['rank_id'] >= $affiliate['config']['ex_level'])) $ppid_money = format_decimal($pid_money*$value['sfen_money']/100);
							if($pppid && ($rank_info[3]['rank_id'] >= $affiliate['config']['ex_level'])) $pppid_money = format_decimal($ppid_money*$value['tfen_money']/100);
						}else{
							if($ppid && ($rank_info[2]['rank_id'] >= $affiliate['config']['ex_level'])) $ppid_point  = intval($pid_point*$value['sfen_money']/100);
							if($pppid && ($rank_info[3]['rank_id'] >= $affiliate['config']['ex_level'])) $pppid_point  = intval($ppid_point*$value['tfen_money']/100);
						}
					}
					if($affiliate['config']['fx_type']==1){//分现金
						if($ppid_money>0){
							$ppid_log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠2级('.idtoname($ppid,'Member','username;nickname').')推荐人'.' 余额：'.$ppid_money;
							affiliate_log($order_id,1,$ppid,$ppid_money,0,$ppid_log);
						}
						if($pppid_money>0){
							$pppid_log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠3级('.idtoname($pppid,'Member','username;nickname').')推荐人'.' 余额：'.$pppid_money;
							affiliate_log($order_id,1,$pppid,$pppid_money,0,$pppid_log);
						}
					}else{//分积分
						if($ppid_point>0){
							$ppid_log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠2级('.idtoname($ppid,'Member','username;nickname').')推荐人'.' 积分：'.$ppid_point;
							affiliate_log($order_id,1,$ppid,0,$ppid_point,$ppid_log);  
						}
						if($pppid_point>0){
							$pppid_log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠3级('.idtoname($pppid,'Member','username;nickname').')推荐人'.' 积分：'.$pppid_point;
							affiliate_log($order_id,1,$pppid,0,$pppid_point,$pppid_log);  
						}
					}
					$return['status'] = 1;
					return $return;
				}
			}
		} 
	}
}
//gyc

//订单付款,分成日志
// function affiliate($order_id){
//     $map = array();
//     $map['id'] = $order_id;
//     $order_info = M('OrderInfo')->where($map)->field('uid')->find();
//      //1113
//     $all_money=$all_profit=$all_commission=$fixed=0;//商品金额百分比//利润//固定金额百分比分佣//固定积分或金额时
//     $order_goods=M('OrderGoods')->alias('o')
//         ->where('order_id='.$order_id)
//         ->join('__GOODS__ as g on o.goods_id=g.id and g.is_referral>0')
//         ->field('sum(o.goods_price*o.goods_number) as all_money,sum((o.goods_price-o.supplier_price)*o.goods_number) as all_profit,sum(o.commission*o.goods_number) as all_commission,sum(o.goods_number) as fixed,o.is_referral')
//         ->group('o.is_referral')
//         ->select();
//     $all_moneys = $all_profits = $fixeds = array();
//     foreach ($order_goods as $k => $v) {
//         if($v['is_referral'] == 0){//不分佣
//             $return['status'] = 1;
//             return $return;
//         }elseif($v['is_referral'] == 1){//按系统设定
//             $all_moneys[$k] = $v['all_money'];
//             $all_profits[$k] = $v['all_profit'];
//         }elseif($v['is_referral'] == 2){//按固定金额
//             $all_moneys[$k] = $all_profits[$k] = $v['all_commission'];
//         }
//         $fixeds[$k] = $v['fixed'];
//     }
//     $all_money = array_sum($all_moneys);
//     $all_profit = array_sum($all_profits);
//     $fixed = array_sum($fixeds);
//     $rank_info=ex_ranks($order_info['uid']);
//     $affiliate = unserialize(C('AFFILIATE'));
//     foreach($affiliate['item'] as $key=>$val){
//         $affiliate['item'][$key]['tui_id']=$rank_info[$key]['id'];
//         $affiliate['item'][$key]['points']=$rank_info[$key]['points'];//1113
//     }
//     $member_rank=idtoname($affiliate['config']['memberrank'],'MemberRank','*');//1113会员等级
//     $point =$money =0;
//     foreach($affiliate['item'] as $k=>$v){
//     if(empty($v['tui_id'])) continue;
//     if ($v['points'] < $member_rank['min_points']) continue;//1113会员等级
//         // 判断三级返利
//         if ($v['point'] > 0 && !empty($all_money)) {
//           switch ($v['point_status'])
//           {
//           case 1://point_status=1商品金额百分比赠送积分
//             $point = format_decimal($all_money*$v['point']/100,0);
//             break;  
//           case 2://point_status=2固定积分
//             $point = $fixed*$v['point'];
//             break;
//           case 3://point_status=3商品利润百分比赠送积分
//             $point = format_decimal($all_profit*$v['point']/100,0);
//             break;
//           }
//         }
//         if ($v['money'] > 0 && !empty($all_money)) {
//           switch ($v['money_status'])
//           {
//           case 1://money_status=1商品金额百分比赠送现金
//             $money = format_decimal($all_money*$v['money']/100);
//             break;  
//           case 2://money_status=2固定现金 money =0 
//             $money = $fixed*$v['money'];
//             break;
//           case 3://money_status=3商品利润百分比赠送现金 money=0 不返利
//             $money = format_decimal($all_profit*$v['money']/100);
//             break;
//           }
//         }
//         $log='被推荐人('.idtoname($order_info['uid'],'Member','username;nickname').')下单，将赠'.$k.'级('.idtoname($v['tui_id'],'Member','username;nickname').')推荐人';
//         if($money>0){
//           $log.=' 余额：'.$money;
//         }
//         if($point>0){
//           $log.=' 积分：'.$point;
//         }
//         if($money>0 || $point>0)affiliate_log($order_id,1,$v['tui_id'],$money,$point,$log);  
//         $return['status'] = 1;
//     }
//     return $return;
// }
//确认收货，处理分成
function affiliate_yes($order_id){
    $map['order_id']=$order_id;
    $map['status']=2;
    $num=M('OrderGoods')->where($map)->count();
    if($num > 0){
        $orderinfo=idtoname($order_id,'OrderInfo','order_sn,uid');
        $orderusername=idtoname($orderinfo['uid'],'Member','username');
        $maps['order_id']=$order_id;
        $maps['is_separate']=0;
        $aff_info=M('AffiliateLog')->field('id,uid,money,point')->where($maps)->select();
        $result=0;
        foreach($aff_info as $v){
            if($v['money'] > 0){
                account_change($v['uid'],$v['money'],8,15,'被推荐人'.$orderusername.'确认订单'.$orderinfo['order_sn'].'收货完毕，得到佣金分成');
            }
            if($v['point'] > 0){
                account_change($v['uid'],$v['point'],4,15,'被推荐人'.$orderusername.'确认订单'.$orderinfo['order_sn'].'收货完毕，得到积分分成');
            }
            //改变分成状态
            $map_st['id']=$v['id'];
            $data['is_separate']=1;
            $result += M('AffiliateLog')->where($map_st)->save($data);
        }
        return $result;
    }else{return false;}
}
//分成日志
function affiliate_log($order_id,$separate_type,$tui_uid='',$money='',$point='',$desc='',$is_separate=0){
    $ex_data['order_id']=$order_id;
    $ex_data['separate_type']=$separate_type;
    $ex_data['uid']=$tui_uid?$tui_uid:0;
    $ex_data['money']=$money>=0?$money:0;
    $ex_data['point']=$point>=0?$point:0;
    $ex_data['desc']=$desc;
    $ex_data['is_separate']=$is_separate;
    $ex_data['addtime']=time();
    $ex_data['time']=cookie('tui_time');
    $info=M('AffiliateLog')->add($ex_data);
    return $info;
}
//会员id，返回三级父集
function ex_ranks($id){
    $rank_p=array();
    $where3['id']=$id;
    $rank_p[1]=M('Member')->where($where3)->getField('parent_id');
    if(!empty($rank_p[1])){
        $where2['id']=$rank_p[1];
        $rank_p[2]=M('Member')->where($where2)->getField('parent_id');
    }
    if(!empty($rank_p[2])){
        $where1['id']=$rank_p[2];
        $rank_p[3]=M('Member')->where($where1)->getField('parent_id');
    }
    if(!empty($rank_p[3])){
        $where1['id']=$rank_p[3];
        $rank_p[4]=M('Member')->where($where1)->getField('parent_id');
    }
    // if(!empty($rank_p[4])){
    //     $where1['id']=$rank_p[4];
    //     $rank_p[5]=M('Member')->where($where1)->getField('parent_id');
    // }
    // if(!empty($rank_p[5])){
    //     $where1['id']=$rank_p[5];
    //     $rank_p[6]=M('Member')->where($where1)->getField('parent_id');
    // }
    $rank_p=array_filter($rank_p);
    if(empty($rank_p))return false;
    foreach($rank_p as $key=>$val){
        $rank_info[$key]=idtoname($val,'Member','*');
    }
    return $rank_info;	
}
//变更会员等级
function user_ranks($uid=0){
    if(empty($uid))return false;
	$map = array();
    $map['id']=$uid;
    $map['status']=1;
    $member_info=M('Member')->where($map)->field('rank_id,points,recharge_points')->find();
    if(!$member_info) return false;
	$sort = idtoname($member_info['rank_id'],'MemberRank','sort','id',false);
    $where['status']=1;
	$where['sort'] = array('gt',$sort);
	$where_or['min_points']=array('elt',$member_info['points']);
	$where_or['max_points']=array('elt',$member_info['recharge_points']);
	$where_or['_logic']='OR';
	$where['_complex'] = $where_or;
    $rank_id=M('MemberRank')->where($where)->order('sort desc')->limit(1)->getField('id');
    if($rank_id>0 && $rank_id!=$member_info['rank_id']){
		$rank_promotion=C("RANK_PROMOTION_INTEGRAL");//等级晋升赠送积分
        account_change($uid,$rank_promotion,4,5,"等级晋升赠送积分");	
        $data['rank_id']=$rank_id;
        M('Member')->where($map)->save($data);
        updatesession($uid);
    }
}
//推荐人个数
function count_tui($pid){
    $map['parent_id']=$pid;
    $result=M('Member')->where($map)->count();
    return $result;
}
//获取token
function get_token($token = NULL) {
    if (! empty ( $_REQUEST ['token'] )){
        $token=$_REQUEST ['token'];session('token',$token);
    }elseif(empty($token)){
        $token= session ('token');
    }elseif ($token !== NULL){
        session ( 'token', $token );
    }
    if(empty($token)){
        $admin_info=session('admin_info');
        $map['adminid']=$admin_info['id'];$map['status']=1;
        $token=M('MemberPublic')->where($map)->order('id desc')->getfield('token');session('token',$token);
    }		
    if (empty ( $token )) {return - 1;}	
    return $token;
}
/**
 * 加密openid
 */
function openid_encode($openid=''){
   if(empty($openid)){return false;}
   $key=file_get_contents(ROOT_PATH.'/hanchao_auth.key');
   $str=json_encode(array('time'=>NOW_TIME+60,'id'=>$openid));
   return base64_encode(authcode($str,'ENCODE',$key));
}
/**
 * 根据加密的opend解密出原openid
 */
function openid_decode($str=''){
    if(empty($str))return false;
    $key=file_get_contents(ROOT_PATH.'/hanchao_auth.key');
    $json= authcode(base64_decode($str),'DECODE',$key);$array=json_decode($json,1);
    if($array['time']>NOW_TIME && $array['id']){
        $openid=$array['id'];
        cookie('wxopenid',$openid);
        session('wxopenid',$openid);
        return $openid;
    }return false;
}
//获取当前用户的OpenId
function get_openid($openid = '') {
    if(empty($openid))$openid=I('request.openid');
    if($openid){
       $openid= openid_decode($openid);
    }
    if(empty($openid)){
       $openid= session('wxopenid');
       if(empty($openid))$openid=cookie('wxopenid');
    }
    //临时调试
    //if(empty($openid))$openid='FromUserName';
    $isWeixinBrowser = is_weixin();
    if (empty ($openid) && $isWeixinBrowser) {
        if(C('BOUND_STATUS') == 2){            
            $site_id=C('appid');//站点ID            
            $weixin_open = new \Common\Vendor\Weixinopen;
            $weixin_config=$weixin_open->wxconfig($site_id);
            if(empty($weixin_config))return ;
            redirect ( $url );
        }else{
            $callback = GetCurUrl ();
            OAuthWeixin ( $callback );
        }
    }
    if (empty ( $openid )) {return ;}
    return $openid;
}
//微信
function OAuthWeixin($callback) {
    if(C('WX_TYPE')!=4)return false;
    $isWeixinBrowser = is_weixin();
    $info['appid'] = C('WX_APPID');
    $info ['secret'] = C('WX_APPSECRET');
    if (! $isWeixinBrowser || empty ( $info ['appid'] )) {
        redirect ( $callback . '&openid=0' );
    }
    $param ['appid'] = $info ['appid'];
    if (! isset ( $_GET ['getOpenId'] )) {
        $param ['redirect_uri'] = $callback . '&getOpenId=1';
        $param ['response_type'] = 'code';
        $param ['scope'] = 'snsapi_base';//snsapi_userinfo
        $param ['state'] = 'hanchaowx';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect';
        redirect ( $url );
    } elseif ($_GET ['state']) {
        $param ['secret'] = $info ['secret'];
        $param ['code'] = I ( 'code' );
        $param ['grant_type'] = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query ( $param );
        $content = curlget ( $url );
        $content = json_decode ( $content, true );
        S('wx_'.$content ['openid'],$content);
        redirect ( $callback . '&openid=' . openid_encode($content ['openid']));
    }
}
// php获取当前访问的完整url地址
function GetCurUrl() {
    $url = 'http://';
    if (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] == 'on') {
        $url = 'https://';
    }
    if ($_SERVER ['SERVER_PORT'] != '80') {
        $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
    } else {
        $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
    }
    // 兼容后面的参数组装
    if (stripos ( $url, '?' ) === false) {
        $url .= '?t=' . time ();
    }
    return $url;
}
/**
  * 带分页多条数据获取
  * @param $module 模块名(表名)
  * @param $map 筛选条件
  * @param $order 排序
  * @param $field 字段
  * @param $pagesize 分页数
  * @param $join join方法
  * @param $REQUEST 分页page 所带参数允许自动义数组
  * @return array
  */
function page_list($module,$map=array(),$order='',$field=true,$pagesize=0,$join='',$REQUEST=1){
    if(empty($module))return false;if(empty($pagesize))$pagesize=C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
    if($REQUEST>=1)$REQUEST = (array)I('request.');
    if(!isset($REQUEST['p'])&&isset($REQUEST['page']))$REQUEST['p']=$REQUEST['page'];
    if(intval($REQUEST['p'])<=0)$REQUEST['p']=1;
    $group = '';
    if(isset($map['group'])&&!empty($map['group'])){$group = $map['group'];unset($map['group']);}
    $model = M($module);
    $preve = (intval($REQUEST['p'])-1)*$pagesize;
    $limit = "$preve,$pagesize";
    if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
        $order = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
    }
    $return = array();
    if($group){
      $distinct='distinct '.$group;
      $return['count'] = $model->alias('a')->where($map)->join($join)->count($distinct);
        if(is_array($return['count'])){
            $count_key=array_keys($return['count']);$return['count'] =$count_key[0];
        }
    }else{
      $return['count'] = $model->alias('a')->where($map)->join($join)->count();
    }
    $Page = new \Common\Vendor\Page($return['count'],$pagesize,$REQUEST);
    $return['page'] = $Page->show();
    $return['firstRow'] = $Page->firstRow;
    $return['listRows'] = $Page->listRows;
    $return['totalPages'] = $Page->totalPages;
    $return['nowPage']=$REQUEST['p']?$REQUEST['p']:$REQUEST['page'];//gyc 12.19
    $return['list'] = $model->alias('a')->where($map)->order('create_time')->join($join)->field($field)->group($group)->order($order)->limit($limit)->select();
    // $return['sql'] = $model->getLastSql();
    return $return;
}
/**
  * 生成缩略图函数
  * @param  $imgurl 图片路径
  * @param  $width  缩略图宽度
  * @param  $height 缩略图高度
  * @param  $domain 是否返回完整路径 默认否
  * @param  $water  是否添加水印 auto 参考后台设置 0 关闭 1|图片名 2|文字|字号|颜色|字体
  * @param  $autocut 是否自动裁剪 默认裁剪，当高度或宽度有一个数值为0是，自动关闭
  * @param  $smallpic 无图片是默认图片路径
  * @return return string 缩略图路径
  */
function thumb($imgurl, $width =300, $height =300, $smallpic = 'nopic.gif',$domain=true ,$water='auto',$autocut = 0) {
    $nopic=$domain?'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/'.'Public/images/'.$smallpic:'Public/images/'.$smallpic;
    if(empty($imgurl))return $nopic;
    if((str_exists($imgurl,'http://') || str_exists($imgurl,'https://'))&&str_exists($imgurl,'oss')&& !str_exists($imgurl,'x-oss-process=image/resize')){
        return $imgurl.'?x-oss-process=image/resize,,m_fill,h_'.$height.',w_'.$width;
    }
    if(str_exists($imgurl,'http://') || str_exists($imgurl,'https://')){return $imgurl;/*
        $imgurl_temp='uploads/thumb/'.md5($imgurl).'.'.fileext($imgurl);
        if(!file_exists(ROOT_PATH.'/'.$imgurl_temp)){oaofile($imgurl_temp,curlget($imgurl));}
        if(file_exists(ROOT_PATH.'/'.$imgurl_temp))$imgurl=$imgurl_temp;*/
    }
    if($width==0 && $height==0)return format_url($imgurl,$domain);
    $imgurl=format_url($imgurl,2);
    if(!file_exists($imgurl)) return $nopic;
    $newimgurl = 'uploads/thumb/thumb_'.$width.'_'.$height.'_'.basename($imgurl);
    if(file_exists($newimgurl))return format_url($newimgurl,$domain);//如果已经存在则直接返回
    $image = new \Common\Vendor\Image(); 
    $image->open($imgurl);
    $base_width = $image->width(); // 返回图片的宽度
    $base_height = $image->height(); // 返回图片的高度
    if($width==$base_width && $height==$base_height)return format_url($imgurl,$domain);
    if($width<=0)$width=100;if($height<=0)$height=100;
    if($autocut)$image->thumb($width, $height,\Common\Vendor\Image::IMAGE_THUMB_CENTER)->save($newimgurl);
    else $image->thumb($width, $height,\Common\Vendor\Image::IMAGE_THUMB_FILLED)->save($newimgurl);    
    $w_str='';$w_arr=array();$warter_value_config=C('THUMB_VALUE');$water_touming=C('THUMB_TOUMING');$water_p=C('THUMB_PALACE');
    if($water=='auto'){$is_water=C('THUMB_TYPE');if($is_water==2){$w_str=$is_water."|".$warter_value_config;}
    }else if($water==1)$is_water=1;else{$w_str=$water;$is_water=2;}
    if($w_str){$w_arr=explode('|',$w_str);$is_water=$w_arr[0];
    $warter_value=!empty($w_arr[1])?$w_arr[1]:'HANCHAO';
    $warter_size=!empty($w_arr[2])?$w_arr[2]:'14';
    $warter_color=!empty($w_arr[3])?$w_arr[3]:'#cccccc';
    $warter_fonts=!empty($w_arr[4])?$w_arr[4]:'warter.ttf';}
    if(empty($warter_value))$warter_value=$warter_value_config;    
    if(!$water_touming)$water_touming=80;  $warter_image=C('IMAGE_WATERMARK');  
    if($is_water==1 && $warter_image && str_exists($warter_image,'.')){
        $image->open($newimgurl)->water($warter_image,$water_p,$water_touming)->save($newimgurl);
    }
    if($is_water==2 && $warter_value){
        if($warter_fonts)$warter_fonts='Public/fonts/'.$warter_fonts;
        $image->open($newimgurl)->text($warter_value,$warter_fonts,$warter_size,$warter_color,$water_p)->save($newimgurl); 
    }
    return format_url($newimgurl,$domain);
}
/**
  * 调取城市数据函数
  * datatype 地理区域划分省级 letter拼音首字母市级 general普通省级 other其余数据
  * @param  $region 0普通数据 1地理区域省级 2普通省级 3带拼音首字母省级
  */
function get_arearegion_cache($region = 0){
    $data = array();
    $datatype=array('other','region','general','letter');
    $regionUrl = ROOT_PATH.'/Public/data/arearegiondata.json';
    if(!file_exists($regionUrl)) return $data;
    $data = file_get_contents($regionUrl);
    if(!empty($data))$data = json_decode($data,true);
    if($region==0){
        unset($data['region'],$data['general'],$data['letter']);
    }else{
        return $data[$datatype[$region]];
    }
    return $data;
}
/**
  * 获取列表分类筛选
  * @param int $cat_id
  * @return array
  */
function get_current_cate($cat_id = 0){
    if(empty($cat_id))$cat_id=0;
    $map['pid']=$cat_id;
    $cate=M('GoodsCategory')->where($map)->select();
    $info=array();
    if (!empty($cate)) {//如有子类 显示当前和子类 其它不显示
        if($cat_id==0)$info['name']='全部分类';
        else $info=idtoname($cat_id,'GoodsCategory','*','id');
        $info['child']=$cate;
        $info['hover']=1;
        $data[]=$info;
    }else{//如无子分类 显示当前级和上级
        $info=idtoname($cat_id,'GoodsCategory','*','id');
        $pre_info=idtoname($info['pid'],'GoodsCategory','*','id');
        $wher['pid']=$info['pid'];
        $catt=M('GoodsCategory')->where($wher)->select();
        foreach ($catt as $key => $val) {
            if($val['id']==$cat_id){
                $catt[$key]['hover']=1;
            }
        }
        $pre_info['hover']=1;
        $pre_info['child']=$catt;
        $data[]=$pre_info;
    }
    return $data;
}
/**
  * 商品标签
  * 目前只支持列表页
  * @param $param
  * @return mixed
  */
function get_goodslabel_list($param){
    $map=array();
    $map['status']=1;
    $map['type']=0;
    if(isset($param['unsetlabel'])){unset($param['label_'.$param['unsetlabel']],$param['unsetlabel']);}
    $labels=M('ProjectLabel')->field(true)->where($map)->select();
    foreach($labels as $k=>$v){
        $labels[$k]['param']=$param;
    }
    return $labels;
}
/**
   * 删除验证
   * @param int $id
   * @param int $type
   * 1,$code='',会员;$code='rank',会员等级;
   * 2,$code='',店铺;$code='rank',店铺等级;
   * 3,订单,
   * 4,$code='',商品,$code='cate',商品分类,
   * 5,供货商,
   * 6,品牌一级分类
   * 7,$code='Area',地区;$code='ArticleCat',文章分类;$code='Intro',简介分类;$code='AuthRule',管理员组;$code='Nav',导航;
   * 8,活动
   * 9,消费者保障服务
   * 10,限时促销活动
   * @return array
   */
function check_delete($id,$type,$code=''){
    $return=array();
    if(!intval($id)||!intval($type)){$return['info']='参数错误';return $return;}
    if($type==1){
        if($code=='rank'){
            $map=array();
            $map['rank_id']=$id;
            $count=M('Member')->where($map)->count();
            if($count){$return['info']='会员已绑定此等级,不可删除';return $return;}
			$map = array();
			$map['rank_limit']=$id;
			$mcount=M('ManypointsRule')->where($map)->count();
			if(!$mcount){$return['status']=1;}else{$return['info']='等级特权已绑定此等级,请先删除该等级特权';return $return;}
        }else{
            $map=array();
            $map['uid']=$id;
            $count=M('Shops')->where($map)->count();
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先删除会员下的店铺';return $return;}
            $count=M('OrderInfo')->where($map)->count('id');
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清空会员下的订单';return $return;}
        }
    }
    if($type==2){
        if($code=='rank'){
            $map=array();
            $map['rank']=$id;
            $count=M('Shops')->where($map)->count();
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='店铺已绑定此等级,不可删除';return $return;}
        }else{
            $map=array();
            $map['uid']=$id;
            $map['status']=array('lt',3);
            $map['type']=10;
            $count=M('OrderInfo')->where($map)->count();
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='有未完成的订单,不可删除';return $return;}
        }			
    }	
    if($type==3){
        $map=array();
        $map['id']=$id;
        $map['status']=array('lt',3);
        $count=M('OrderInfo')->where($map)->count();
        if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='订单未完结,不可删除';return $return;}
    }
    if($type==4){
        if($code=='cate'){//商品分类
            $map=array();
            $map['pid']=$id;
            $count_cate=M('GoodsCategory')->where($map)->count();
            if(!$count_cate){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除子分类';return $return;}
            $map=array();
            $map['cat_id']=$id;
            $count=M('Goods')->where($map)->count();
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='分类下绑定了商品,无法删除';return $return;}
        }else{//商品
            $map=array();
            $map['goods_id']=$id;
            $order_ids=M('OrderGoods')->where($map)->getField('order_id',true);
            $map=array();
            if($order_ids){
              $map['id']=array('in',implode(',',$order_ids));
              $map['status']=array('lt',3);
              $count=M('OrderInfo')->where($map)->count();
            }
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='此商品关联未完结订单,不可删除';return $return;}
            }
    }
    if($type==5){
        $map=array();
        $map['suppliers_id']=$id;
        $count=M('Goods')->where($map)->count();
        if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除供货商下的商品';return $return;}
    }
    if($type==6){//品牌,一级
        $map=array();
        $map['brand_cat_id']=$id;
        $count=M('Brand')->where($map)->count();
        if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除子分类';return $return;}
    }
    if($type==7){
        $map=array();
        $map['pid']=$id;
        $count=M($code)->where($map)->count();
        if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除子分类';return $return;}
    }
    if($type==8){//活动
        $map=array();
        $map['id']=$id;
        $promote_info=M("PromotAct")->where($map)->field(true)->find();
        if( $promote_info['is_limit_time']==1){
            $map=array();
            $map['promote_id']=$id;
            $map['status'] = 1;
            $map['publish_wait'] = 1;
            $map['is_delete'] = 0;
            $count=M('Goods')->where($map)->count();
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除活动下的商品';return $return;}
        }else if( $promote_info['is_pt']==1){
			$map=array();
			$map['act_id'] = $id;
			$goods_id = M('PromotExt')->where($map)->order('id desc')->getField('style_ext_id');
			$save['pt_id'] = 0;
			$update = M('Goods')->where('id='.$goods_id)->save($save);
			if($update){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除活动下的商品';return $return;}
		}else{
            $map=array();
            $map['type']=3;
            $map['type_value']=$id;
            $count=M('Bonu')->where($map)->count();
            if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除活动下的红包';return $return;}
        }	
    }
    if($type==9){//消费者保障服务 ProjectLabelLink
        $map=array();
        $map['label_id']=$id;
        $map['shop_id']=array('gt',0);
        $count=M('ProjectLabelLink')->where($map)->count('id');
        if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='已有商铺加入此服务,不可删除';return $return;}
    }
    if($type==10){//消费者保障服务 ProjectLabelLink
        $map=array();
        $map['promote_id']=$id;
        $map['status'] = 1;
        $map['publish_wait'] = 1;
        $map['is_delete'] = 0;
        $count=M('Goods')->where($map)->count('id');
        if(!$count){$return['status']=1;}else{$return['status']=0;$return['info']='请先清除活动下的商品';return $return;}
    }
    return $return;
}
/**
  * 商品标签辅助函数
  * @param $param
  * @param $labelid 标签id
  * @return string url
  */
function get_goodslabel_url($param,$labelid='',$unsetlabel=0){
    if($unsetlabel){$param['unsetlabel']=$unsetlabel;}
    $param['label_'.$labelid] = $labelid;
    return geturl('Cate/index',$param,true,true);
}
/**
  * 获取所有限时活动的商品
  * @param $num 商品数量
  * @return mixed
  */
function get_promot_goods($num){
    $num=$num?$num:5;
    $map['status']=1;
    $map['is_delete']=0;
    $map['publish_wait']=1;
    $map['promote_id']=array('gt',0);
    $map['promote_price']=array('gt',0);
    $map['promote_start_time']=array('lt',NOW_TIME);
    $map['promote_end_time']=array('gt',NOW_TIME);
    $pro_goods=M('Goods')->field('id,goods_name,img,promote_end_time,shop_price,promote_price')->where($map)->order('promote_end_time asc')->limit($num)->select();
    return $pro_goods;
}
/**
  * 获取所有服务
  * @param $num 商品数量
  * @return mixed
  */
function get_service_goods($shop_id='',$limit=100,$order='id desc',$content=0,$cat_id=''){
	if(!$shop_id)return false;
	$shop_type = idtoname($shop_id,'Shops','shop_type','id',false);//判断是否是加盟店
	if($cat_id)$map['cat_id'] = $cat_id;
    $map['status']=1;
    $map['is_delete']=0;
    $map['publish_wait']=1;
    $map['goods_type'] = 4;
	if($shop_type == 1){
		// $shopids = ','.$shop_id.',';
		// $map['_string'] = "shop_ids like '%".$shopids."%' OR shop_ids='0'";
		$map['_string'] = "shop_ids = ".$shop_id." OR shop_ids='0'";
	}
	if($shop_type == 2){
		$map['shop_id'] = $shop_id;
	}
    $ser_goods=M('Goods')->field('id,goods_name,sell_count,simple_description,img,shop_price')->where($map)->order($order)->limit($limit)->select();
	if($content == 1){
		foreach($ser_goods as $k=>$v){
			$ser_goods[$k]['content'] = idtoname($v['id'],'GoodsContent','content');
		}
	}
    return $ser_goods;
}
/**
  * 商品浏览历史(登录)
  * @param $uid,$goods_id  会员,商品id
  * @return mixed
  */
function goods_footprint($uid,$goods_id){
    if(!uid || !$goods_id) return false;
    $value=session($uid+'_footer_history');
    $num=C('BROWSING_HISTORY_NUM')?C('BROWSING_HISTORY_NUM'):10;
    if(!in_array($goods_id,$value)){
        if(count($value)>=$num)array_shift($value);
        $value[]=$goods_id;
        $value=array_filter(array_unique($value));
        session($uid+"_footer_history",$value);
    }
    return true;
}
/**
  * 获取商品列表页价格分级的筛选条件
  * @param string $catid
  * @param string $price
  * @param string $goods_type 商品类型
  * @return array
  */
function get_price_map($catid='',$price='',$goods_type=1){
    $return=array();
    if($goods_type==5){
      GLOBAL $PurchaseCategory;$catinfo=$PurchaseCategory[$catid];
    }else{
      GLOBAL $GoodsCategory;$catinfo=$GoodsCategory[$catid];
    }
    if(empty($catinfo)) return $return;
    if ($catinfo['grade'] > 1) {
        $pricelist = get_grade_price($catinfo, $catid,$goods_type);
        $return['pricelist'] = $pricelist;
        if (!empty($price) && !empty($pricelist)) {
            $pricedata = $pricelist[$price];
            if (!empty($pricedata)) {
                if (str_exists($pricedata, '-')) {
                    $pricearr = explode('-', str_replace('&nbsp;', '', $pricedata));
                    $return['shop_price'][] = array('EGT', $pricearr[0]);
                    $return['shop_price'][] = array('elt', $pricearr[1]);
                } else if (str_exists($pricedata, '以上')) {
                    $return['shop_price'] = array('EGT', str_replace('以上', '', $pricedata));
                }
            }
        }
    }
    return $return;
}
/**
  * 获取价格分级
  * @param array $cat
  * @return array
  *算法思路：
  *1、当分级大于1时，进行价格分级
  *2、取出该类下商品价格的最大值、最小值
  *3、根据商品价格的最大值来计算商品价格的分级数量级：
  *价格范围(不含最大值)    分级数量级
  *0-0.1                   0.001
  *0.1-1                   0.01
  *1-10                    0.1
  *10-100                  1
  *100-1000                10
  *1000-10000              100
  *4、计算价格跨度：
  *取整((最大值-最小值) / (价格分级数) / 数量级) * 数量级
  *5、根据价格跨度计算价格范围区间
  *6、查询数据库
  *可能存在问题：
  *1、
  *由于价格跨度是由最大值、最小值计算出来的
  *然后再通过价格跨度来确定显示时的价格范围区间
  *所以可能会存在价格分级数量不正确的问题
  *该问题没有证明
  *2、$Model = new \Think\Model() // 实例化一个model对象 没有对应任何数据表
  *$Model->query("select * from __PREFIX__user where status=1");
  *当价格=最大值时，分级会多出来，已被证明存在
  *$goods_type 商品类型
  */
function get_grade_price($cat,$catid='',$goods_type=1){
    if(empty($catid)) return false;
    $map=array();
    $map['g.status']=1;
    $map['g.publish_wait']=1;
    $map['g.is_delete']=0;
    if($goods_type==5){
      $map['g.goods_type']=5;
      GLOBAL $PurchaseCategory;
      $catinfo = $PurchaseCategory[$catid];
    }else{
      $map['g.goods_type']=1;
      GLOBAL $GoodsCategory;
      $catinfo = $GoodsCategory[$catid];
    }
    $extension_goods=get_extension_goods($catinfo['allson'],1);
    $whereor['g.cat_id']=array('in',$catinfo['allson']);
    if($extension_goods)$whereor['g.id']=array('in',$extension_goods);
    $whereor['_logic'] = 'or';
    $map['_complex'] = $whereor;
    $row = M('Goods')->alias('g')->field('min(g.shop_price) AS min, max(g.shop_price) AS max')->where($map)->find();
    // 取得价格分级最小单位级数，比如，千元商品最小以100为级数
    $price_grade = 0.0001;
    for($i=-2; $i<= log10($row['max']); $i++){$price_grade *= 10;}      //100
    //跨度
    $dx = ceil(($row['max'] - $row['min']) / ($cat['grade']) / $price_grade) * $price_grade;
    if($dx == 0){$dx = $price_grade;}   
    for($i = 1; $row['min'] > $dx * $i; $i ++);
    for($j = 1; $row['min'] > $dx * ($i-1) + $price_grade * $j; $j++);
    $row['min'] = $dx * ($i-1) + $price_grade * ($j - 1);
    for(; $row['max'] >= $dx * $i; $i ++);
    $row['max'] = $dx * ($i) + $price_grade * ($j - 1);
    $price_grade = M('Goods')->alias('g')->field('(FLOOR((g.shop_price - '.$row['min'].') / '.$dx.')) AS sn, COUNT(*) AS goods_num')->where($map)->group('sn')->select();
    foreach ($price_grade as $key=>$val){
        $temp_key = $key + 1;
        $price_grade[$temp_key]['goods_num'] = $val['goods_num'];
        $price_grade[$temp_key]['start'] = $row['min'] + round($dx * $val['sn']);
        $price_grade[$temp_key]['end'] = $row['min'] + round($dx * ($val['sn'] + 1));
        $price_grade[$temp_key]['price_range'] = $price_grade[$temp_key]['start'] . '&nbsp;-&nbsp;' . $price_grade[$temp_key]['end'];
        $price_grade[$temp_key]['formated_start'] = number_format($price_grade[$temp_key]['start'] ,2, '.', '');
        $price_grade[$temp_key]['formated_end'] = number_format($price_grade[$temp_key]['end'],2, '.', '');
        $price_grade[$temp_key]['url'] = U('Cate/Index', array('cid'=>$catid, 'bid'=>$brand, 'price_min'=>$price_grade[$temp_key]['start'], 'price_max'=> $price_grade[$temp_key]['end'], 'filter_attr'=>$filter_attr_str));
        /* 判断价格区间是否被选中 */
        if (isset($_REQUEST['price_min']) && $price_grade[$temp_key]['start'] == $price_min && $price_grade[$temp_key]['end'] == $price_max){
            $price_grade[$temp_key]['selected'] = 1;
        }else{
            $price_grade[$temp_key]['selected'] = 0;
        }
        $pricelist[$temp_key] = $price_grade[$temp_key]['price_range'];
    }
    return $pricelist;
}
/**
  *获取代金券
  * @param int $user_id 会员id
 * @param int $cart_ids 购物车ids
 * @param int $goods_ids 商品ids
  */
function get_online_bonus($goods_money,$user_id,$cart_ids='',$goods_ids=''){
    $shop_id=get_wxsmall_shop_id();
    $now_time=NOW_TIME;
    if($cart_ids){
        $map=array();
        $map['id']=array('in',$cart_ids);
        $goods_ids=M('Cart')->where($map)->getField('goods_id',true);
    }
    $act_id=array();
    if($goods_ids){
        $map=array();
        $map['style_ext_id']=array('in',$goods_ids);
        $map['style']=6;
        $act_id = M('PromotExt')->where($map)->getField('act_id',true);
    }

    $map=$bouns_info=array();
    if(!empty($act_id)){
        $map_p=$c_map=array();
        $map_p['style']=6;
        $act_idg = M('PromotExt')->where($map_p)->getField('act_id',true);//获取所有绑商品的优惠券id
        if($act_idg){
            $c_map['coupons_id']=array('not in',$act_idg);
        }
        $coupons_id=M('CouponsGet')->where($c_map)->getField('coupons_id',true);//获取不绑商品的优惠券id
        if($coupons_id){
            $actids=array_merge($act_id,$coupons_id);
            $map['c.id']=array('in',$actids);
        }
        
    }
    
    if(empty($act_id) && empty($coupons_id)){
        $return['total']=0;
        $return['list']=array();
        return $return;
    }
    $map['cg.status']=0;
    $map['cg.uid']=$user_id;
    $map['_string']='(cg.begin_timestamp = 0 or cg.begin_timestamp <= '.$now_time.') and (cg.end_timestamp = 0 or cg.end_timestamp >= '.$now_time.')';
    $list = M('CouponsGet')->alias('cg')->where($map)->JOIN('JOIN __COUPONS__ c ON cg.coupons_id=c.id')->field('c.type,c.begin_timestamp,c.end_timestamp,c.fixed_term,c.notice,c.color,c.title,c.is_show,cg.id,c.discount,c.reduce_cost,c.least_cost,cg.rank_id')->select();
    $total=count($list);
    if($total > 0){
        foreach($list as $k=>$v){
            $list[$k]['reduce_cost'] = intval($v['reduce_cost']);
            $list[$k]['least_cost'] = Intval($v['least_cost']);
            if(!empty($list[$k]['is_show'])){
                $list[$k]['is_show'] = array_filter(explode(',',$list[$k]['is_show']));
            }
            if($list[$k]['rank_id'] == 'DISCOUNT'){
                $discount= (100-$v['discount'])/100;
                $list[$k]['discount'] = (100-$v['discount'])/10;
                $list[$k]['jian_money']=($v['discount']/100)*$goods_money;
            }else{
                $list[$k]['jian_money'] =$v['reduce_cost'];
            }
            if(!empty($v['is_show'])){
                $is_show = array_filter(explode(',',$v['is_show']));
                if(!in_array($shop_id,$is_show)){
                    unset($list[$k]);
                }
            }
        }
    }
    $return['total']=count($list);
    $return['list']=$list;
    return $return;
}
/**
  *@return string 1,第一次打开,2,已打开过
  */
function is_first_open(){
    $is_first_open=session('slide_open');
    if($is_first_open){session('slide_open',2);}else{session('slide_open',1);}
    return session('slide_open');
}
/**
  * 检查会员登录状态 适用于APP请求 各个模块请求
  */
function checkuserauthtype(){
    $AppId=isset($_SERVER['HTTP_X_APICLOUD_APPID'])?$_SERVER['HTTP_X_APICLOUD_APPID']:0;
    $AppKey=isset($_SERVER['HTTP_X_APICLOUD_APPKEY'])?$_SERVER['HTTP_X_APICLOUD_APPKEY']:0;
    $return=array('status'=>3,'msg'=>'获取登录信息错误,请重新登录!');
    $paramdata=I('param.');
    if($AppId&&$AppKey){//APP请求
        if((!isset($paramdata['uid'])||!isset($paramdata['token']))||isset($paramdata['nologin']))return $return;
        $paramdata['uid']=intval($paramdata['uid']);
        if(empty($paramdata['uid']) || empty($paramdata['token'])){$return['msg']='获取登录信息错误,请重新登录!';
            echo(json_encode($return));exit;
        }
        $memberinfo=idtoname($paramdata['uid'],'Member','*');
        $appkeyarr=explode('.',$AppKey);
        $timestamp=$appkeyarr[1];
        if(SHA1($memberinfo['password'].$timestamp)!=SHA1($paramdata['token'].$timestamp)){
            echo(json_encode($return));exit;
        }
        return $memberinfo;
    }
    if(isset($paramdata['HCtoken'])){
        if(empty($paramdata['HCtoken'])){$this->ajaxReturn($return);}
        $result = D('Wxsmall/Login')->check_wxsmall_code($paramdata);
        if($result['status']==1){
            $userinfo=idtoname($result['uid'],'Member','*','id',false);
            $userinfo['HCshop']['bind_shop_id'] = $result['bind_shop_id']?$result['bind_shop_id']:0;
            $userinfo['HCshop']['code'] = $result['code']?$result['code']:'';
            $userinfo['HCshop']['send'] = $result['send']?$result['send']:0;
            if(empty($userinfo['HCshop']['bind_shop_id'])&&isset($paramdata['HCshopid'])&&$paramdata['HCshopid']>0){
                $userinfo['HCshop']['bind_shop_id'] = $paramdata['HCshopid'];
            }
            return $userinfo;
        }else{
            $return['msg'] = $result['msg'];
            $return['code'] = $result['code'];//使小程序自动拉取会员授权信息，重新登录
        }
        echo(json_encode($return));exit;
    }
    $memberinfo = session('member_info');
    if($memberinfo)return $memberinfo;
}
/**
 * 检查门店登录状态 适用于APP请求 各个模块请求
 */
function checkshopauthtype(){
    $AppId=isset($_SERVER['HTTP_X_APICLOUD_APPID'])?$_SERVER['HTTP_X_APICLOUD_APPID']:0;
    $AppKey=isset($_SERVER['HTTP_X_APICLOUD_APPKEY'])?$_SERVER['HTTP_X_APICLOUD_APPKEY']:0;
    $return=array();
    if($AppId&&$AppKey){//APP请求
        $paramdata=I('param.');
        if((!isset($paramdata['shopuid'])||!isset($paramdata['shoptoken']))||isset($paramdata['nologin']))return $return;
        $return['status'] = 3;
        $return['msg']='获取登录信息错误,请重新登录!';
        $paramdata['shopuid']=intval($paramdata['shopuid']);
        if(empty($paramdata['shopuid']) || empty($paramdata['shopuid'])){
            echo(json_encode($return));exit;
        }
        $shopinfo=idtoname($paramdata['shopuid'],'ShopsAccount','*','id',false);
        $appkeyarr=explode('.',$AppKey);
        $timestamp=$appkeyarr[1];
        if(SHA1($shopinfo['password'].$timestamp)!=SHA1($paramdata['shoptoken'].$timestamp)){
            echo(json_encode($return));exit;
        }
        $shopinfo=D('Common/ShopLogin')->loginupdate($paramdata['shopuid']);
        return $shopinfo;
    }
    $shop_info = session('shops_info');
    if($shop_info)return $shop_info;
}
/**
  * 获取登录店铺地址 $address_info['province'],$address_info['city'],$address_info['district']
  */
function getshopaddress($shop_id=''){
  if($shop_id){
    $position = M('Shops')->where('id='.$shop_id)->field('province,city_id,district')->find();
    if($position){
      $return['province'] = $position['province'];
      $return['city'] = $position['city_id'];
      $return['district'] = $position['district'];
      return $return;
    }
  }
}
/**
  * 检查会员定位信息 适用于APP请求 各个模块请求 $address_info['province'],$address_info['city'],$address_info['district']
  */
function checkuseraddress($address=''){
    $cookie_time=3600*24*7;
    if(!empty($address)){
        cookie('dingwei_address',$address,$cookie_time);
        session('dingwei_address',$address);return $address;
    }
    $address_info_cookie = cookie('dingwei_address');//获取定位信息
    $address_info_session = session('dingwei_address');//获取定位信息 
    if(!empty($address_info_cookie)){
        if(empty($address_info_session))session('dingwei_address',$address_info_cookie);
        return $address_info_cookie;
    }
    if(!empty($address_info_session)){
        if(empty($address_info_cookie))cookie('dingwei_address',$address_info_session,$cookie_time);
        return $address_info_cookie;
    }
    $AppId=isset($_SERVER['HTTP_X_APICLOUD_APPID'])?$_SERVER['HTTP_X_APICLOUD_APPID']:0; 
    $AppKey=isset($_SERVER['HTTP_X_APICLOUD_APPKEY'])?$_SERVER['HTTP_X_APICLOUD_APPKEY']:0;
    $return=array();
    //测试阶段屏蔽
    if($AppId&&$AppKey){//APP请求
        $paramdata=I('param.');
        if(!empty($paramdata['province']))$address_info['province'] = $paramdata['province'];
        if(!empty($paramdata['city']))$address_info['city'] = $paramdata['city'];
        if(!empty($paramdata['district']))$address_info['district'] = $paramdata['district'];
        if($address_info){
            cookie('dingwei_address',$address_info,$cookie_time);
            session('dingwei_address',$address_info);
        }
        return $address_info;
    }else{
        return $return;
    }
}
/**
  * 签到赠消费积分
  */
function give_login_point($uid,$is_check = true){
    if(!$uid)return false;
	if($is_check){
		$map = array();$map['id']=$uid;
		$map['sign_time']=array('gt',strtotime(date('Y-m-d',NOW_TIME)));
		$count=M('Member')->where($map)->count();
		if($count){
			$res['status'] = 2;
			return $res;exit;
		}
	}
	$res['status'] = 0;
	$usepoints=C('LOGIN_GAIN_SELL_INTEGRAL');
	if($usepoints>0){
		account_change($uid,$usepoints,4,5,'签到赠积分');
		$res['status'] = 1;
		$res['usepoints'] = $usepoints;
	}
	return $res;
}
/**
  * 返回会员累计签到天数
  */
function getmiddlenum($now=0,$max=30,$step=7){
	$middle=$step/2;$start=1;
	if($now>$middle){
		$start+=ceil($now-$middle);
	}
	$array=array();$end=$start+$step;
	if($end>$max){
		$end=$max+1;$start=$end-$step;
	}
	for($i=$start;$i<$end;$i++){$array[]=$i;}
	return $array;
}
/**
  * 会员累计签到修改member表和添加签到记录win_gift表
  */
function save_sign($day_num,$uid){
	$return = array();
	$map = array();$map['id']=$uid;
	$map['sign_time']=array('gt',strtotime(date('Y-m-d',NOW_TIME)));
	$count=M('Member')->where($map)->count();
	if($count){
		$u_map = array();$u_map['id']=$uid;
		$return['status'] = 2;
		$return['is_day'] = M('Member')->where($u_map)->getField('sign_day_num');
		$return['msg'] = '已经签到过了！';
		return $return;
	}
	if($day_num && $uid){
		// 是否为实物;是否领取;礼品名称;礼品数量
		$gift_type = 0;$check_status = 1;$sign_points = '积分';
		$gift_number = C('LOGIN_GAIN_SELL_INTEGRAL');
		if(C('SIGN_TYPE') == 1){
			$sign_info = json_decode(C('SIGN_INFO'),true);
			if($sign_info['gift_num'] && $day_num && $day_num == $sign_info['gift_day']){
				if($sign_info['gift_type'] == 1){
					$gift_number = 1;
					$gift_type = 1;$check_status = 0;
					$sign_points = $sign_info['gift_num'].'礼品';
				}else if($sign_info['gift_type'] == 2){
					$gift_number = $sign_info['gift_num'];
					$sign_points = '现金';
					account_change($uid,$sign_info['gift_num'],1,5,'累计签到'.$day_num.'天赠现金');
				}else if($sign_info['gift_type'] == 3){
					$gift_number = $sign_info['gift_num'];
					$sign_points = '积分';
					account_change($uid,$sign_info['gift_num'],4,5,'累计签到'.$day_num.'天加赠积分');
				}else if($sign_info['gift_type'] == 4){
					$gift_number = 1;
					$c_map = array();$c_map['id'] = $sign_info['gift_num'];
					$coupons = M('Coupons')->where($c_map)->field(true)->find();
					if($coupons){
						$add_data = array();
						$add_data['coupons_id'] = $coupons['id'];
						$add_data['card_id'] = $coupons['card_id'];
						$add_data['rank_id'] = $coupons['rank_id'];
						$add_data['discount'] = $coupons['discount'];
						$add_data['reduce_cost'] = $coupons['reduce_cost'];
						$add_data['least_cost'] = $coupons['least_cost'];
						if($coupons['type'] == 1){
							$add_data['begin_timestamp'] = $coupons['begin_timestamp'];
							$add_data['end_timestamp'] = $coupons['end_timestamp'];
						}else{
							$now_time = NOW_TIME;
							$begin_timestamp = $now_time + $coupons['fixed_begin_term']*24*3600;
							$end_timestamp = $begin_timestamp + $coupons['fixed_begin_term']*24*3600;
							$add_data['begin_timestamp'] = $begin_timestamp;
							$add_data['end_timestamp'] = $end_timestamp;
						}
						$add_data['add_time'] = time();
						$add_data['uid'] = $uid;
						$add_data['code'] = time().rand(1000,9999).$uid;
						$add = M('CouponsGet')->add($add_data);
						if($add)M('Coupons')->where($c_map)->setDec('quantity',1);
					}
					$sign_points = $coupons['name'].'优惠券';
				}
				$rr['status'] = 1;
			}else{
				$rr = give_login_point($uid,true);
			}
		}else{
			$rr = give_login_point($uid,true);
		}
		$data = array();
		$data['sn_number'] = createOrderNo();
		$data['order_id'] = $data['gift_id'] = 0;
		$data['gift_name'] = $sign_points;
		$data['gift_type'] = $gift_type;
		$data['win_type'] = 5;
		$data['gift_number'] = $gift_number;
		$data['user_id'] = $uid;
		$data['check_status'] = $check_status;
		if($data['check_status'] == 1){
			$data['add_time'] = $data['check_time'] = NOW_TIME;
		}else{
			$data['check_time'] = 0;
			$data['add_time'] = NOW_TIME;
		}
		$res = M('WinGift')->add($data);
		if($res && $rr['status'] == 1){
			$return['status'] = 1;
			//member表存数据
			save_sign_member($day_num,$uid);
			if($data['check_status'] == 1){$return['msg'] = '签到成功！';}
			else{$return['msg'] = '签到成功，实物礼品请到我的资金->我的礼品中查看！';}
			$u_map = array();$u_map['id']=$uid;
			$return['is_day'] = M('Member')->where($u_map)->getField('sign_day_num');
			$return['all_points'] = M('Member')->where($u_map)->getField('usepoints');
		}else if($res && $rr['status'] == 2){
			$u_map = array();$u_map['id']=$uid;
			$return['status'] = 2;
			$return['is_day'] = M('Member')->where($u_map)->getField('sign_day_num');
			$return['all_points'] = M('Member')->where($u_map)->getField('usepoints');
			$return['msg'] = '已经签到过了！';
		}else{
			$return['status'] = 0;
		}
	}else{
		$return['status'] = 0;
	}
	return $return;
}
function save_sign_member($day_num,$uid){
	if($day_num > 30) $sign_day_num = 1;
	else $sign_day_num = $day_num;
	$u_save = array();
	$u_save['sign_day_num'] = $sign_day_num;$u_save['sign_time'] = NOW_TIME;
	$u_map = array();$u_map['id'] = $uid;
	M('Member')->where($u_map)->save($u_save);
}
/**
  * 注册赠积分
  */
function give_register_point($uid){
    if(!$uid)return false;
    //注册赠消费积分
    $usepoints=C('REG_GAIN_SELL_INREGRAL');
    if($usepoints>0){
        account_change($uid,$usepoints,4,9,'注册赠积分');
    }
}
/**
  * 获取上一个页面的链接
  */
function get_forward(){
    $forward=cookie('forward')?cookie('forward'):$_SERVER['HTTP_REFERER'];
    return $forward;
}
/**
 * 属性ID转化为中文名字
 * @param string $key 属性ID字符
 * @param $goods_id 商品ID
 * @param $cache 是否缓存
 * @return $back array 直接返回数组 其它为分隔符
 */
function attr_key2name($key,$goods_id=0,$cache=true,$back=' '){
    if(empty($key) || empty($goods_id))return '';
    $map=array();
    $map['g.goods_id']=$goods_id;
    $map['g.id']=str_exists($key,'_')?array('in',explode('_',$key)):$key;
    $map['a.type']='checkbox';
    $attrlist=M('GoodsAttr')->alias('g')->join('__GOODS_ATTRIBUTE__ a on g.attr_id=a.id')->where($map)->cache($cache)->field('g.attr_value,a.options,a.name')->select();
    $data=array();
    foreach($attrlist as $v){
        $array=strtoarray($v['options']);
        $data[]=$array[$v['attr_value']];
    }
    $list=array_filter($data);
    if(empty($list))return '';
    return $back=='array'?$list:implode($back,$list);
}
/**
 * 查询或检测店铺余额
 * @param $shop_id 店铺ID
 * @param $money 检测余额是否达到此值
 */
function shopbalance($shop_id,$money='0'){
    $shop_id = intval($shop_id);
    if(empty($shop_id))return false;
    $map=array();
    $map['id']=$shop_id;
    $map['status']=1;
    $balance=M('Shops')->where($map)->getField('total_revenues');
    $money=floatval($money);
    return $money?$balance>=$money:$balance;
}
/**
  *获取友情链接
  */
function get_friendlink($catid=2,$limit=5){}
//更新计划任务
function updatetask($config_info){
	if(empty($config_info) || empty($config_info['id']))return;
    $data=array();
	$next_time=intval($config_info['next_time'])?$config_info['next_time']:$config_info['start_time'];
	$data['last_time']=$next_time;
	$data['next_time']=$next_time+$config_info['interval_time']*$config_info['execute_time'];
	$map=array();
	$map['id']=$config_info['id'];
	M('Cron')->where($map)->save($data);
}
/**
  * 获取供货商资金变更对应数组
  * @param $key
  * @param $field
  */
function supplier_balancetype($key='',$field=''){
    $array=array(
    1=>array('field'=>'money','name'=>'余额'),
    2=>array('field'=>'unbalance','name'=>'未结算金额'),
    3=>array('field'=>'onbalance','name'=>'待结算金额'),
    4=>array('field'=>'freeze_price','name'=>'冻结资金'),
    5=>array('field'=>'total_revenues','name'=>'营业总额'),
    );
    if(empty($key) && empty($field))return $array;
    if(!empty($key) && empty($field))return $array[$key]['name'];
    if(!empty($key) && !empty($field))return $array[$key][$field];
    return false;
}
/**
  * 供货商账户变动记录
  * @param int $supplier_id 供货商id
  * @param int $change_money 变动金额
  * @param string $type 变动类型1余额2:unbalance未结算3:onbalance待结算,4:freeze_price冻结5:total_revenues营业总额
  * @param string $status 操作类型1:充值,2:提现,3:订单结算,4:系统结算
  * @param int $change_desc 变动描述
  * @param int $order_info 订单信息
  * @param int $adminid 操作管理员ID
  */
function supplier_balance_log($supplier_id, $change_money=0, $type=0, $status=4, $change_desc='', $order_info='',$adminid=0){
    $allowfields=supplier_balancetype();
    if(empty($allowfields) || !is_array($allowfields))return false;
    if(empty($supplier_id) || empty($change_money) || floatval($change_money)==0 || empty($allowfields[$type]))return false;
    $field=$allowfields[$type]['field'];
    $Suppliers=M('Suppliers');$where=array();$where['id']=$supplier_id;
    $suppliers_info=$Suppliers->where($where)->count();
    if (!$suppliers_info)return false;
    $change_money=format_decimal($change_money,2,2);
    if ($change_money>0) {
      $Suppliers->where($where)->setInc($field,$change_money);
      $log_data['change_type']=0;
      $log_data['change_num']=$change_money;
    }else{
      $Suppliers->where($where)->setDec($field,-$change_money);
      $log_data['change_type']=1;
      $log_data['change_num']=-$change_money;
    }
    $log_data['suppliers_id']=$supplier_id;
    $log_data['type']=$type;
    $log_data['end_num']=$Suppliers->where("`id`='".$supplier_id."'")->getField($field);
    $log_data['status']=$status;
    $log_data['adminid']=$adminid;
    $log_data['order_id']=$order_info['id']?$order_info['id']:0;
    $log_data['change_time']=NOW_TIME;
    if($change_desc){
        $log_data['change_desc']=$change_desc;
    }else{
        if($change_money>0){
            if($order_info){
                $log_data['change_desc']='订单'.$order_info['order_sn'].'结算入账'.$change_money;
            }else{
                $log_data['change_desc']='入账'.$change_money;
            }
        }else{
            if($order_info){
                $log_data['change_desc']='订单'.$order_info['order_sn'].'支出'.-$change_money;
            }else{
                $log_data['change_desc']='支出'.-$change_money;
            }
        }
    }
    $result = M('SupplierbalanceLog')->add($log_data);
    return $result;
}
function getShopid($shop_ids='',$type=0,$count=1){
	$module = 'ShopsAccount';
	$join = '';$field = true;$geo=true;
    $map = array();
	$result = get_position_temp_param();
	if($result['append_field'])$field = array();
	$order = $result['order'];
	$field = $result['append_field'];		
	$map['a.status'] = 1;
	$map['a.pid'] = 0;
	$map['g.status'] = 1;
	if($shop_ids){
		$map['g.id'] = array('IN',$shop_ids);
	}
    $join = 'LEFT JOIN __SHOPS__ g ON g.id=a.shop_id';
    $result = page_list($module,$map,$order,$field,$count,$join);
	if($type == 1){
		return $result['list'];
	}else{
		return $result['list']['0']['id'];
	}
}
function get_position_temp_param($alias='g'){
	$siteinfo=session('siteinfo')?session('siteinfo'):cookie('siteinfo');
	$xpoint=$siteinfo['temp_lng'];
	$ypoint=$siteinfo['temp_lat'];
	$return = array();
	if($xpoint>0){		
		$pi = PI();  //圆周率
		$r = 6378137;  //地球平均半径(米)
		$return['append_field'] = array("(ACOS(SIN(($ypoint * $pi)/180)*SIN(($alias.ypoint*$pi)/180 )+COS(($ypoint*$pi)/180 )* COS(($alias.ypoint*$pi)/180)*COS(($xpoint*$pi)/180-($alias.xpoint*$pi)/180))*$r)"=>"distance",'g.*');
		$return['order'] = array("distance"=>"asc");
	}else{
		$return['order'] = array("$alias.id"=>"desc");
	}
	return $return;
}
//根据收货地址获取可以配送的门店列表
function getShop($type=0,$count=10){
	$module = 'ShopsAccount';
	$join = '';$field = true;$geo=true;
    $map = array();
	$result = get_shop_param();
	if($result['append_field'])$field = array();
	$order = $result['order'];
	$field = $result['append_field'];		
	$map['a.status'] = 1;
	$map['a.pid'] = 0;
	$map['g.status'] = 1;
    $join = 'LEFT JOIN __SHOPS__ g ON g.id=a.shop_id';
    $result = page_list($module,$map,$order,$field,$count,$join);
	$ma_info = session('ma_info');
	if($ma_info){
		$xpoint=$ma_info['xpoint'];
		$ypoint=$ma_info['ypoint'];
	}else{
		$siteinfo=session('siteinfo')?session('siteinfo'):cookie('siteinfo');
		$xpoint=$siteinfo['temp_lng'];
		$ypoint=$siteinfo['temp_lat'];
	}
	foreach($result['list'] as $k=>$v){
		$distance = distance($ypoint,$xpoint,$v['ypoint'],$v['xpoint']);
		$s_map['shop_id'] = $v['id'];
		$shop_scale = M('ShopsDelivery')->where($s_map)->order('scale desc')->getField('scale');
		if(!empty($shop_scale)){
			if($shop_scale < $distance){
				unset($result['list'][$k]);
			}
		}
	}
	if($type == 1){
		return $result['list'];
	}else{
		return $result['list']['0']['id'];
	}
}
/**
* 根据两个坐标计算距离(公里)
*/
function distance($lat1, $lng1, $lat2, $lng2){
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;
    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;
    return $km;
}
function get_shop_param($alias='g'){
	$siteinfo=session('siteinfo')?session('siteinfo'):cookie('siteinfo');
	$xpoint=$siteinfo['temp_lng'];
	$ypoint=$siteinfo['temp_lat'];
	$return = array();
	if($xpoint>0){		
		$pi = PI();  //圆周率
		$r = 6378137;  //地球平均半径(米)
		$return['append_field'] = array("(ACOS(SIN(($ypoint * $pi)/180)*SIN(($alias.ypoint*$pi)/180 )+COS(($ypoint*$pi)/180 )* COS(($alias.ypoint*$pi)/180)*COS(($xpoint*$pi)/180-($alias.xpoint*$pi)/180))*$r)"=>"distance",'g.*');
		$return['order'] = array("distance"=>"asc");
	}else{
		$return['order'] = array("$alias.id"=>"desc");
	}
	return $return;
}
/**
* 多倍积分
* @param int $order_id 订单id
*/
function give_double_points($order_id){
    $order_id=intval($order_id);
	if(!$order_id)return false;
	$return = array('points'=>0,'money'=>0);
    $where=array();
    $where['id']=$order_id;
	$order_info = M('OrderInfo')->where($where)->field('uid,order_sn,type,order_money,order_amount,status')->find();
    $map = array();
    $map['status'] = 1;
	if(!$order_info || $order_info['status']!=3 || $order_info['uid']<=0)return false;
	//消费类型
	if($order_info['type'] == 1 || $order_info['type'] == 11 || $order_info['type'] == 14 || $order_info['type']==13 || $order_info['type'] == 6){
		$map['consumption_type'] = array('eq',2);
		//金额限制
		$map['money_limit'] = array('elt',$order_info['order_money']);
	}elseif($order_info['type'] == 2){
		$map['consumption_type'] = array('neq',2);
		//金额限制
		$map['money_limit'] = array('elt',$order_info['order_amount']);
	}
	//等级限制
	$rank_id = idtoname($order_info['uid'],'Member','rank_id','id',false);
	$rank_limit = "'0,".$rank_id."'";
	$map['rank_limit'] = array('IN',$rank_limit);
	//时间限制
	$map['begin_time'] = array('LT',NOW_TIME);
	$map['_string'] = 'end_time >'.NOW_TIME.' or end_time = 0';
	// 赠送优惠券
	$map['give_type'] = 3;
	$coupons_id = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('coupons_id');
    if($coupons_id){
		$is_coupons = 0;
		if($order_info['type'] != 2){
			$c_map = array();$c_map['id'] = $coupons_id;
			$c_map['quantity'] = array('gt',0);$c_map['status'] = 1;
			$coupons = M('Coupons')->where($c_map)->field(true)->find();
			if($coupons['type'] == 1){
				if($coupons['begin_timestamp'] < NOW_TIME && NOW_TIME < $coupons['end_timestamp']){
					$is_coupons = 1;
				}
			}else{
				$is_coupons = 1;
			}
			if($is_coupons == 1){
				$return['coupons'] = 1;
				if($coupons['rank_id'] == 'CASH'){
					$return['get_coupons'] = '满减';
				}
				if($coupons['rank_id'] == 'DISCOUNT'){
					$return['get_coupons'] = '满折';
				}
				if($coupons){
					$add_data = array();
                    $meb_map=array();
                    $meb_map['id']=$order_info['uid'];
                    $member_info=M("Member")->where($meb_map)->field('mobile,username,nickname')->find();
                    $add_data['to']=$member_info['mobile'];
                    if($member_info['username']){
                        $add_data['user_name']=$member_info['username'];
                    }elseif($member_info['nickname']){
                        $add_data['user_name']=$member_info['nickname'];
                    }else{
                        $add_data['user_name']=$member_info['mobile'];
                    }
                    $add_data['first'] = '消费有礼';
                    $add_data['goods_name']=$coupons['title'];
                    $add_data['send_time'] = date('Y-m-d H:i:s',NOW_TIME);
                    $add_data['remark'] = "尊敬的会员，您获得一张卡券，请及时领取";
                    $add_data['type'] = 4;
                    $add_data['content'] = "请领取卡券";
                    $url=U("Mobile/Index/coupons_give",array('id'=>$coupons['id'],'type'=>1,'order_id'=>$order_id),true,true);
                    sendbytheme($add_data,"MEMBER_CARE",$url);
				}
			}
		}
	}
	// 赠送积分
	$map['give_type'] = 2;
	$give_num = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('give_num');
	if($give_num){
		if($order_info['type'] == 2){
			$sell_points=C("RECHARGE_SELL_INTEGRAL_RATE");//充值赠消费积分比例
			$usepoints = format_decimal($order_info['order_amount']*$sell_points*$give_num/100,0,2);
			account_change($order_info['uid'],$usepoints,4,5,'参与会员等级特权活动赠送,充值id'.$order_info['order_sn']);
		}else{
			$sell_points=C("SALES_GAIN_SELL_INTEGRAL_RATE");//消费赠消费积分比例
			$usepoints=format_decimal($order_info['order_amount']*$sell_points*$give_num/100,0,2);
			account_change($order_info['uid'],$usepoints,4,5,'参与会员消费有礼等级特权活动赠送,订单id'.$order_info['order_sn']);
		}
		$return['points'] = 1;
        $return['get_score'] = $usepoints;
	}
	// 赠送现金
	$map['give_type'] = 1;
	$give_money_num = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('give_num');
	if($give_money_num){
		if($order_info['type'] == 2){
			$usepoints = $give_money_num;
			account_change($order_info['uid'],$usepoints,1,5,'参与会员等级特权活动赠送,充值id'.$order_info['order_sn']);
		}else{
			$usepoints = $give_money_num;
			account_change($order_info['uid'],$usepoints,1,5,'参与会员消费有礼等级特权活动赠送,订单id'.$order_info['order_sn']);
		}
		$return['money'] = 1;
        $return['get_money'] = $usepoints;
	}
	return $return;
}
/**
* 查看多倍积分
* @param int $order_id 订单id
*/
function look_give_double_points($order_id){
    $order_id=intval($order_id);
    if(!$order_id)return false;
    $map = array();
    $return = array('points'=>0,'money'=>0,'coupons'=>0);
    $map['status'] = 1;
    $order_info = M('OrderInfo')->where('id='.$order_id)->field('uid,order_sn,type,order_money,order_amount,status')->find();
    if(!$order_info || $order_info['uid']<=0)return false;
    //消费类型
    if($order_info['type'] == 1  || $order_info['type'] == 11 || $order_info['type'] == 14 || $order_info['type']==13){
        $map['consumption_type'] = array('eq',2);
        //金额限制
        $map['money_limit'] = array('elt',$order_info['order_money']);
    }elseif($order_info['type'] == 2){
        $map['consumption_type'] = array('neq',2);
        //金额限制
        $map['money_limit'] = array('elt',$order_info['order_amount']);
    }
      //等级限制
    $rank_id = idtoname($order_info['uid'],'Member','rank_id','id',false);
    $rank_limit = "'0,".$rank_id."'";
    $map['rank_limit'] = array('IN',$rank_limit);
      //时间限制
      // $map['begin_time'] = array('LT',NOW_TIME);
      // $map['_string'] = 'end_time >'.NOW_TIME.' or end_time = 0';
      // 赠送优惠券
    $map['give_type'] = 3;
    $coupons_id = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('coupons_id');
    if($coupons_id && $order_info['type'] != 2){
        $is_coupons = 0;
        $c_map = array();$c_map['id'] = $coupons_id;
        $c_map['quantity'] = array('gt',0);$c_map['status'] = 1;
        $coupons_info = M('Coupons')->where($c_map)->field(true)->find();
        if($coupons_info){
            if($coupons_info['type'] == 1){
                if($coupons_info['begin_timestamp'] < NOW_TIME && NOW_TIME < $coupons_info['end_timestamp']){
                    $is_coupons = 1;
                }
            }else{
                $is_coupons = 1;
            }
            if($is_coupons == 1){
                $return['coupons'] = 1;
                if($coupons_info['rank_id'] == 'CASH'){
                    $return['get_coupons'] = '满减';
                }
                if($coupons_info['rank_id'] == 'DISCOUNT'){
                    $return['get_coupons'] = '满折';
                }
            }
        }
    }
    // 赠送积分
    $map['give_type'] = 2;
    $give_num = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('give_num');
    if($give_num){
        if($order_info['type'] == 2){
            $sell_points=C("RECHARGE_SELL_INTEGRAL_RATE");//充值赠消费积分比例
            $usepoints = format_decimal($order_info['order_amount']*$sell_points*$give_num/100,0,2);
        }else{
            $sell_points=C("SALES_GAIN_SELL_INTEGRAL_RATE");//消费赠消费积分比例
            $usepoints=format_decimal($order_info['order_amount']*$sell_points*$give_num/100,0,2);
        }
        $return['points'] = 1;
        $return['get_score'] = $usepoints;
    }
      // 赠送现金
    $map['give_type'] = 1;
    $give_money_num = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('give_num');
    if($give_money_num){
        if($order_info['type'] == 2){
            $usepoints = $give_money_num;
        }else{
            $usepoints = $give_money_num;
        }
        $return['money'] = 1;
        $return['get_money'] = $usepoints;
    }
    return $return;
}
/**
* 店铺给会员充值
* @param int $uid会员ID $money 充值金额
*/
function shop_give_double($uid,$money = 0){
	if(!$uid)return false;
	$map = array();
	//消费类型
	$map['consumption_type'] = array('neq',2);
	$map['money_limit'] = array('elt',$money);
	//等级限制
	$rank_id = idtoname($uid,'Member','rank_id','id',false);
	$rank_limit = "'0,".$rank_id."'";
	$map['rank_limit'] = array('IN',$rank_limit);
	//时间限制
	$map['begin_time'] = array('LT',NOW_TIME);
	$map['_string'] = 'end_time >'.NOW_TIME.' or end_time = 0';
	$map['status'] = 1;
	//赠送积分
	$map['give_type'] = 2;
	$give_points = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('give_num');
	$sell_points=C("RECHARGE_SELL_INTEGRAL_RATE");//充值赠消费积分比例
	if($give_points){
		$usepoints = format_decimal($money*$sell_points*$give_points/100,0,2);
		account_change($uid,$usepoints,4,5,'会员等级特权活动赠送');
		$return['points'] = 1;
	}
	//赠送现金
	$map['give_type'] = 1;
	$give_money = M('ManypointsRule')->where($map)->order('money_limit desc')->getField('give_num');
	if($give_money){
		$usepoints = $give_money;
		account_change($uid,$usepoints,1,5,'会员等级特权活动赠送');
		$return['money'] = 1;
	}
	if($return['points'] != 1){
		$usepoints = format_decimal($money*$sell_points/100,0,2);
		account_change($uid,$usepoints,4,1,'充值赠积分');
	}
}
/**
* 计算等级晋升差距金额
* @param int $uid 会员id
*/
function getRankMoney($uid){
	if(!$uid)return false;
	$grade_choices = C('GRADE_CHOICES');//会员升级选择
	if($grade_choices==1){$return['grade_name']='消费';}else{$return['grade_name']='充值';}
	$money = 0;
	$memberinfo=idtoname($uid,'Member','*','id',false);
	// return $memberinfo;
	if($grade_choices==1){
		$m_map['min_points'] = array('GT',$memberinfo['points']);
		$m_map['id'] = array('GT',$memberinfo['rank_id']);
	}else{
		$m_map['min_points'] = array('GT',$memberinfo['recharge_points']);
		$m_map['id'] = array('GT',$memberinfo['rank_id']);
	}
	$m_map['status'] = 1;
	$min_points = M('MemberRank')->where($m_map)->order('min_points asc')->getField('min_points');
	// return $min_points;
	if($min_points){
		if($grade_choices==1){
			$return['grade_money'] = $min_points - $memberinfo['points'];
			$return['z_money'] = $memberinfo['points'];
		}else{
			$return['grade_money'] = $min_points - $memberinfo['recharge_points'];
			$return['z_money'] = $memberinfo['recharge_points'];
		}
	}else{
		if($grade_choices==1){
			$return['grade_money'] = $min_points - $memberinfo['points'];
			$return['z_money'] = $memberinfo['points'];
		}else{
			$return['grade_money'] = $min_points - $memberinfo['recharge_points'];
			$return['z_money'] = $memberinfo['recharge_points'];
		}
	}
	if($return['grade_money']<=0)$return['grade_money'] = 0;
	if($return['z_money']<=0)$return['z_money'] = 0;
	return $return;
}
/**
* 订货商品获取 起订量
* @param int $goods_id 商品id
*/
function getmoq($goods_id){
  if(!$goods_id)return false;
  $map=array();
  $map['goods_id'] = $goods_id;
  $count = M('GoodsPackage')->where($map)->count();
  if($count){
    $package = M('GoodsPackage')->where($map)->find();
    $return = $package;
    $return['unit_name'] = $package['name'];
    $return['pack_id'] = $package['id'];
  }else{
    $return = M('Goods')->where('id='.$goods_id)->field('moq,unit_name,shop_price,supply_price')->find();
    $return['pack_id'] = 0;
  }
  return $return;
}
/**
 * 门店顾客数量统计
 * @param $uid 会员id
 * @param $shop_id 门店id
 **/
function shops_customer($uid='',$shop_id=''){
  $c_map = $a_map = $save = $result = array();$return['status'] = 0;
  if(empty($uid) || empty($shop_id)) return false;
  $c_map['user_id'] = $uid;
  $c_map['shop_id'] = $shop_id;
  $count = M('ShopsCustomer')->where($c_map)->count();
  if($count <= 0){
    $a_map = $c_map;
    $a_map['add_time'] = NOW_TIME;
    $result = M('ShopsCustomer')->add($a_map);
    if($result){
      $return['status'] = 1;
    }
  }else{
    $save['add_time'] = NOW_TIME;
    $result = M('ShopsCustomer')->where($c_map)->save($save);
    if($result){
      $return['status'] = 1;
    }
  }
  return $return;
}
/**
  *获取评论标签个数
  */
/*function get_tag_num($tag_name,$group_id=1,$type=7,$dp_id){
	$count = 0;
	$map=array();
	$map['tag_name']=$tag_name;
	if($group_id == 2 && $type == 7){
		$map['group_id']=$group_id;
		$map['type']=$type;
	}
	if(empty($dp_id)){
		$count=0;
	}else{
		$map['dp_id']=array('in',$dp_id);
		$count=M('MemberTagLink')->where($map)->count('*');
		$count=$count?$count:0;
	}
	return $count;
}*/
/**
  *获取评论标签个数
  * @param $tag_name 标签name
  * @param $group_id 1商品2服务
  * @param $goods_id 商品或者服务ID
  */
function get_tag_num($tag_name,$group_id=1,$goods_id){
	$count = 0;
	$map=array();
	$map['tag_name']=$tag_name;
	if($group_id == 2){
		$map['group_id']=2;
		$map['type']=7;
	}else{
		$map['group_id']=1;
		$map['type']=4;
	}
	if($goods_id){
		$map['type_id']=$goods_id;
		$count=M('MemberTagLink')->where($map)->count();
		$count=$count?$count:0;
	}
	return $count;
}
/**
 * 用于展示地图标签显示定位结果
 * @param $x
 * @param $y
 */
function showlocation($x='',$y=''){
    if(empty($x) || empty($y)) return '未定位';
    return '已定位:'.$x.','.$y;
}
//更新微信信息
function updatememberinfo($openid){
    if(empty($openid))return false;
    $Weixin = new \Common\Vendor\WeixinChat();
    $wxdata = $Weixin->user($openid);
    if($wxdata['headimgurl']){
        $map = array();
        $map['wxid'] = $openid;
        $member_data = array(
            'nickname'  =>$wxdata['nickname'],
            'header_img'=>$wxdata['headimgurl'],
            'wx_unionid'=>$wxdata['unionid'],
        );
        $res= M('Member')->where($map)->save($member_data);
        if($wxdata['unionid']){
            $where = array();
    		$where['openid']=$wxdata['unionid'];
    		$o_member = M('OauthMember')->where($where)->count();
    		if(empty($o_member)){
                $ipid=get_client_ip(1);
                $uid = M('Member')->where($map)->getField('id');
                if(empty($uid))return false;
    			$data = array(
    				'_from'				 => 'weixin',
    				'_name'				 => $wxdata['nickname']?$wxdata['nickname']:$openid,
    				'head_img'			 => $wxdata['headimgurl'],
    				'create_time'		 => NOW_TIME,
    				'lock_to_id'		 => $uid,
    				'last_login_time'	 => NOW_TIME,
    				'last_login_ip'		 => $ipid,
    				'login_times'		 => 1,
    				'status'			 => 1,
    				'access_token'		 => 0,
    				'expires_date'		 => 0,
    				'openid'			 => $wxdata['unionid'],
    			);
    			M('OauthMember')->add($data);
    		}
        }
    }return true;
}
/**
 * 通过openid获取uid 没有进行添加
 * @param $openid
 */
function GetmdataBywx($openid,$shop_id=0){
    if(!$openid) return false;
    $map = array();
    $map['wxid'] = $openid;
    $member_info = M('Member')->where($map)->field(true)->find();
    if($member_info){
        $member_info['reg_type'] = 0;        
        if(empty($member_info['nickname']) || empty($member_info['header_img']) || empty($member_info['wx_unionid'])){
            updatememberinfo($openid);
        }
        return $member_info;
    }else{
        $Weixin = new \Common\Vendor\WeixinChat();
        $wxdata = $Weixin->user($openid);
        if(empty($wxdata))return false;
        $map = array();
        $map['wx_unionid'] = $wxdata['unionid'];
        $member_info = M('Member')->where($map)->field(true)->find();
        if($member_info){
            $member_data=array();
            $member_data['wxid']=$openid;
            M('Member')->where($map)->save($member_data);
            return $member_info;
        }
        $ipid=get_client_ip(1);
		$ExtensionId=cookie('ExtensionId');
        $ExtensionShopid=!empty($shop_id)?$shop_id:cookie('ExtensionShopid');
		if($wxdata['unionid']){
			$where = array();
			$where['openid']=$wxdata['unionid'];
			$o_member = M('OauthMember')->where($where)->count();
			if(empty($o_member)){
				$data = array(
					'_from'				 => 'weixin',
					'_name'				 => $wxdata['nickname']?$wxdata['nickname']:$openid,
					'head_img'			 => $wxdata['headimgurl'],
					'create_time'		 => NOW_TIME,
					'lock_to_id'		 => 0,
					'last_login_time'	 => NOW_TIME,
					'last_login_ip'		 => $ipid,
					'login_times'		 => 1,
					'status'			 => 1,
					'access_token'		 => 0,
					'expires_date'		 => 0,
					'openid'			 => $wxdata['unionid'],
				);
				M('OauthMember')->add($data);
			}
            $member_data = array(
                'reg_time'=>NOW_TIME,
                'reg_ip'=>$ipid,
                'rank_id'=>1,
                'parent_id'=>$ExtensionId,
                'is_tmp'=>1,
                'status'=>1,
                'wxid'=>$openid,
                'nickname'=>$wxdata['nickname'],
                'header_img'=>$wxdata['headimgurl'],
                'wx_unionid'=>$wxdata['unionid'],
                'MSN'=>3,
            );
            //jxr start 2018.11.08
            if(intval(C('INHERIT_RECOMMEND'))==1){
                $bind_shop = intval(idtoname($ExtensionId,'Member','user_shop','id',false));
                if($bind_shop)$member_data['user_shop'] = $bind_shop;
            }else{
                if($ExtensionShopid) $member_data['user_shop']=$ExtensionShopid;
            }
            //jxr end 2018.11.08
			//jxr start 2019.05.27
			if(!empty($ExtensionId)){
				$where['id']=$ExtensionId;
				$where['status']=1;
				$p_info=M('Member')->where($where)->field('rank_id')->find();
				if($p_info['rank_id'] >= 2){
					// if($p_info['rank_id']==3){
						// $member_data['pxs_id'] = $ExtensionId;//获取上级培训师
						// $member_data['jxs_id'] = $p_info['jxs_id'];//获取上级经销商
					// }else if($p_info['rank_id']==4){
						// $member_data['jxs_id'] = $ExtensionId;//获取上级培训师
						// $member_data['pxs_id'] = $p_info['pxs_id'];//获取上级培训师
					// }else{
						// $member_data['pxs_id'] = $p_info['pxs_id'];//获取上级培训师
						// $member_data['jxs_id'] = $p_info['jxs_id'];//获取上级经销商
					// }
				}else{
					$member_data['parent_id']=0;
				}
				
			}
			//jxr end 2019.05.27
            $uid = M('Member')->add($member_data);
            //gyc 2019.1.22
            
            $map = array();
            $map['id']=$uid;
            $mem_save['recom_code'] = str_pad($uid,6,0,STR_PAD_LEFT);
            M('Member')->where($map)->save($mem_save);
            //gyc
			$save['lock_to_id'] = $uid;
			M('OauthMember')->where($where)->save($save);
			$member_info = M('Member')->where('id='.$uid)->field(true)->find();
			$member_info['reg_type'] = 1;
			return $member_info;
		}else{
			$map = array();
			$map['wxid'] = $openid;
			$member_info = M('Member')->where($map)->field(true)->find();
			if($member_info){
				return $member_info;
			}else{
				$member_data = array(
					'reg_time'=>NOW_TIME,
					'reg_ip'=>$ipid,
					'rank_id'=>1,
					'parent_id'=>$ExtensionId,
					'is_tmp'=>1,
					'status'=>1,
					'wxid'=>$openid,
					'nickname'=>$wxdata['nickname'],
					'header_img'=>$wxdata['headimgurl'],
                    'MSN'=>1,
				);
                //jxr start 2018.11.08
                if(intval(C('INHERIT_RECOMMEND'))==1){
                    $bind_shop = intval(idtoname($ExtensionId,'Member','user_shop','id',false));
                    if($bind_shop)$member_data['user_shop'] = $bind_shop;
                }else{
                    if($ExtensionShopid) $member_data['user_shop']=$ExtensionShopid;
                }
                //jxr end 2018.11.08
				//jxr start 2019.05.27
				if(!empty($ExtensionId)){
					$where['id']=$ExtensionId;
					$where['status']=1;
					$p_info=M('Member')->where($where)->field('pxs_id,jxs_id,rank_id')->find();
					if($p_info['rank_id'] >= 2){
						// if($p_info['rank_id']==3){
							// $member_data['pxs_id'] = $ExtensionId;//获取上级培训师
						// }else if($p_info['rank_id']==4){
							// $member_data['jxs_id'] = $ExtensionId;//获取上级培训师
						// }else{
							// $member_data['pxs_id'] = $p_info['pxs_id'];//获取上级培训师
							// $member_data['jxs_id'] = $p_info['jxs_id'];//获取上级经销商
						// }
					}else{
						$member_data['parent_id']=0;
					}
					
				}
				//jxr end 2019.05.27
				$uid = M('Member')->add($member_data);
                //gyc 2019.1.22
                $recom_code = M('Member')->where('status=1')->order('recom_code desc')->limit(1)->getField("recom_code");
                $recom_code = $recom_code+1;
                $map = array();
                $map['id']=$uid;
                $mem_save['recom_code'] = $recom_code;
                M('Member')->where($map)->save($mem_save);
                //gyc
				$member_info = M('Member')->where('id='.$uid)->field(true)->find();
				$member_info['reg_type'] = 1;
				return $member_info;
			}
		}
    }
}
/**
* 拓客奖励
* @param string $order_id 订单id
* @param string $f_status 1奖励，2订单分成三级返利
* @param string $award_status bean新增粉丝奖励，register新增会员注册奖励，get_coupon微信卡券新用户赠领，cancel_coupon赠领卡券核销奖励
*/
function TooKeenAward($order_id,$f_status,$award_status='',$send_id=''){
    $return['status'] = 0;
    if(empty($send_id) || empty($award_status)) return $return;
    $affiliate = unserialize(C('AFFILIATE'));
    $map=array();
    $map['id']=$order_id;
    $order_info=M("OrderInfo")->where($map)->field(true)->find();
    if($f_status == 1){
        if($award_status == 'bean') $msg = '新增粉丝';
        if($award_status == 'register') $msg = '新增会员注册';
        if($award_status == 'get_coupon') $msg = '微信卡券新用户赠领';
        if($award_status == 'cancel_coupon') $msg = '赠领卡券核销';
        $unit = $award_status.'_unit';
        $award = $affiliate['config'][$award_status];
        $unit = $affiliate['config'][$unit];//1积分2现金
        $map=array();
        $map['id']=$send_id;
        $member_info=M("Member")->where($map)->field('username,nickname')->find();
        if($member_info['username']){
            $username=$member_info['username'];
        }elseif($member_info['nickname']){
            $username=$member_info['nickname'];
        }
        if($unit == 1 && $award){
            account_change($send_id,$award,4,15,$msg.'，将赠推荐人('.idtoname($send_id,'Member','username;nickname').')，积分：'.$award);
            $log=$msg."将赠推荐人".$username."，积分：".$award;
            affiliate_log($order_id,0,$send_id,0,$award,$log,1);
            //门店扣积分`
            shop_balance_log($order_info['shop_id'],-$award,7,3,'订单'.$order_info['order_sn'].'分佣'.$log.',店铺积分减少', $order_info);

            $return['status'] = 1;
        }elseif($unit == 2 && $award){
            account_change($send_id,$award,8,15,$msg.'，将赠推荐人('.idtoname($send_id,'Member','username;nickname').')，佣金：'.$award);
            $log=$msg."将赠推荐人".$username."，佣金：".$award;
            affiliate_log($order_id,0,$send_id,$award,0,$log,1);
            //门店扣余额
            shop_balance_log($order_info['shop_id'],-$award,1,3,'订单'.$order_info['order_sn'].'分佣,店铺积分减少', $order_info);

            $return['status'] = 1;
        }
    }
    return $return;
}
/**
 * 可向仓库订货的商品
 * @param int $area_id 地区id
 * @return $goodsid 可购买商品id
 */
function library_goods($area_id){}
/**
 * 判断该仓库是否配送该地区
 * @param int $area_id 地区id
 * @return $id_array 满足配货的仓库id
 */
function get_area_stid($area_id=0){
    $smap=array();
    $id_array=array();
    $smap['is_country'] = 0;
    $storage=M("Storage")->where($smap)->getField('id,area_id',true);//查询符合该店铺配货区 的仓库
    foreach($storage as $k=>$v){
        $varr=explode(',',$v);
        if(in_array($area_id,$varr)){
            $id_array[0]=$k;
            return $id_array;
        }
        $alldata = array();
        if($v){
            $map=array();
            $map['status']=1;
            $map['id']= array('in', $v);
            $area_info=M('Area')->where($map)->field('id,pid,name')->cache(true)->select();
            foreach ($area_info as $ka => $va) {
                $areadata = getallson($va['id'],'Area');
                foreach($areadata as $key=>$val){
                    array_push($alldata,$val);
                }
            }
            if(in_array($area_id, $alldata)){
                array_push($id_array,$k);
            }
        }
    }
    return $id_array;
}
/* 得到所有门店 */
function getShops(){
	$map=array();
	$map['status'] = 1;
	// $map['shop_type'] = 1;
	$shopsData = M('Shops')->where($map)->field('id,name')->select();
	return $shopsData;
}
function xmlToArray($xml){
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}
/**
 * 得到开启的所有物流
 */
function is_distribute(){
    $class=M('Distribute')->where('status=1')->cache(true)->order('id desc')->getField("code",true);
    return $class;
}
/**
 * 发送及时通讯消息
 * @param $mobile 接收消息的电话可以是数组,字符串, 带[,]分开的字符串
 * @param $mag 消息 类型,主体内容,其它
 */
function sendIm($mobile,$msg=''){
    if(empty($mobile))return false;
    if(!is_array($mobile))$mobile=explode(',',$mobile);
    $jmessage= new \Common\Vendor\JMessage;
    foreach ($mobile as $key => $value) {
        $jmessage->sendText($value,$msg);
    }return true;
}

function save_member_header_img($id){
    $return['status']=3;
    if(!$id){$return['msg']="会员id不存在";return $return;}
    $map=array();
    $map['id']=$id;
    $map['status']=1;
    $member_info = M('Member')->where($map)->field('id,username,header_img,nickname,mobile')->find();

    if (empty($member_info)) {
        $return['status']=2;
        $return['msg']="会员不存在";
        return $return;
    }
    if(empty($member_info['header_img'])) {
        $return['status']=2;
        $return['msg']="会员头像不存在";
        return $return;
    }
    $old_header_img="/uploads/image/qrcode/cache/header_img_".$id.".jpg";
    $old_f="/uploads/image/qrcode/header_img_".$id."_1.jpg";//生成之后的图
    if(file_exists(ROOT_PATH.$old_f)){
        $return['status']=1;
        $return['msg']="头像已存在";
        $return['url']=$old_f;
        return $return;
    }
    $yuan_img = format_url($member_info['header_img'],2);
    if(!file_exists(ROOT_PATH.$old_header_img))copy($yuan_img,ROOT_PATH.$old_header_img);
    if(!file_exists(ROOT_PATH.$old_header_img)){
        $return['msg']="生成图片失败，请重试！(000)";
        return $return;
    }
    if(file_exists(ROOT_PATH.$old_header_img)){unlink(ROOT_PATH.$old_f);}
    rename(ROOT_PATH.$old_header_img,ROOT_PATH.$old_f);
    if(file_exists(ROOT_PATH.$old_f)){
        // 生成成功，添加记录
        $return['status']=1;
        $return['url']=$old_f;
        $return['msg']="生成成功！";
        return $return;
    }else{
        $return['msg']="生成图片失败，请重试！(002)";
        return $return;
    }
}

/**
  * 推广海报
  * @param $id 会员 $is_check 是否检测 1不检测 2检测
  * @return mixed
  */
function tgercode($id,$is_check=1,$poster_id=''){
    $id=intval($id);
    $return =array('status'=>0,'msg'=>'');
    if(empty($id)){
        $return['msg']="参数错误!";
        return $return;
    }
    $map=array();
    $map['id']=$id;
    $map['status']=1;
    $invite_key = base64_encode($id);
    if($poster_id==2){
        $member_info = M('LittleShop')->where($map)->field('logo,tuan_name')->find();
        $member_info['header_img'] = $member_info['logo'];
        $member_info['nickname'] = $member_info['tuan_name']; 
        $path="/pages/tuanzhang/register/register?invite_key=".$invite_key;
        $path_type = 1;
    }else{
        $member_info = M('Member')->where($map)->field('id,username,header_img,nickname,wxid')->find();
        $path="/pages/index/index?invite_key=".$invite_key;
        $path_type='';
    }
    if (empty($member_info)) {
        $return['msg']="会员不存在";
        return $return;
    }
    
    if(empty($poster_id))$poster_id=C('POSTER_LIST_ID');
    $poster_conf=array();
    if($poster_id){
        $attr_data = require_once ROOT_PATH."/Public/data/poster_data.php";
        if(!empty($attr_data[$poster_id])){
            $poster_conf=$attr_data[$poster_id];
        }
    }
    $poster_key = md5(serialize($poster_conf));
   
    $old_f="/uploads/image/qrcode/haibao_".$poster_key.$id.".jpg";//生成之后的图
    if($is_check==1 && file_exists(ROOT_PATH.$old_f)){
       $return['status']=1;
       $return['url']=format_url($old_f,1);
       return $return;
    }
    //头像、昵称和二维码的坐标
    // $ewm_xy = '215,59|222,250|230,296';
    $ewm_xy =!empty($poster_conf['param'])?$poster_conf['param']:C('COORDINATE');
    $size=!empty($poster_conf['font_size'])?$poster_conf['font_size']:20;
    $size = 20;
    $xyy = array();
    $xy = explode('|',$ewm_xy);
    foreach($xy as $it){$xyy[] = explode(',',$it);}
    unset($xy,$ewm_xy);//原图背景、
    $yuan_img = !empty($poster_conf['background'])?$poster_conf['background']:C('BOTTOM_IMG');if(empty($yuan_img))return false;
    $linshiimg="/uploads/image/qrcode/cache/linshi_".$id.".jpg";//临时图片
    $yuan_img = format_url($yuan_img,2);
    if(!file_exists(ROOT_PATH.$linshiimg))copy($yuan_img,ROOT_PATH.$linshiimg);
    if(!file_exists(ROOT_PATH.$linshiimg)){
         $return['msg']="生成图片失败，请重试！(000)";
         return $return;
    }
    $old_cache_f='';
    //生成微信推广二维码
    $sp =!empty($poster_conf['permanent'])?$poster_conf['permanent']: intval(C('PERMANENT'));if(empty($sp))$sp=0;
    $erwei =!empty($poster_conf['erweima'])?$poster_conf['erweima']: intval(C('ERWEIMA'));if(empty($erwei))$erwei=150;
    // if(C('WX_TYPE')==4){
        // $weixin = new \Common\Vendor\WeixinChat;
        // if(empty($access_token))$access_token=$weixin->getdd();
        // if($sp==0){
        //   $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        // }else{
        //   $data = '{"expire_seconds": 604800,"action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        // }
        // $rt=curlget('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token,$data,"POST",array(),true);
        // $json=json_decode($rt);
        // $ticket = $json->ticket;
        // if($ticket){
        //     $str = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket); 
        //     $img = curlget($str);
        //     $old_cache_f= ROOT_PATH."/uploads/image/qrcode/cache/qrcode_".$id.".jpg";//微信临时头像
        //     if(!empty($img)){@file_put_contents($old_cache_f,$img);}
        // }
        $old_cache_f= ROOT_PATH."/uploads/image/qrcode/cache/qrcode_".md5($path).".jpg";
        if(!file_exists($old_cache_f)){
          $param=array();
          $param['path'] =$path;
          $param['type'] = $path_type;
          $wxsmall = new \Common\Vendor\Wxsmallopen($param);
          $result=$wxsmall->get_location_small_code($param);
          preg_match('/(.*)base64,(.*)/', $result, $matches);//print_r($matches);exit;
          $base64 = $matches['2'];
          $img = base64_decode($base64);
          if(!empty($img)){@file_put_contents($old_cache_f,$img);}
          else{
            $return['msg']="网络不给力,请稍后再试";
            return $return; 
          }
        }
        // print_r($old_cache_f);exit;
    // }else{
    //     $url = U('Mobile/Login/register',array('eid'=>$id),true,true);
    //     $old_cache_f = phpgrcode(urlencode($url),'',10,'wximg_'.$id);//二维码 缓存生成之后的图
    // }    
    $haibao= new \Common\Vendor\Haibao;
    $codeparams=array();//二维码写入到背景图片中
    $codeparams[]=array('path_logo'=>format_url($old_cache_f),'dst_x'=>$xyy[2][0],'dst_y'=>$xyy[2][1],'imgWidth'=>$erwei,'imgHeight'=>$erwei);
    $touxiang =!empty($poster_conf['touxiang'])?$poster_conf['touxiang']:intval(C('TOUXIANG'));if(empty($touxiang))$touxiang=150;
    if($member_info['header_img']){
      if(str_exists($member_info['header_img'],'http')){
            $header_type=getwebimageinfo($member_info['header_img']);
            $w_img= ROOT_PATH."/uploads/image/qrcode/cache/header_".$id.".".$header_type;//微信临时头像
            if(!file_exists($w_img)){
                file_put_contents($w_img,file_get_contents($member_info['header_img']));
            }
      }else{
            $w_img = $member_info['header_img'];//头像写入到背景图片中
      }
      $codeparams[]=array('path_logo'=>format_url($w_img),'dst_x'=>$xyy[0][0],'dst_y'=>$xyy[0][1],'imgWidth'=>$touxiang,'imgHeight'=>$touxiang);
    }    
    if($codeparams)$haibao->addPics(ROOT_PATH.$linshiimg,$codeparams);    
    $nickname=!empty($member_info['nickname'])?$member_info['nickname']:$member_info['username'];
    $nickname=trim($nickname);
    $encode = mb_detect_encoding($nickname,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
    if ($encode != "UTF-8"){$nickname = iconv($encode,"UTF-8",$nickname);}
    if($xyy[1][0]=='center'){
         $length= $haibao->checkStrlength($nickname,$size);
         $imgwidth=$xyy[1][2]?$xyy[1][2]:827;
         $xyy[1][0]= floor(($imgwidth - $length)/2);   
    }
    if($haibao->addWord(ROOT_PATH.$linshiimg,$nickname,$xyy[1][0],$xyy[1][1],$size,'white')){//写入昵称到背景图片中
        rename(ROOT_PATH.$linshiimg,ROOT_PATH.$old_f);
        if(file_exists(ROOT_PATH.$old_f)){
            $return['status']=1;
            $return['url']=format_url($old_f,1);
            return $return;
        }else{
            $return['msg']="生成图片失败，请重试！(002)";
            return $return;
        }
    }else{  
        $return['msg']="生成图片失败，请重试！(003)";
        return $return;
    } 
}
/**
  * 推广海报
  * @param $id 会员 $is_check 是否检测 1不检测 2检测
  * @return mixed
  */
function old_tgercode($id,$is_check=1,$poster_id='',$is_type=0){
    $id=intval($id);
    $return =array('status'=>0,'msg'=>'');
    if(empty($id)){
        $return['msg']="参数错误!";
        return $return;
    }
    $map=array();
    $map['id']=$id;
    $map['status']=1;
    $member_info = M('Member')->where($map)->field('id,username,header_img,nickname,wxid,recom_code')->find();
    if (empty($member_info)) {
        $return['msg']="会员不存在";
        return $return;
    }
    $old_f="/uploads/image/qrcode/haibao_".$id.".jpg";
    if($is_type==1)$old_f="/uploads/image/qrcode/small_haibao_".$id.".jpg";//生成之后的图
    if($is_check==1 && file_exists(ROOT_PATH.$old_f) && $is_type!=1){
       $return['status']=1;
       $return['url']=format_url($old_f,1);
       return $return;
    }
    if(empty($poster_id))$poster_id=C('POSTER_LIST_ID');
    $poster_conf=array();
    if($poster_id){
        $attr_data = require_once ROOT_PATH."/Public/data/poster_data.php";
        if(!empty($attr_data[$poster_id])){
            $poster_conf=$attr_data[$poster_id];
        }
    }
    //头像、昵称和二维码的坐标
    // $ewm_xy = '215,59|222,250|230,296';
    $ewm_xy =!empty($poster_conf['param'])?$poster_conf['param']:C('COORDINATE');
    $size=!empty($poster_conf['font_size'])?$poster_conf['font_size']:20;
    $xyy = array();
    $xy = explode('|',$ewm_xy);
    foreach($xy as $it){$xyy[] = explode(',',$it);}
    unset($xy,$ewm_xy);//原图背景、
    $yuan_img = !empty($poster_conf['background'])?$poster_conf['background']:C('BOTTOM_IMG');if(empty($yuan_img))return false;
    $linshiimg="/uploads/image/qrcode/cache/linshi_".$id.".jpg";//临时图片
    $yuan_img = format_url($yuan_img,2);
    if(!file_exists(ROOT_PATH.$linshiimg))copy($yuan_img,ROOT_PATH.$linshiimg);
    if(!file_exists(ROOT_PATH.$linshiimg)){
         $return['msg']="生成图片失败，请重试！(000)";
         return $return;
    }
    $old_cache_f='';
    //生成微信推广二维码
    $sp =!empty($poster_conf['permanent'])?$poster_conf['permanent']: intval(C('PERMANENT'));if(empty($sp))$sp=0;
    $erwei =!empty($poster_conf['erweima'])?$poster_conf['erweima']: intval(C('ERWEIMA'));if(empty($erwei))$erwei=150;
    if(C('WX_TYPE')==4){
        $weixin = new \Common\Vendor\WeixinChat;
        if(empty($access_token))$access_token=$weixin->getdd();
        if($sp==0){
          $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        }else{
          $data = '{"expire_seconds": 604800,"action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        }
        $rt=curlget('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token,$data,"POST",array(),true);
        $json=json_decode($rt);
        $ticket = $json->ticket;
        if($ticket){
            $str = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);	
            $img = curlget($str);
            $old_cache_f= ROOT_PATH."/uploads/image/qrcode/cache/header_".$id.".jpg";//微信临时头像
            if(!empty($img)){@file_put_contents($old_cache_f,$img);}
			
        }
    }else{
        $url = U('Mobile/Login/register',array('eid'=>$id),true,true);
        $old_cache_f = phpgrcode(urlencode($url),'',10,'wximg_'.$id);//二维码 缓存生成之后的图
    }
    if($is_type==1){
        $invite_key = base64_encode($id);
        $param=array();$param['width']=120;
        $param['type']=1;
        $param['path'] = "pages/index/index?invite_key=".$invite_key."&uid=".$id."&eid=".$id;//小程序参数
        $wxsmall = new \Common\Vendor\Wxsmallopen;
        $result=$wxsmall->get_location_small_code($param);
        preg_match('/(.*)base64,(.*)/', $result, $matches);
        $base64 = $matches['2'];
        $img = base64_decode($base64);
        $old_cache_f= ROOT_PATH."/uploads/".date("YmdHis")."wx_img.jpg";
        if(!empty($img)){@file_put_contents($old_cache_f,$img);}
    }
    if(empty($old_cache_f) || !file_exists($old_cache_f)){
        $return['msg']="推广二维码生成中,请稍后重试!";
        return $return;
    }
    
    $haibao= new \Common\Vendor\Haibao;
    $codeparams=array();//二维码写入到背景图片中
   // $codeparams[]=array('path_logo'=>format_url($old_cache_f),'dst_x'=>$xyy[3][0],'dst_y'=>$xyy[3][1],'imgWidth'=>$erwei,'imgHeight'=>$erwei);
    $codeparams[]=array('path_logo'=>format_url($old_cache_f),'dst_x'=>$xyy[2][0],'dst_y'=>$xyy[2][1],'imgWidth'=>$erwei,'imgHeight'=>$erwei);


    $touxiang =!empty($poster_conf['touxiang'])?$poster_conf['touxiang']:intval(C('TOUXIANG'));if(empty($touxiang))$touxiang=150;
    if($member_info['header_img']){//头像写入到背景图片中
      $w_img = $member_info['header_img'];
      $codeparams[]=array('path_logo'=>format_url($w_img),'dst_x'=>$xyy[0][0],'dst_y'=>$xyy[0][1],'imgWidth'=>$touxiang,'imgHeight'=>$touxiang);
    }
    if($codeparams)$haibao->addPics(ROOT_PATH.$linshiimg,$codeparams);
    $nickname=!empty($member_info['nickname'])?$member_info['nickname']:$member_info['username'];
    $nickname=trim($nickname);
    $encode = mb_detect_encoding($nickname,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
    if ($encode != "UTF-8"){$nickname = iconv($encode,"UTF-8",$nickname);}
    if($xyy[1][0]=='center'){
         $length= $haibao->checkStrlength($nickname,$size);
         $imgwidth=$xyy[1][2]?$xyy[1][2]:827;
         $xyy[1][0]= floor(($imgwidth - $length)/2);   
    }
    $recom_code=!empty($member_info['recom_code'])?$member_info['recom_code']:$member_info['recom_code'];
    $recom_code=trim($recom_code);
    $encodes = mb_detect_encoding($recom_code,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
    if ($encodes != "UTF-8"){$recom_code = iconv($encodes,"UTF-8",$recom_code);}
    if($xyy[2][0]=='center'){
         $length= $haibao->checkStrlength($recom_code,$size);
         $imgwidth=$xyy[2][2]?$xyy[2][2]:827;
         $xyy[2][0]= floor(($imgwidth - $length)/2);   
    }
    
    $params[]=array('str'=>$nickname,'posX'=>$xyy[1][0],'poxY'=>$xyy[1][1],'size'=>28,'color'=>'white');
    //  $xyy[3][0]  $xyy[2][0]
    $params[]=array('str'=>$recom_code,'posX'=>$xyy[3][0],'poxY'=>$xyy[3][1],'size'=>20,'color'=>'white');
    
    if($haibao->addWords(ROOT_PATH.$linshiimg,$params)){//写入昵称到背景图片中
        rename(ROOT_PATH.$linshiimg,ROOT_PATH.$old_f);
        if(file_exists(ROOT_PATH.$old_f)){
            //if($sp>0 && $old_cache_f) unlink($old_cache_f);
            $return['status']=1;
            $return['url']=$old_f;
            return $return;
        }else{
            $return['msg']="生成图片失败，请重试！(002)";
            return $return;
        }
    }else{  
        $return['msg']="生成图片失败，请重试！(003)";
        return $return;
    } 
}
/**
  * 推广海报
  * @param $id 会员 $is_check 是否检测 1不检测 2检测
  * @return mixed
  */
function tger_code($id,$is_check=1,$poster_id=''){
    $id=intval($id);
    $return =array('status'=>0,'msg'=>'');
    if(empty($id)){
        $return['msg']="参数错误!";
        return $return;
    }
    $map=array();
    $map['id']=$id;
    $map['status']=1;
    $member_info = M('Member')->where($map)->field('id,username,header_img,nickname,wxid,recom_code')->find();
    if (empty($member_info)) {
        $return['msg']="会员不存在";
        return $return;
    }
    $old_f="/uploads/image/qrcode/haibao_".$id.".jpg";//生成之后的图
    if($is_check==1 && file_exists(ROOT_PATH.$old_f)){
       $return['status']=1;
       $return['url']=format_url($old_f,1);
       return $return;
    }
    if(empty($poster_id))$poster_id=C('POSTER_LIST_ID');
    $poster_conf=array();
    if($poster_id){
        $attr_data = require_once ROOT_PATH."/Public/data/poster_data.php";
        if(!empty($attr_data[$poster_id])){
            $poster_conf=$attr_data[$poster_id];
        }
    }

    //头像、昵称和二维码的坐标
    // $ewm_xy = '215,59|222,250|230,296';
    $ewm_xy =!empty($poster_conf['param'])?$poster_conf['param']:C('COORDINATE');
    $size=!empty($poster_conf['font_size'])?$poster_conf['font_size']:20;
    $xyy = array();
    $xy = explode('|',$ewm_xy);
    foreach($xy as $it){$xyy[] = explode(',',$it);}
    unset($xy,$ewm_xy);//原图背景、
    $yuan_img = !empty($poster_conf['background'])?$poster_conf['background']:C('BOTTOM_IMG');if(empty($yuan_img))return false;
    $linshiimg="/uploads/image/qrcode/cache/linshi_".$id.".jpg";//临时图片
    $yuan_img = format_url($yuan_img,2);
    if(!file_exists(ROOT_PATH.$linshiimg))copy($yuan_img,ROOT_PATH.$linshiimg);
    if(!file_exists(ROOT_PATH.$linshiimg)){
         $return['msg']="生成图片失败，请重试！(000)";
         return $return;
    }
    $old_cache_f='';
    //生成微信推广二维码
    $sp =!empty($poster_conf['permanent'])?$poster_conf['permanent']: intval(C('PERMANENT'));if(empty($sp))$sp=0;
    $erwei =!empty($poster_conf['erweima'])?$poster_conf['erweima']: intval(C('ERWEIMA'));if(empty($erwei))$erwei=150;
    if(C('WX_TYPE')==4){
        $weixin = new \Common\Vendor\WeixinChat;
        if(empty($access_token))$access_token=$weixin->getdd();
        if($sp==0){
          $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        }else{
          $data = '{"expire_seconds": 604800,"action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        }
        $rt=curlget('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token,$data,"POST",array(),true);
        
        $json=json_decode($rt);
        $ticket = $json->ticket;        
        if($ticket){
            $str = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket); 
            $img = curlget($str);
            $old_cache_f= ROOT_PATH."/uploads/image/qrcode/cache/header_".$id.".jpg";//微信临时头像
            if(!empty($img)){@file_put_contents($old_cache_f,$img);}
            
        }
    }else{
        $url = U('Mobile/Login/register',array('eid'=>$id),true,true);
        $old_cache_f = phpgrcode(urlencode($url),'',10,'wximg_'.$id);//二维码 缓存生成之后的图
    }
    if(empty($old_cache_f) || !file_exists($old_cache_f)){
        $return['msg']="推广二维码生成中,请稍后重试!";
        return $return;
    }
    
    $haibao= new \Common\Vendor\Haibao;
    $codeparams=array();//二维码写入到背景图片中
    $codeparams[]=array('path_logo'=>format_url($old_cache_f),'dst_x'=>$xyy[3][0],'dst_y'=>$xyy[3][1],'imgWidth'=>$erwei,'imgHeight'=>$erwei);
    
    $touxiang =!empty($poster_conf['touxiang'])?$poster_conf['touxiang']:intval(C('TOUXIANG'));if(empty($touxiang))$touxiang=150;
    if($member_info['header_img']){//头像写入到背景图片中
      $w_img = $member_info['header_img'];
      $codeparams[]=array('path_logo'=>format_url($w_img),'dst_x'=>$xyy[0][0],'dst_y'=>$xyy[0][1],'imgWidth'=>$touxiang,'imgHeight'=>$touxiang);
    }
    if($codeparams)$haibao->addPics(ROOT_PATH.$linshiimg,$codeparams);
    $nickname=!empty($member_info['nickname'])?$member_info['nickname']:$member_info['username'];
    $nickname=trim($nickname);
    $encode = mb_detect_encoding($nickname,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
    if ($encode != "UTF-8"){$nickname = iconv($encode,"UTF-8",$nickname);}
    if($xyy[1][0]=='center'){
         $length= $haibao->checkStrlength($nickname,$size);
         $imgwidth=$xyy[1][2]?$xyy[1][2]:827;
         $xyy[1][0]= floor(($imgwidth - $length)/2);   
    }
    $recom_code=!empty($member_info['recom_code'])?$member_info['recom_code']:$member_info['recom_code'];
    $recom_code=trim($recom_code);
    $encodes = mb_detect_encoding($recom_code,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
    if ($encodes != "UTF-8"){$recom_code = iconv($encodes,"UTF-8",$recom_code);}
    if($xyy[2][0]=='center'){
         $length= checkStrlength($recom_code,$size);
         $imgwidth=$xyy[2][2]?$xyy[2][2]:827;
         $xyy[2][0]= floor(($imgwidth - $length)/2);   
    }
    
    $params[]=array('str'=>$nickname,'posX'=>$xyy[1][0],'poxY'=>$xyy[1][1],'size'=>28,'color'=>'white');
    $params[]=array('str'=>$recom_code,'posX'=>$xyy[2][0],'poxY'=>$xyy[2][1],'size'=>20,'color'=>'white');
    
    if($haibao->addWords(ROOT_PATH.$linshiimg,$params)){//写入昵称到背景图片中
        rename(ROOT_PATH.$linshiimg,ROOT_PATH.$old_f);
        if(file_exists(ROOT_PATH.$old_f)){
            //if($sp>0 && $old_cache_f) unlink($old_cache_f);
            $return['status']=1;
            $return['url']=$old_f;
            return $return;
        }else{
            $return['msg']="生成图片失败，请重试！(002)";
            return $return;
        }
    }else{  
        $return['msg']="生成图片失败，请重试！(003)";
        return $return;
    } 
}
/**
    *打印外卖小票
    * @param varchar  $machine_code 打印终端标识
      * @param text $content  打印模板
      * @param varchar $order_sn  订单号
    */
function doPrint($machine_code,$content,$order_sn){
    $return=array('status'=>0,'info'=>'');
    if(empty($machine_code)){$return['info']="打印标识为空,参数错误！";return $return;}
    if(empty($content)){$return['info']="打印模板为空,参数错误！";return $return;}
    if(empty($order_sn)){$return['info']="订单号为空,参数错误！";return $return;}    
    $print= new \Common\Vendor\ylyApi;
    $return= $print->doPrint($machine_code,$content,$order_sn);//打印
    return $return;
}
//处理打印模板
function del_print_template($order_sn){
    if(empty($order_sn)){
        $return['status']=0;
        $return['info']="订单号为空,参数错误！";
    }else{
        $map=array();
        $map['order_sn']=$order_sn;
        $map['pay_status']=3;
        $map['status']=3;
        $map['is_delete']=0;
        $map['type']= array('in','13,14');
        $order_info=M('OrderInfo')->where($map)->field(true)->find();
        if(empty($order_info)){
            $return['status']=0;
            $return['info']="没有查询到该订单！";
        }else{
            /*模板里的数据开始*/
            $order_info['shop_name']=idtoname($order_info['shop_id'],'Shops','name','id',false);
            $order_info['cashier']=idtoname($order_info['sa_id'],'ShopsAccount','name','id',false);
            $order_info['goods_allmoney']=format_price($order_info['goods_allmoney']);
            $order_info['order_amount']=format_price($order_info['order_amount']);
            $order_info['discount']=format_price($order_info['discount']);
            $order_info['used_score_money']=format_price($order_info['used_score_money']);
            $order_info['addtime']=date('Y-m-d H:i:s',$order_info['addtime']);
            $map=array('order_id'=>$order_info['id']);
            $order_goods=M('OrderGoods')->where($map)->select();
            if(!empty($order_goods)){
                foreach($order_goods as $k=>$v){
                    $order_goods[$k]['goods_price']=format_price($v['goods_price']);
                    $order_goods[$k]['goods_number']=floatval($v['goods_number']);
                }
            }
            $order_info['order_goods']=$order_goods;
            /*模板里的数据结束*/
            //打印模板
           // if(empty($tplhtml))$tplhtml=C('PRINT_TEMPLATE');
            $tplhtml=trim(htmlspecialchars_decode($tplhtml));
            if(empty($tplhtml)){
                $return['status']=0;
                $return['info']="打印模板为空,参数错误！";
            }else{
                $WEB_SITE_NAME=C('WEB_SITE_NAME');//网站名称
                $View= new \Common\Vendor\TplView();
                $View->assign('time',time_format(NOW_TIME));
                $View->assign($order_info);
                $View->assign('WEB_SITE_NAME',$WEB_SITE_NAME);
                $content=$View->fetch('',$tplhtml);
                $return['status']=1;
                $return['content']=$content;
            }
        }
    }
    return $return;
}
/**
 * 台卡
 * @param $id 门店id
 * @param $is_check 检测是否存在 如存在直接返回
 * @return mixed
 */
function deccacode($id,$is_check=1){
    $id=intval($id);
    $site_id=C('appid');//站点ID
    $return =array('status'=>0,'msg'=>'');
    if(empty($id)){
        $return['msg']="参数错误!";
        return $return;
    }
    $map=array();
    $map['id']=$id;
    $map['status']=1;
    $shops_info = M('Shops')->where($map)->field('id,name,thumb,decca_img,thumb_img')->find();
    if (empty($shops_info)) {
        $return['msg']="仓库不存在";
        return $return;
    }elseif($shops_info['decca_img'] && $is_check==1){
        $return['status']=1;
        $return['url']=format_url($shops_info['decca_img'],1);
        return $return;
    }
    //logo、二维码的坐标
    //原图背景、
    $x=240;$y=505;
    $yuan_img = '/uploads/image/qrcode/yl.jpg';
    $linshiimg="/uploads/image/qrcode/cache/linshi_".$id.NOW_TIME.".jpg";//临时图片
    if(!file_exists(ROOT_PATH.$linshiimg))copy(ROOT_PATH.$yuan_img,ROOT_PATH.$linshiimg);
    if(!file_exists(ROOT_PATH.$linshiimg)){
        $return['msg']="生成图片失败，请重试！(000)";
        return $return;
    }
    //生成台卡二维码
    $sp = intval(C('PERMANENT'));if(empty($sp))$sp=0;//永久临时二维码
    
    
    $p_map=array();
    $p_map['status']=1;
    $p_map['code']='chinaums';
    $payconfig=M('Payment')->where($p_map)->field('config_account')->find();
    if(empty($payconfig) || empty($payconfig['config_account'])){$return['msg']="支付通道未开通！请联系客服开通.";return $return;}
    $yinlian=creat_code($id);$url=$yinlian['url'];
    $old_cache_f='';
    $logo=$shops_info['thumb']?$shops_info['thumb']:$shops_info['thumb_img'];
	if(!$logo)$logo = "/Public/images/dlogo.png";
    $logo=format_url($logo,1);
    $old_cache_f = phpgrcode(urlencode($url),'M','20','decca_'.$site_id.'_'.$id,$logo);//生成之后的图
    $old_cache_f= format_url($old_cache_f,2);
    $haibao= new \Common\Vendor\Haibao;    
    $t =$haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y);//二维码写入到背景图片中    
    
    $cachetype=C('DATA_CACHE_TYPE');if(empty($cachetype))$cachetype='File';
    if($cachetype!='File'){
        $url_img =format_url($linshiimg,2);
        $image=array(
            'name'=>"shop_chinaums_".$id.".png",
            'type'=>'image/png',
            'tmp_name'=>$url_img,
            'error'=>'0',
            'size'=>filesize($url_img),
            'oss'=>1
        );
        $res=uploadimg($image);
    }else{
        $res=array('status'=>1,'info'=>$linshiimg);
    }    
    if($t&&$res['status']==1){
        $return['status']=1;
        $data['decca_img']=$res['info'];
        $return['url']=$res['info'];
        $shops_info = M('Shops')->where($map)->save($data);
	    unlink($old_cache_f);
        if($cachetype!='File'){unlink(ROOT_PATH.$linshiimg);}
        return $return;
    }else{
        $return['msg']="生成图片失败，请重试！(002)";
        return $return;
    }
}
  /**
   * 上传图片到附件服务器
   * @param $file 图片路径
   * @param $dir 目录
   */
  function uploadimg($file,$dir='image'){
       $return=array('status'=>0,'info'=>'');
       if(empty($file)){$return['info']='图片不存在';return $return;}
       //上传配置
       $ext_arr = array(
           'image' => explode(',', C('UPLOAD_IMGEXTS')),
            'flash' => array('swf', 'flv'),
            'media' => array('swf','flv','mp3','wav','wma','wmv','mid','avi','mpg','asf','rm','rmvb'),
            'file' => explode(',', C('UPLOAD_EXTS')),
            );
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = C('UPLOAD_MAXSIZE') * 1024 * 1024; // 设置附件上传大小
        $upload->exts = $ext_arr[$dir]; // 设置附件上传类型
        $upload->subName = array('date', 'Ymd');
        $upload->rootPath = C('UPLOAD_PATH');
        $upload->savePath = $dir . '/';
        $info = $upload->uploadOne($file);
        if ($info) {
            $return['status'] =1; 
            $return['info'] =str_exists($info['filename'],'http')?$info['filename']: __ROOT__.'/'.ltrim($info['filename'],'/');
        } else {
            $return['info'] = $upload->getError();
        }
        return $return;
  }
  function curlinit($url,$post){
    $ch = curl_init();
    //2.设置URL和相应的选项
    curl_setopt($ch, CURLOPT_URL, $url);
    //启用时会将头文件的信息作为数据流输出。        
    curl_setopt($ch, CURLOPT_HEADER, false);
    //将curl_exec()获取的信息以字符串返回，而不是直接输出。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);  
    //FALSE 禁止 cURL 验证对等证书（peer's certificate）。    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);      
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  //验证主机 
     //发送 POST 请求    
    curl_setopt($ch, CURLOPT_POST, true);     
    //全部数据使用HTTP协议中的 "POST" 操作来发送。          
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    //3.抓取URL并把它传递给浏览器    
    $content = curl_exec($ch); 
    //4.关闭cURL资源，并且释放系统资源    
    curl_close($ch); 
    $res = json_decode($content,true);
    return $res;
  }
/**
 * 验证应用权限
 */
function check_use_auth($use_code,$type=0){
    $return = array('status' => 1, 'msg' => '', 'url' => '');return $return;
}
/**
 * 获取认证的支付方式
 */
function check_re_pay(){
    $site_id=C('appid');
    if(empty($site_id)) return false;
    $map=array();
    $map['site_id']=$site_id;
    $map['status']=1;
    $c_type=M('SiteInfo')->where($map)->getField('c_type');
    if(empty($c_type))$c_type=3;
    return $c_type;
}
/**
 * 银联接口生成台卡二维码
 * @return array
 */
function creat_code($shop_id){
    $return=array('status'=>0,'msg'=>'');
    $pay_code=ucfirst(strtolower('chinaums'));//转化支付方式code为首字母大写其他小写
    $p_map=array();
    $p_map['status']=1;
    $p_map['code']=$pay_code;
    $payconfig=M('Payment')->where($p_map)->field(true)->find();
    if(empty($payconfig)){$return['msg']='参数设置有误！'; return $return;}
    $payconfig['memberId']=$shop_id;
    $payconfig['is_decca']=1;
    $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
    $vo = new \Common\Vendor\Pay\PayVo();
    $vo->setParam($payconfig);
    $RequestForm=$pay->buildRequestForm($vo);
    if($RequestForm['status']){
        $return['status']=1;
        $return['url']=$RequestForm['url'];
        return $return;
    }else{
        return $RequestForm;
    }
}
/**
   *导购员提成
   * @param $order_id 订单id
   * @param $status 1销售提成 2充值提成 3计次套餐提成 4礼品卡提成
   */
function guide_divide($order_id,$status){
    $map = array();
    $map['id'] = $order_id;
    $order_info = M('OrderInfo')->where($map)->field('uid,guide,order_sn,order_amount,shop_id')->find();
    $res_guide=array();
    if($order_info['shop_id']){
        $res_guide=$guide=M('Shops')->where('id='.$order_info['shop_id'])->cache(true)->getField('guide');
    }
    if(empty($res_guide)){
        $res = M('Config')->field('value')->where("name='GUIDE'")->cache(true)->find();$res_guide=$res['value'];
    }
    $affiliate = unserialize($res_guide);
    if(empty($affiliate))return false;
    $is_guishu=false;//是否为按归属提成
    $guide='';//归属导购
    if($affiliate['market_way']==1 && $order_info['uid'] && ($affiliate['no_way']==1 || $affiliate['guoshu_rate']>0)){
        $guide=idtoname($order_info['uid'],'Member','guide');
    }    
    if(empty($order_info['guide']) && $affiliate['market_way']==1 && $affiliate['no_way']==1){//无导购按 归属提成
        $is_guishu=true;
        if(empty($guide))return false;
        $order_info['guide']=$guide;        
    }
    if(empty($order_info['guide']))return false;
    if(!$is_guishu && $order_info['guide']==$guide){
        $is_guishu=true;
    }
    
    if($status == 1){//销售提成
        //1113
        $all_money=$all_profit=$all_commission=$fixed=0;//商品金额百分比//利润//固定金额百分比分佣//固定积分或金额时
        $map=array();
        $map['order_id']=$order_id;
        $map['staff_comm']=array('gt',0);
        $order_goods=M('OrderGoods')
            ->where($map)
            ->field('sum(goods_price*goods_number) as all_money,sum(profit) as all_profit,sum(money*goods_number) as all_commission,staff_comm')
            ->select();
        // end
        $all_moneys = $all_profits = $all_commissions = array();
        $money=0;
        foreach ($order_goods as $k => $v) {
            if($v['staff_comm'] == 0){//不提成
                $return['status'] = 1;
                return $return;
            }elseif($v['staff_comm'] == 1){//按系统设定
                $all_money = $v['all_money'];
                $all_profit = $v['all_profit'];
                if($affiliate['market_status'] == 1){//按商品金额%
                    $money += format_decimal($all_money*$affiliate['market']/100);
                }else{//按商品利润%
                    $money += format_decimal($all_profit*$affiliate['market']/100);
                }
            }elseif($v['staff_comm'] == 2){//按固定金额
                $money += $all_profits[$k] = $all_commissions[$k] =  $v['all_commission'];
            }
        }
        $log='';
        if($order_info['uid']){$log.='会员('.show_user_name($order_info['uid']).')';}
        $log.='下单('.$order_info['order_sn'].')，';
    }elseif($status == 2){//充值提成
        $money = format_decimal($order_info['order_amount']*$affiliate['recharge']/100);
        $log='会员('.show_user_name($order_info['uid']).')充值('.$order_info['order_sn'].')，';
    }elseif($status == 3){//计次套餐提成
    }elseif($status == 4){//礼品卡提成
		$log='';
        $money = format_decimal($order_info['order_amount']*$affiliate['prepaid_card']/100);
        if($order_info['uid']){$log.='会员('.show_user_name($order_info['uid']).')';}
        $log.='购买礼品卡('.$order_info['order_sn'].')，';
    }
    if($money){
        if($order_info['guide']>0){
            $map=array();
            $map['id']=$order_id;
            $save=array();
            $save['sales_maid']=format_decimal($money);
            M('OrderInfo')->where($map)->save($save);
        }
        if(!$is_guishu && $guide && $affiliate['market_way']==1 && $affiliate['guoshu_rate']>0){//非归属给归属导购员获取提成
            $guishumoney=$money*$affiliate['guoshu_rate']/100;
            $money=$money-$guishumoney;
            $guide_name=idtoname($guide,'ShopsAccount','name');
            $guishulog=$log.'将归属赠导购员('.$guide_name.')佣金'.$guishumoney.'元';
            if($guishumoney>0)account_change($guide,$guishumoney,1,10,$guishulog,'','',5);
        }
        $guide_name=idtoname($order_info['guide'],'ShopsAccount','name');
        $log.='将赠导购员('.$guide_name.')佣金'.$money.'元';
        if($money>0)account_change($order_info['guide'],$money,1,10,$log,'','',5);
        
    }
    $return['status'] = 1;
  return $return;
}
/**
 * 添加库存变更日志
 * @param int $shop_id 店铺id
 * @param int $order_id 订单id
 * @param $pre_number 更改之前数量
 * @param int $goods_id 商品id
 * @param $number 更改数量
 * @param int $change_type 0加1减
 * @param string $desc 更改库存描述
 * @param $type 1商品销售 2客户退货 3货流进货 4货流调出 5货流出库 6货流退货 7库存盘点 8商品报损 9 编辑库存 10大件拆包 11商品取消订单/退货
 * @param string $attr_key 商品属性id
 * @return bool|mixed
 */
function change_stock_log($shop_id,$order_id,$pre_number,$goods_id,$number,$change_type=0,$desc='',$type,$attr_key=''){
    if(empty($shop_id)  || empty($goods_id) || empty($number) || empty($type)) return false;
    if($number>0 && $change_type==0){
        $data=array();
        $data['change_type']=0;
        $data['change_num']=$number;
        $data['total_num'] = floatval($pre_number)+floatval($number);
    }else{
        $data['change_type']=1;
        $data['change_num']=-$number;
        $data['total_num'] = floatval($pre_number)-floatval($number);
    }
    $data['shop_id'] = $shop_id;
    $data['goods_id'] = $goods_id;
    $data['change_time'] = NOW_TIME;
    $admininfo = session('admin_info');
    $data['admin_id'] = empty($admininfo['id'])?0:$admininfo['id'];
    $data['change_desc'] = '[日志]' . $desc;
    $data['type'] = $type;
    $data['order_id'] = $order_id;
    $data['attr_key'] = empty($attr_key)?'':$attr_key;
    $StockLog=M('StockLog');
    if(!empty($desc)) $insertid = $StockLog->add($data);
    return $insertid;
}
//存session
function save_session(){
    $siteinfo = session('siteinfo');
    if($siteinfo['temp_lng'] && $siteinfo['temp_lat']){
        $x = $siteinfo['temp_lng'];
        $y = $siteinfo['temp_lat'];
    }else{
        return false;
    }
    $ret = D('Wxsmall/Login')->bind_shop_param($x,$y);
    if($ret['status'] == 1){
        session('main_shop_id',$ret['data']['id']);
    }else{
        session('main_shop_id',null);
    }
}
//低版本的array_column
function i_array_column($input, $columnKey, $indexKey=null){
    if(!function_exists('array_column')){ 
        $columnKeyIsNumber  = (is_numeric($columnKey))?true:false; 
        $indexKeyIsNull            = (is_null($indexKey))?true :false; 
        $indexKeyIsNumber     = (is_numeric($indexKey))?true:false; 
        $result                         = array(); 
        foreach((array)$input as $key=>$row){ 
            if($columnKeyIsNumber){ 
                $tmp= array_slice($row, $columnKey, 1); 
                $tmp= (is_array($tmp) && !empty($tmp))?current($tmp):null; 
            }else{ 
                $tmp= isset($row[$columnKey])?$row[$columnKey]:null; 
            } 
            if(!$indexKeyIsNull){ 
                if($indexKeyIsNumber){ 
                  $key = array_slice($row, $indexKey, 1); 
                  $key = (is_array($key) && !empty($key))?current($key):null; 
                  $key = is_null($key)?0:$key; 
                }else{ 
                  $key = isset($row[$indexKey])?$row[$indexKey]:0; 
                } 
            } 
            $result[$key] = $tmp; 
        } 
        return $result; 
    }else{
        return array_column($input, $columnKey, $indexKey);
    }
}
//是否为微信小程序环境
function is_wxsmall(){
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'miniProgram') !== false ) {
        return true;
    }  
    return false;
}
/**小程序的获取店铺id +APP
 * @return int
 */
function get_wxsmall_shop_id(){
    $paramdata=I('param.');
    if(isset($_SERVER['HTTP_X_APPKEY'])&&$paramdata['HCshopid']>0){
        return $paramdata['HCshopid'];
    }
    // zjn --2-21 --
    $AppId=isset($_SERVER['HTTP_X_APICLOUD_APPID'])?$_SERVER['HTTP_X_APICLOUD_APPID']:0;
    $AppKey=isset($_SERVER['HTTP_X_APICLOUD_APPKEY'])?$_SERVER['HTTP_X_APICLOUD_APPKEY']:0;
    if($AppId && $AppKey && $paramdata['HCshopid']>0){
        return $paramdata['HCshopid'];
    }
    // zjn --end--
    $shop_id=session('main_shop_id');
    if($shop_id>0){
        return $shop_id;
    }
    if(empty($shop_id)){
      return $paramdata['shop_id']?$paramdata['shop_id']:0;
    }
    return 0;
}
/**app的获取店铺id
 * @return int
 */
function get_app_shop_id(){
    $paramdata=I('param.');
    $AppId=isset($_SERVER['HTTP_X_APICLOUD_APPID'])?$_SERVER['HTTP_X_APICLOUD_APPID']:0;
    $AppKey=isset($_SERVER['HTTP_X_APICLOUD_APPKEY'])?$_SERVER['HTTP_X_APICLOUD_APPKEY']:0;
    if($AppId && $AppKey && $paramdata['HCshopid']>0){
        return $paramdata['HCshopid'];
    }
    return 0;
}
/**
 * 验证手机号是否存在
 * @param string $mobile 手机号
 * @param string $type 查询类型（1会员 2店铺）
 * @return array
 */
function checkmobile($mobile,$type=1){
	$map = array();
	if($type == 1){
		$map['mobile'] = array('eq',$mobile);
		$id = M('Member')->where($map)->getField('id');
	}elseif($type == 2){
		$map['mobile'] = array('eq',$mobile);
		$id = M('ShopsAccount')->where($map)->getField('id');
	}
	return $id;
}
/**
 * 散货商品编码
 * @param int $str_len 得到编码的长度
 */
function weight_goods_sn($goods_sn,$str_len = 5){
	$cashier_prefix=C("CASHIER_JIZHONGCODE");//计重商品编码前缀
	if($goods_sn && strlen(intval($goods_sn)) == $str_len){
		return intval($goods_sn);
	}
	$map = array();
	$map['is_type'] = 1;//计重商品
	$map['goods_sn'] = array('neq','');
	if($cashier_prefix){
		$map['goods_sn'] = array('like',$cashier_prefix.'%');
	}
	$weight_goods = M('Goods')->where($map)->order('goods_sn desc,id desc')->getField('goods_sn');
	$qz_len = strlen($cashier_prefix);//前缀的长度
	$num_len = $str_len - $qz_len;//要补齐的长度
	if(empty($weight_goods)){
		$weight_goods = $cashier_prefix.str_pad(0, $num_len, 0, STR_PAD_LEFT);
	}
	$num = intval(substr($weight_goods,$qz_len)) + 1;
	$num_sn = str_pad($num, $num_len, 0, STR_PAD_LEFT);
	$weight_goods_sn = $cashier_prefix . $num_sn;
	// echo $weight_goods_sn;exit;
	return $weight_goods_sn;
}
/**
 * 员工工号
 * @param int $str_len 员工工号的长度
 */
function shop_account_sn($login_sn='',$str_len = 6){
	$cashier_prefix=1;//员工工号前缀
	if($login_sn && strlen(intval($login_sn)) == $str_len){
		return intval($login_sn);
	}
	$map = array();
	$map['login_name'] = array('neq','');
	if($cashier_prefix){
		$map['login_name'] = array('like',$cashier_prefix.'%');
	}
	$login_name = M('ShopsAccount')->where($map)->order('login_name desc,id desc')->getField('login_name');
	$qz_len = strlen($cashier_prefix);//前缀的长度
	$num_len = $str_len - $qz_len;//要补齐的长度
	if(empty($login_name)){
		$login_name = $cashier_prefix.str_pad(0, $num_len, 0, STR_PAD_LEFT);
	}
	$num = intval(substr($login_name,$qz_len)) + 1;
	$num_sn = str_pad($num, $num_len, 0, STR_PAD_LEFT);
	$shop_account_sn = $cashier_prefix . $num_sn;
	// echo $shop_account_sn;exit;
	return $shop_account_sn;
}
function show_user_name($uid){
    if(empty($uid))return false;
	return idtoname($uid,'Member','username;nickname;real_name;mobile;id');
}
/**
 * 货流通知极光推送
 * @param $shop_id 订单id
 */
function FrieghtPushSend($shop_id=0){
    if(empty($shop_id))return false;
    $content="您有新的货流通知，请及时处理";
    $paramdata=array('type'=>4,'txt'=>0);    
    $ids=getpushids(2,$shop_id);            
    if(!empty($ids[1]))$result = pushSend($ids[1],$content,'app',1,$paramdata);
    if(!empty($ids[2]))$result = pushSend($ids[2],$content,'app',2,$paramdata);
}
/**
 * 导出格式化数字
 * @param $str 字符串
 */
function format_xml_num($str){
    if (strlen((float)$str) >= 12 && is_numeric((float)$str) && (float)$str && !strpos($str, '.'))$str ="'".(string)$str; return $str;
}
//获取统计代码
function getScript(){
    echo htmlspecialchars_decode(C('STATS_CODE'));
}
/**
 * csv 大数据导出
 * @param $filename 导出保存的文件名
 * @param $tileArray 标题数组
 * @param $dataArray 数据数组
 */
function export_csv($filename='', $tileArray=array(), $dataArray=array()){
    if(!$filename)$filename = date("YmdHis") . ".csv";
    set_time_limit(0);//不限制脚本执行时间以确保导出完成 
    ob_end_clean();ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename=".$filename);
    $fp=fopen('php://output','w');
    fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
    if(!empty($tileArray)){
        fputcsv($fp,$tileArray);
    }
    $index = 0;
    foreach ($dataArray as $item) {
        if($index==1000){
            $index=0;ob_flush();flush();
        }$index++;
        fputcsv($fp,$item);
    }
    ob_flush();flush();ob_end_clean();
}
/**
 * 返回微信二维码(长链接)
 */
function wxqrcode($id,$type=0,$sp=0){
    $return =array('status'=>0,'info'=>'');
    if(empty($id))return;
    $cachecontent=array();
    if($type==1){
        $cachename='wxqrcode'.$id.'-'.$type.'-'.$sp;
        $cachecontent=S($cachename);
        if(!empty($cachecontent['qrcode'])){$return['status']=1;$return['info']=$cachecontent['qrcode'];return $return;}
        if($cachecontent['count']>3){$return['info']= 'access_token time out';return $return;}
    }
    if(empty($cachecontent['qrcodeurl'])){
        $weixin = new \Common\Vendor\WeixinChat;
        if(empty($access_token))$access_token=$weixin->getdd();
        if(empty($access_token)){$return['info']= 'access_token error';return $return;}
        if($sp==0){
            $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        }elseif($sp==1 && is_string($id)){
            $data = '{"expire_seconds": 604800,"action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$id.'"}}}';
        }else{
            $data = '{"expire_seconds": 604800,"action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';
        }
        $rt=curlget('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token,$data,"POST",array(),true);
        $json=json_decode($rt);
        if(empty($json->ticket)){$return['info']= $json->errmsg;return $return;}
        $ticket = $json->ticket;
        $str = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);
        $cachecontent['qrcodeurl']=$str;
    }else{
        $str =$cachecontent['qrcodeurl'];
    }
    if($type==1){
        $result=qrtostr($str);
        if(empty($result)){$weixinopen = new \Common\Vendor\Weixinopen;$result=$weixinopen->get_wxqrcode1($str);}
        if(empty($result))$result='null';
        if(!empty($result) && $result!='null'){$cachecontent['qrcode']=$result;}
        if(empty($cachecontent['count']))$cachecontent['count']=0;
        $cachecontent['count']++;
        S($cachename,$cachecontent,60*60*24);
    }else{
        $result=$str;
    }
    $return['status']=1;
    $return['info']=$result;
    return $return;
}
//二维码识别
function qrtostr($img){
    if(empty($img))return false;
    vendor("QrReader.QrReader");
    $qrcode = new \QrReader($img);
    return $qrcode->text();
}
//微信分享
function wx_share($title='',$description='',$goods_img='',$share_url='',$type=0){
    $cssjs='<script type="text/javascript"> var appId ="",timestamp ="",nonceStr ="",signature = "",title = "",description = "",goods_img_pic = "",share_url = "",wxloadreaday=false;</script>';
    //验证是否是微信打开
    $is_wx=is_weixin();
    if($is_wx==false)return $cssjs;
    //验证是否绑定微信
    $wx = new \Common\Vendor\Jssdk();
    $signPackage = $wx->getSignPackage();
    if(empty($signPackage))return $cssjs;
    if(empty($signPackage["appId"]) || empty($signPackage["timestamp"]) || empty($signPackage["nonceStr"]) || empty($signPackage["signature"]))return $cssjs;
    if(empty($title))$title=C("WEB_SITE_TITLE");
    $qian=array(" ","　","\t","\n","\r");
    if(empty($description))$description=str_replace($qian,'',C("WEB_SITE_DESCRIPTION"));
    if(empty($goods_img))$goods_img=C("WEB_SMALL_LOGO");
    // if(empty($share_url))$share_url=U('Mobile/Index/Index');
    $cssjs='<link rel="stylesheet" type="text/css" href='.__ROOT__.'"/Public/css/share.min.css" />';
    $cssjs.='<script type="text/javascript"> var appId ="'.$signPackage["appId"].'";var timestamp ="'.$signPackage["timestamp"].'";var nonceStr ="'.$signPackage["nonceStr"].'";var signature = "'.$signPackage["signature"].'";var title = "'.$title.'";var description = "'.$description.'";var goods_img_pic = "'.$goods_img.'";var share_url = "'.$share_url.'";</script>';
    $cssjs.='<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>';
    if(empty($type))$cssjs.='<script type="text/javascript" src='.__ROOT__.'"/Public/script/wx_share.js?'.HANCHAO_STATICVERSION.'"></script>';
    return $cssjs;
}
/**
 * 获取商品编码校验拉
 * @param $s 商品编码
 */
function CheckBarCode($s) {
    $length=strlen($s)-1;
    $a = $b = $c = $d = $e = 0;
    for ($i = 1; $i <= $length; $i++) {
        $sc = intval($s[($i - 1)]);
        if ($i <= 12 && $i % 2 == 0) {
            $a += $sc;
        }else if ($i <= 11 && $i % 2 == 1) {
            $b += $sc;
        }
    }
    $c = $a * 3;
    $d = $b + $c;
    if ($d % 10 == 0)  $e = $d - $d;
    else $e = $d + (10 - $d % 10) - $d;
    return $e;
}/**
 * 半角转全角
 * @param string $str
 * @param $type 0半角到全角 1全角到半角
 * @return string
 **/
function SBC_DBC($str, $type=0) {
    $DBC = Array(
        '０' , '１' , '２' , '３' , '４' ,'５' , '６' , '７' , '８' , '９' ,
        'Ａ' , 'Ｂ' , 'Ｃ' , 'Ｄ' , 'Ｅ' ,'Ｆ' , 'Ｇ' , 'Ｈ' , 'Ｉ' , 'Ｊ' ,
        'Ｋ' , 'Ｌ' , 'Ｍ' , 'Ｎ' , 'Ｏ' ,'Ｐ' , 'Ｑ' , 'Ｒ' , 'Ｓ' , 'Ｔ' ,
        'Ｕ' , 'Ｖ' , 'Ｗ' , 'Ｘ' , 'Ｙ' ,'Ｚ' , 'ａ' , 'ｂ' , 'ｃ' , 'ｄ' ,
        'ｅ' , 'ｆ' , 'ｇ' , 'ｈ' , 'ｉ' ,'ｊ' , 'ｋ' , 'ｌ' , 'ｍ' , 'ｎ' ,
        'ｏ' , 'ｐ' , 'ｑ' , 'ｒ' , 'ｓ' ,'ｔ' , 'ｕ' , 'ｖ' , 'ｗ' , 'ｘ' ,
        'ｙ' , 'ｚ' , '－' , '　' , '：' ,'．' , '，' , '／' , '％' , '＃' ,
        '！' , '＠' , '＆' , '（' , '）' ,'＜' , '＞' , '＂' , '＇' , '？' ,
        '［' , '］' , '｛' , '｝' , '＼' ,'｜' , '＋' , '＝' , '＿' , '＾' ,
        '￥' , '￣' , '｀'
    );
    $SBC = Array( // 半角
        '0', '1', '2', '3', '4','5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O','P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y','Z', 'a', 'b', 'c', 'd',
        'e', 'f', 'g', 'h', 'i','j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's','t', 'u', 'v', 'w', 'x',
        'y', 'z', '-', ' ', ':','.', ',', '/', '%', '#',
        '!', '@', '&', '(', ')','<', '>', '"', '\'','?',
        '[', ']', '{', '}', '\\','|', '+', '=', '_', '^',
        '$', '~', '`'
    );
    if ($type) {
        return str_replace($DBC, $SBC, $str); // 全角到半角
    } else {
        return str_replace($SBC, $DBC, $str); // 半角到全角
    }
}
function quweima($str){//转为区位码
    $str=str_replace(' ','',$str);
    $str=SBC_DBC($str);
    $str =iconv('utf-8','gb2312',trim($str));
    $str_qwm = '';
    for($i=0; $i<strlen($str); $i++){
       $str_c=(@ord($str[$i])>0xa0?substr($str, $i++, 2):substr($str, $i, 1));//提字
       $str_qwm_new = @sprintf("%02d%02d",ord($str_c[0])-160,ord($str_c[1])-160);//转为区位码
       if($str_qwm_new)$str_qwm = $str_qwm.$str_qwm_new." ";//重复组合，防止小于4字符，全文索引不认
    }
    $str_qwm =substr($str_qwm,0,-1);
    return str_replace(' ','',$str_qwm);
}
function pinyin_long($zh){//获取整条字符串所有汉字拼音首字母
    if(empty($zh))return false;
    $py = new \Common\Vendor\Py();
    return $py->getFirstLetter($zh);
}
/**
 * 手机号隐藏中间4位(也挂隐藏姓名部分)
 * @param $mobile 手机号
 * @param $start_length起始位
 * @param $replace_length 结束位
 * @param $mark 隐藏替换符
 */
function str_cutmobile($mobile,$start_length=3,$replace_length=4,$mark='****'){
    if(empty($mobile))return $mark;
    if(is_numeric($mobile) && strlen($mobile)==11){
        $str=substr_replace($mobile,$mark,$start_length,$replace_length);
    }else{
        $str= mb_substr($mobile,0,1,'utf-8').$mark;
        if(strlen($mobile)>6){$str.=mb_substr($mobile,-1,1,'utf-8');}
    }
    return $str;
}
/**
 * 拓客海报可选列表
 * @param $type 类型
 */
function poster_list($type=0){
    $attr_data = require_once ROOT_PATH."/Public/data/poster_data.php";
    $poster_list=array();
    $site_info=session('site_info');$appid=C('APPID');
    if($site_info['end_time']<NOW_TIME)$site_info['package']=0;
    
    foreach($attr_data as $k=>$v){
        $v['type']=intval($v['type']);
        if(empty($v['background']) || empty($v['param']) || $v['type']!=$type)continue;
        if(!empty($v['auth_siteid'])){
            $auth_siteid=explode(',',$v['auth_siteid']);
            if(!in_array($appid,$auth_siteid))continue;
        }
        if(!empty($v['auth_package'])){
            $auth_package=explode(',',$v['auth_package']);
            if(!in_array($site_info['package'],$auth_package))continue;
        }
        if(empty($v['name']))$v['name']='默认';
        $v['id']=$k;
        $poster_list[]=$v;
    }
    return $poster_list;
}

/**
 * 某一等级以上所有等级
 * @param $rank_id 等级id
 */
function get_rankids($rank_id){
    if(!$rank_id)return;
    $map=array();
    $map['id']=$rank_id;
    $map['status']=1;
    $sort = M('MemberRank')->where($map)->getField('sort');
    unset($map['id']);
    $map['sort']=array('egt',$sort);
    $rank_ids=M('MemberRank')->where($map)->getField('id',true);
    if($rank_ids)return $rank_ids;
}
/**
 * 计算团队业绩或者个人业绩
 * @param $uid 会员id
 * @param $performance 加权值
 * @param $map 搜索条件
 * @param $type 0：团队业绩 1：个人业绩 默认0团队
 */
function get_ordermoney($uid,$performance,$map=array(),$type=0){
    if(!$uid)return;
    $ids=array();
    // 获得该会员的团队会员
    $map['pay_status']=3;
    $map['is_delete']=0;
    $map['status']=3;
    if($type==0){//团队人员
        $ids=get_all_child_id($uid);
    }else{//个人业绩涉及人员
        // 直推人员和自己
        $ids=M('Member')->where('parent_id='.$uid)->getField('id',true);
    }
    array_push($ids,$uid);
    $map['uid']=array('in',$ids);
    $sellmoney = M('OrderInfo')->where($map)->sum('goods_allmoney');
    // print_r(M('OrderInfo')->getLastSql());die;
    if($sellmoney){
        // 5、团队/个人业绩符合条件的获取该条件下的权重
        $new = array();
        foreach ($performance as $val) {
            if($type==0)$new[] = $val['t_money'];
            else $new[] = $val['g_money'];
        }
        array_multisort($new, SORT_DESC, $performance);
        foreach ($performance as $key => $value) {
            if($type==0){
                $money=$value['t_money'];
                $money_weight=$value['t_money_weight'];
            }else{
                $money=$value['g_money'];
                $money_weight=$value['g_money_weight'];
            } 
            $money=$money*10000;
            if($sellmoney>=$money){
                $return['weight']=$money_weight;break;
            }else continue;
        }
        $return['sellmoney']=$sellmoney;
    }

    return $return;
}
/**
 * 分红权重计算
 * @param $uid 会员id
 * @param $uid 会员id
 */
function share_bonus($start_time=0,$end_time=0){
    $data=array();
    // 1、是否满足分红的等级条件 会员等级是否有效
    $share_config = M('Config')->where("name='SHAREBONUS'")->getField('value');
    $shareinfo = unserialize($share_config);
    $rank_ids=get_rankids($shareinfo['config']['fh_level']);
    $where['status']=1;
    $where['rank_id']=array('in',$rank_ids);
    $uids=M('Member')->where($where)->getField('id',true);
    if(!$uids)return;
    // 2、下级是否拥有n个以上X等级以上会员
    $rank_ids1=get_rankids($shareinfo['config']['child_level']);
    $where1['rank_id']=array('in',$rank_ids1);
    $where1['uid']=array('in',$uids);
    $where1['zhi_num']=array('egt',$shareinfo['config']['child_level_num']);
    $users=M('MemberRankLink')->where($where1)->field('uid,u_rank')->select();
    $users=array_unique($users,SORT_REGULAR);
    // $users=Array ( '0' => Array ( 'uid' => 20 ,'u_rank' => 2 ),'1' => Array ( 'uid' => 12 ,'u_rank' => 2 ) );
    // print_r(count($users));die;
    if($users){
        foreach($users as $k=>$v){
            // 3、若以上条件符合 则得到会员的等级权重
            $map['status']=1;
            $map['id']=$v['u_rank'];
            $count=M('MemberRank')->where($map)->count();
            if($count >= 0){
                $v['rank_weight']=floatval($shareinfo['item'][$v['u_rank']]['level_weight']); //等级权重
            }
            // 4、计算团队业绩
            if($start_time>0)$t_map['addtime'][]=array('egt',$start_time);
            if($end_time>0)$t_map['addtime'][]=array('lt',$end_time);
            $t_weight=get_ordermoney($v['uid'],$shareinfo['t_performance'],$t_map);
            $v['t_weight']=floatval($t_weight['weight']); //团队加权
            $v['t_sellmoney']=$t_weight['sellmoney']; //团队业绩
            // 6、计算个人业绩
            $g_weight=get_ordermoney($v['uid'],$shareinfo['g_performance'],$t_map,1);
            $v['g_weight']=floatval($g_weight['weight']); //个人加权
            $v['g_sellmoney']=$g_weight['sellmoney']; //个人业绩
            //该计算单人总权重 =等级权重+团队业绩权重+个人业绩权重+默认权重100
            $v['user_weight']=$v['rank_weight']+$v['t_weight']+$v['g_weight']+100;
            $data['user_money'][]=$v;
            $data['log']['user_num']=count($users);
            $data['log']['sum_weight']+=$v['user_weight'];
        }
    }else{
        return;
    }
    return $data;
}
//获取所有父级
function get_all_parent_id($id,&$arr = array()){
    if(intval($id)>0){
        $arr[] = $id;
        $pid= M('Member')->where('id='.$id)->getField('parent_id');
        if($pid>0){
            get_all_parent_id($pid,$arr);
        }
    }
    return $arr;
}
//获取所有子级
function get_all_child_id($id,$map=array(),&$arr = array()){
    if(intval($id)>0){
        $map['parent_id']=$id;
        $pids= M('Member')->where($map)->field('id')->select();
        // print_r($pids);exit;
        if($pids>0){
            foreach ($pids as $key => $value) {
                // print_r($value['id']);
                $arr[]=$value['id'];
                get_all_child_id($value['id'],'',$arr);
            }
        }
    }
    return $arr;
}

/**
 * 是否有权限获得三级分佣奖励
 * @param $user    会员id
 * @param $goods_info     商品价格（会员价\属性价）
 */
function is_sanji($user,$goods_info){
    $return=array('fy_status'=>0);
    $config=unserialize(C('AFFILIATE'));
    //1、推广返利等级限定 为开启   并且等级为X等级
    if($config['config']['is_level'] == 1){
        $u_rank=idtoname($user,'Member','rank_id','id',false);
        if(intval($u_rank) >= intval($config['config']['ex_level'])){
            $return['fy_status']=1; //拥有获得分佣的资质
        }
    }
    if($return['fy_status']==1){
        //2、分销类型 1现金 2积分
        $return['fx_type']=$config['config']['fx_type'];
        //3、是否设置固定金额 
        if($goods_info){
            // 0|不分佣,1|按系统设定,2|按固定金额
            if($goods_info['is_referral'] == 2){
                $goods_info['referral_money'] = $goods_info['commission'];
            }else if($goods_info['is_referral'] == 1){
                $goods_info['referral_money'] = $goods_info['shop_price']*$config['item'][1]['level_money']/100;
            }else{
                $goods_info['referral_money'] = 0;
            }
            $return['price']=$goods_info['referral_money'];
        }
    }
    return $return;
}
//清空所有缓存
function clearcache(){
   $cachepath=ROOT_PATH.'/uploads/image/matter/';$cachename='cachetime.cache';
   $cachetime=@file_get_contents($cachepath.$cachename);
   $date=date('Y-m-d');
   if($cachetime==$date)return false;
   foreach(scandir($cachepath) as $fn) {
       if(in_array($fn,array(".","..",$cachename)))continue;
       unlink($cachepath.$fn);
   }file_put_contents($cachepath.$cachename,$date);
   return true;
}

function sell_count($id,$act_id=0,$goods=''){
    if(empty($id))return false;
    $shop_id = get_wxsmall_shop_id();
    if(empty($goods)){
        $map=array();
        $map['id']=$id;
        $goods_act_sell_count=M("Goods")->where($map)->getField("act_sell_count");
    }
    $map=array();
    $map['goods_id']=$id;
    $map['shop_id']=$shop_id;
    $goods=M("ShopsGoodsStock")->where($map)->field('sell_count,goods_number')->find();
    if ($act_id) {
        $pt_map = array();
        $pt_map['id'] = $act_id;
        $act_info = M('PromotAct')->where($pt_map)->field('end_time,start_time')->find();
    }

    if($act_id && (($act_info['end_time'] && NOW_TIME<$act_info['end_time']) && ($act_info['start_time'] && NOW_TIME >$act_info['start_time']))){
        if ($goods_act_sell_count > 0) {
            $sell_count=$goods_act_sell_count;
        } else {
            $sell_count =0;
        }
    }else{
        if ($goods['sell_count'] > 0) {
            $sell_count=$goods['sell_count'];
        } else {
            $sell_count = 0;
        }
    }
    return floatval($sell_count);
}
function share_name($id,$type=0){
    $info = M('Goods')->where('id='.$id)->find();
    if($info['promote_id']){
        $tl_map['status'] = 1;
        $tl_map['id'] = $info['promote_id'];
        $act_info = M('PromotAct')->where($tl_map)->order('end_time desc')->field('id,start_time,end_time')->find();
        if($act_info['start_time']<=NOW_TIME && $act_info['end_time']>=NOW_TIME ){
            $act_id=$act_info['id'];
        }
        if($act_id && $info['promote_price']>0){//判断促销价是否有效
            $price = $info['promote_price'];
            $name = '抢购价';
        }else{
            $price = $info['shop_price'];
            $name = '售价';
        }
    }else if($info['pt_id']){
        $map = array();
        $map['pa.id'] = $info['pt_id'];
        $map['pe.style_ext_id']=$info['id'];
        $map['pe.style']=4;
        $map['pa.start_time'] = array('lt',NOW_TIME);
        $map['pa.end_time'] = array('gt',NOW_TIME);
        // $goods = M('PromotAct')->where('id='.$info['pt_id'])->find();
        $pro_info = M('PromotAct')->field('pa.*,pe.style,pe.style_ext_id,pe.remarks')->alias('pa')->where($map)->join('LEFT JOIN __PROMOT_EXT__ pe ON pe.act_id=pa.id')->find();
        if($pro_info){
            $price = unserialize($pro_info['remarks']);
            $name = '拼团价';
        }else{
            $price = $info['shop_price'];
            $name = '售价';
        }
    }else{
        $price = $info['shop_price'];
        $name = '售价';
    }
    $share_name =$name.' '.$price.'元 '. $info['goods_name'];
    // $len = strlen($info['goods_name']);
    // if($len<52){
    //     $share_name =$name.' '.$price.'元 '. $info['goods_name'];
    // }else{
    //     $share_name =$name.' '.$price.'元 '.mb_substr($info['goods_name'],0,24,'utf-8');
    // }
    if($type==1){
        return $price;
    }else{
        return $share_name;
    }

}

/**
 * 商品内容页图文分享
 * @param $uid 会员id
 * @param $is_type 类型0小程序1素材
 * @param $goods_id 商品id
 * @return mixed
 */
function goods_shots($uid,$is_type=1,$goods_id,$lshop_id){
    $uid=intval($uid);
    // $site_id=C('appid');//站点ID
    $return =array('status'=>0,'msg'=>'');
    if(empty($goods_id)){//empty($uid) || 
        $return['msg']="参数错误!";
        return $return;
    }
    if($uid){
        $map=array();$map['id']=$uid;$map['status']=1;
        $member_info = M('Member')->where($map)->field('id,username,header_img,nickname,wxid')->find();
        if (empty($member_info)) {
            $return['msg']="会员不存在";
            return $return;
        }
    }
    $map=array();$map['id']=$goods_id;$map['status']=1;
    $goods_info = M('Goods')->where($map)->field('goods_name,market_price,shop_price,img')->find();
    if (empty($goods_info)) {
        $return['msg']="商品不存在";
        return $return;
    }
    clearcache();
    //logo、二维码的坐标
    //原图背景、
    $x=100;$y=980;
    $yuan_img = ROOT_PATH.'/uploads/image/qrcode/bg.jpg';
    if(empty($yuan_img))return false;
    $linshiimg="/uploads/image/matter/code_cont".$uid.'_'.$is_type.'_'.$goods_id.".jpg";
    //删除
    if(file_exists(ROOT_PATH.$linshiimg)){
        unlink(ROOT_PATH.$linshiimg);
    }

    if(!file_exists(ROOT_PATH.$linshiimg)){
        copy($yuan_img,ROOT_PATH.$linshiimg);
        if(!file_exists(ROOT_PATH.$linshiimg)){
            $return['msg']="生成图片失败，请重试！(000)";
            return $return;
        }
        $old_cache_f='';
        if($is_type == 1){
            // 如果是小店店主
            if(cookie('lshop_id')){
                $lshop_id=cookie('lshop_id');
            }
            if($lshop_id){
                $lshop_id=$lshop_id;
            }
            $url=U('Mobile/goods/goods_cont',array('id'=>$goods_id,'eid'=>$uid,'lshop_id'=>$lshop_id),true,true);
            $old_cache_f = phpgrcode(urlencode($url),'M','3','decca_'.$lshop_id.'_'.$uid);//生成之后的图
            $old_cache_f= format_url($old_cache_f,2);
        }else{
            $invite_key = base64_encode($uid);
            $param=array();$param['width']=120;
            $param['type']=1;
            $param['path'] = "pages/takeout/cont/cont?invite_key=".$invite_key."&id=".$goods_id.'&lshop_id='.$lshop_id;//小程序参数
            $wxsmall = new \Common\Vendor\Wxsmallopen;
            $result=$wxsmall->get_location_small_code($param);
            preg_match('/(.*)base64,(.*)/', $result, $matches);
            $base64 = $matches['2'];
            $img = base64_decode($base64);
            $old_cache_f= ROOT_PATH."/uploads/".date("YmdHis")."wx_img.jpg";
            if(!empty($img)){@file_put_contents($old_cache_f,$img);}
        }
        $haibao= new \Common\Vendor\Haibao;    
        // $haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y);//二维码写入到背景图片中
        if($old_cache_f){
            //二维码写入到背景图片中
            if($is_type == 1){
                $t =$haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y,210,210);
            }else{
                $t =$haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y,210,210);
            }
        }
        if($goods_info['img']){
            $img_x = 147;
            $img_y = 193;
            $t =$haibao->addPic(ROOT_PATH.$linshiimg,ROOT_PATH.$goods_info['img'],$img_x,$img_y,430,430);
        }
        $goods_name=!empty($goods_info['goods_name'])?$goods_info['goods_name']:'商品名称';
        $goods_name=trim($goods_name);
        $encode = mb_detect_encoding($goods_name,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
        if ($encode != "UTF-8"){$goods_name = iconv($encode,"UTF-8",$goods_name);}
        $theTitle = $haibao->cn_row_substr($goods_name,2,15);
        $iinfo=getimagesize(ROOT_PATH.$linshiimg);$imgWidth=$iinfo[0];
        $params=array();
        $wordstart=680;
        foreach($theTitle as $v){
            $size=24;
            $centerx=$haibao->getcenterx($v,$size,$imgWidth);
            $params[]=array('str'=>$v,'posX'=>$centerx,'poxY'=>$wordstart,'size'=>$size,'color'=>'black');
            $wordstart= $wordstart+40;
        }
        $params[]=array('str'=>'￥','posX'=>233,'poxY'=>782,'size'=>18,'color'=>'red');
        $params[]=array('str'=>$goods_info['shop_price'],'posX'=>253,'poxY'=>782,'size'=>24,'color'=>'red');
        
        $strlength=$haibao->checkStrlength($goods_info['shop_price'],24);
        $danweix=253+$strlength;
        $params[]=array('str'=>'','posX'=>$danweix,'poxY'=>782,'size'=>18,'color'=>'red');
        $moneygray=$danweix+45;
        $params[]=array('str'=>'￥'.$goods_info['market_price'],'posX'=>$moneygray,'poxY'=>782,'size'=>18,'color'=>'gray');
        
        $strlength=$haibao->checkStrlength('￥'.$goods_info['market_price'],18);
        $params[]=array('str'=>'line','posX'=>$moneygray,'poxY'=>776,'size'=>$strlength,'color'=>'gray');
         
        $haibao->addWords(ROOT_PATH.$linshiimg,$params);
    }
    if(file_exists(ROOT_PATH.$linshiimg)){
        $return['status']=1;
        $return['url']=format_url($linshiimg);
        unlink($old_cache_f);
        return $return;
    }else{
        $return['msg']="生成图片失败，请重试！(002)";
        return $return;
    }
}
/**
 * 素材生成图片
 * @param $uid 会员id
 * @param $is_type 类型0小程序1素材
 * @param $goods_id 商品id
 * @param $matter_img 素材路径
 * @param $matter_img_id 素材id
 * @return mixed
 */
function matter_code($uid,$is_type=1,$goods_id,$matter_img,$matter_img_id){
    $uid=intval($uid);
    // $site_id=C('appid');//站点ID
    $return =array('status'=>0,'msg'=>'');
    if(empty($uid) || empty($goods_id) || empty($matter_img) || empty($matter_img_id)){
        $return['msg']="参数错误!";
        return $return;
    }
    $map=array();$map['id']=$uid;$map['status']=1;
    $member_info = M('Member')->where($map)->field('id,username,header_img,nickname,wxid')->find();
    if (empty($member_info)) {
        $return['msg']="会员不存在";
        return $return;
    }
    $map=array();$map['id']=$goods_id;$map['status']=1;
    $goods_info = M('Goods')->where($map)->field('goods_name,market_price,shop_price')->find();
    if (empty($goods_info)) {
        $return['msg']="商品不存在";
        return $return;
    }
    clearcache();
    //logo、二维码的坐标
    //原图背景、
    $x=370;$y=510;
    $yuan_img = format_url($matter_img,2);
    // $linshiimg="/uploads/image/matter/code".$site_id.'_'.$uid.'_'.$is_type.'_'.$goods_id.'_'.$matter_img_id.".jpg";//临时图片
    $linshiimg="/uploads/image/matter/code".$uid.'_'.$is_type.'_'.$goods_id.'_'.$matter_img_id.".jpg";//临时图片
    if(!file_exists(ROOT_PATH.$linshiimg)){
        copy($yuan_img,ROOT_PATH.$linshiimg);
        if(!file_exists(ROOT_PATH.$linshiimg)){
            $return['msg']="生成图片失败，请重试！(000)";
            return $return;
        }
        $old_cache_f='';
        if($is_type == 1){
            // 如果是小店店主
            if(cookie('lshop_id')){
                $lshop_id=cookie('lshop_id');
            }
            $url=U('Mobile/goods/goods_cont',array('id'=>$goods_id,'eid'=>$uid,'lshop_id'=>$lshop_id),true,true);
            // $old_cache_f = phpgrcode(urlencode($url),'M','3','decca_'.$site_id.'_'.$uid);//生成之后的图
            $old_cache_f = phpgrcode(urlencode($url),'M','3','decca_'.$lshop_id.'_'.$uid);//生成之后的图
            $old_cache_f= format_url($old_cache_f,2);
        }else{
            // $param=array();$param['morecode']="SHOP";$param['shop_id']=1;$param['width']=150;//小程序参数
            // $wxsmall = new \Common\Vendor\Wxsmallopen;
            // $result=$wxsmall->get_location_small_code($param);
            // $old_cache_f='uploads/'.date("YmdHis").'wx_img.png';
            // $rr = file_put_contents($old_cache_f,$result);
            // if($rr){
            //     $old_cache_f = format_url($old_cache_f);
            // }
            $invite_key = base64_encode($uid);
            $param=array();$param['width']=120;
            $param['type']=1;
            $param['path'] = "pages/takeout/cont/cont?invite_key=".$invite_key."&id=".$goods_id;//小程序参数
            $wxsmall = new \Common\Vendor\Wxsmallopen;
            $result=$wxsmall->get_location_small_code($param);
            preg_match('/(.*)base64,(.*)/', $result, $matches);
            $base64 = $matches['2'];
            $img = base64_decode($base64);
            $old_cache_f= ROOT_PATH."/uploads/".date("YmdHis")."wx_img.jpg";
            if(!empty($img)){@file_put_contents($old_cache_f,$img);}
        }
        $haibao= new \Common\Vendor\Haibao;    
        // $haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y);//二维码写入到背景图片中
        if($old_cache_f){
            //二维码写入到背景图片中
            if($is_type == 1){
                $t =$haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y);
            }else{
                $t =$haibao->addPic(ROOT_PATH.$linshiimg,$old_cache_f,$x,$y,120,120);
            }
        }
        $goods_name=!empty($goods_info['goods_name'])?$goods_info['goods_name']:'商品名称';
        $goods_name=trim($goods_name);
        $encode = mb_detect_encoding($goods_name,array("ASCII","UTF-8","GB2312","GBK","BIG5"));
        if ($encode != "UTF-8"){$goods_name = iconv($encode,"UTF-8",$goods_name);}
        $theTitle = $haibao->cn_row_substr($goods_name,2,13);
        // print_r($theTitle);exit;
        $params=array();
        $wordstart=540;
        foreach($theTitle as $v){
            $size=18;
            $params[]=array('str'=>$v,'posX'=>15,'poxY'=>$wordstart,'size'=>$size,'color'=>'black');
            $wordstart= $wordstart+30;
        }
        $params[]=array('str'=>'￥','posX'=>25,'poxY'=>620,'size'=>18,'color'=>'red');
        $params[]=array('str'=>$goods_info['shop_price'],'posX'=>45,'poxY'=>620,'size'=>24,'color'=>'red');
        
        $strlength=$haibao->checkStrlength($goods_info['shop_price'],24);
        $danweix=45+$strlength;
        $params[]=array('str'=>'','posX'=>$danweix,'poxY'=>620,'size'=>18,'color'=>'red');
        $moneygray=$danweix+20;
        $params[]=array('str'=>'￥'.$goods_info['market_price'],'posX'=>$moneygray,'poxY'=>620,'size'=>18,'color'=>'gray');
        
        $strlength=$haibao->checkStrlength('￥'.$goods_info['market_price'],18);
        $params[]=array('str'=>'line','posX'=>$moneygray,'poxY'=>612,'size'=>$strlength,'color'=>'gray');
         
        $haibao->addWords(ROOT_PATH.$linshiimg,$params);
    }
    if(file_exists(ROOT_PATH.$linshiimg)){
        $return['status']=1;
        $return['url']=format_url($linshiimg);
        unlink($old_cache_f);
        return $return;
    }else{
        $return['msg']="生成图片失败，请重试！(002)";
        return $return;
    }
}
function member_upgrade($id,$orderids_arr=''){
        if(empty($id))return false;
        $member_info = M('Member')->where('id='.$id)->find();
        if(empty($member_info))return false;
        $map = array();
        $map['status']=1;
        $map['sort'] = array('gt',$member_info['rank_id']);
        $member_ranks = M('MemberRank')->where($map)->order('sort asc')->select();
        /* //购买指定商品金额
        if(!empty($orderids_arr)){
            $o_ids = $orderids_arr;
            $goods_ids = unserialize(C('PRO_GOODS'));
            $g_ids = unserialize($goods_ids['temp']);
            $map = array();
            $map['order_id']=array('in',$o_ids);
            $map['goods_id']=array('in',$g_ids);
            $buy_money = M('OrderGoods')->where($map)->sum('goods_price*goods_number');
        } */
		//jxr start 修改
		$ranks=array(2,3,4);
		$rank_num=array();
		//推荐会员晋升人数
		$map = array();
		$map['uid']=$id;
		$member_link = M('MemberRankLink')->where($map)->select();
		$new_array = array();
		if(!empty($member_link)){
			foreach ($member_link as $key => $value) {
				$new_array[$value['rank_id']]=$value;
				foreach($ranks as $k => $val){
					if(empty($rank_num[$val]))$rank_num[$val]=array('zhi_num'=>0,'jian_num'=>0,'all_num'=>0);
					if($val <= $value['rank_id']){
						$rank_num[$val]['zhi_num'] +=$value['zhi_num'];
						$rank_num[$val]['jian_num'] +=$value['jian_num'];
						
						$rank_num[$val]['all_num'] +=$value['all_num'];
					}
				}
			}
		}
		//jxr end 修改
        if(!empty($member_ranks)){
            foreach ($member_ranks as $key => $value) {
                $level_pro=unserialize($value['level_pro']);
                 // print_r($level_pro);exit;
                // 购买指定商品晋升
                if($level_pro['pro_type']==1){
                    if($level_pro['type_buy']==1){
						//购买指定商品金额
						if(!empty($orderids_arr)){
							$o_ids = $orderids_arr;
							$goods_ids = unserialize(C('PRO_GOODS'));
							$g_ids = unserialize($goods_ids['temp']);
							//该等级的晋升商品	jxr 2019.10.12  start 
							$map = array();
							$map['rank_jinsheng']=array('in','0,'.$value['id']);
							$map['id']=array('in',$g_ids);
							$gids=M('Goods')->where($map)->getField('id',true);
							//该等级的晋升商品	jxr 2019.10.12  end
							$map = array();
							$map['order_id']=array('in',$o_ids);
							$map['goods_id']=array('in',$gids);
							$buy_money = M('OrderGoods')->where($map)->sum('goods_price*goods_number');
						}
                        if($buy_money>=$level_pro['buy_money']) $return['pro_status']=1;
                        else $return['pro_status']=0;
                    }
                }
                //消费满额晋升
                if($level_pro['pro_type']==2){
                    if($level_pro['one_buy']==1){
                        $one_buy_money = $member_info['one_buy_count'];
                        if($one_buy_money>=$level_pro['one_buy_money']) $res['one_buy']=1;
                        else $res['one_buy']=0;
                    }else{
                        $res['one_buy']=1;
                    }
                    if($level_pro['zhi_buy']==1){
                        $zhi_buy_money = $member_info['zhi_buy_count'];
                        if($zhi_buy_money>=$level_pro['zhi_buy_money']) $res['zhi_buy']=1;
                        else $res['zhi_buy']=0;
                    }else{
                        $res['zhi_buy']=1;
                    }
                    if($level_pro['jian_buy']==1){
                        $jian_buy_money = $member_info['jian_buy_count'];
                        if($jian_buy_money>=$level_pro['jian_buy_money']) $res['jian_buy']=1;
                        else $res['jian_buy']=0;
                    }else{
                        $res['jian_buy']=1;
                    }
                    if($res['one_buy']==1 && $res['zhi_buy']==1 && $res['jian_buy']==1){
                        $return['pro_status']=1;
                    }else{
                        $return['pro_status']=0;
                    }
                }
                //推荐会员晋升
                if($level_pro['pro_type']==3){
                    
                    if($level_pro['zhi_tui']==1){
                        $link_info = $rank_num[$level_pro['zhi_level']];
                        if($link_info['zhi_num']>=$level_pro['zhi_level_num']) $res['zhi_tui']=1;
                        else $res['zhi_tui']=0;
                        
                    }else{
                        $res['zhi_tui']=1;
                    }
                    if($level_pro['jian_tui']==1){
                        $link_info = $rank_num[$level_pro['jian_level']];
                        if($link_info['jian_num']>=$level_pro['jian_level_num']) $res['jian_tui']=1;
                        else $res['jian_tui']=0;
                    }else{
                        $res['jian_tui']=1;
                    }
                    if($level_pro['all_tui']==1){
						$link_info = $rank_num[$level_pro['all_level']];
                        if($link_info['all_num']>=$level_pro['all_level_num']) $res['all_tui']=1;
                        else $res['all_tui']=0;
                    }else{
                        $res['all_tui']=1;
                    }
                    if($res['zhi_tui']==1 && $res['jian_tui']==1){
                        $return['pro_status']=1;
                    }else{
                        $return['pro_status']=0;
                    }
                } 
				// 或者条件 jxr
				if(!empty($level_pro_plus)){
					if($level_pro_plus['zhi_tui_plus']==1){
						$link_info_plus = $rank_num[$level_pro_plus['zhi_level_plus']];
						if($link_info_plus['zhi_num']>=$level_pro_plus['zhi_level_num_plus']) $res['zhi_tui_plus']=1;
						else $res['zhi_tui_plus']=0;
					}
					if($res['zhi_tui_plus']==1){
						$return['pro_status_plus']=1;
					}else{
						$return['pro_status_plus']=0;
					}
				}
				
				if($return['pro_status']==1 || $return['pro_status_plus']==1){
					$return['rank_id'][]=$value['id'];break;
				}
            }
              $inf =array_filter($return['rank_id']);
              if(!empty($inf)){
                $rrr = change_rank_link($id,$inf[0],$member_info['rank_id']);
                $rest = pro_affiliate($id,$inf[0]);
                // print_r($rrr);exit;
                $save['rank_id'] = $inf[0];
                $save['is_littleshop']=1;
				if($inf[0]==2){
					$save['js_vip_time']=NOW_TIME;//jxr end 2019.05.31
				}
                $map = array();
                $map['id'] = $id;
                $result=M('Member')->where($map)->save($save);

                $map = array();
                $map['uid']=$id;
                $link_save['u_rank']=$inf[0];
                M('MemberRankLink')->where($map)->save($link_save);

                $map = array();
                $map['uid']=$id;
                $little_count = M('LittleShop')->where($map)->count();
                if($little_count==0){
                    $little_shop['uid']=$id;
                    $little_shop['addtime']=NOW_TIME;
                    $little_shop['status']=1;
                    M('LittleShop')->add($little_shop);
                }
                $pid = idtoname($id,'Member','parent_id');
				member_upgrade($pid);
                /* $ppid = idtoname($pid,'Member','parent_id');
                if(!empty($pid))$parent_ids[]=$pid;
                if(!empty($ppid))$parent_ids[]=$ppid;
                foreach ($parent_ids as $key => $va) {
                    member_upgrade($va);
                } */
                
              }
        }
    }
//gyc 2019.1.27
function pro_affiliate($uid,$rank_id){
	if(empty($uid) || empty($rank_id))return false;
	$affiliate = unserialize(C('AFFILIATE'));
	$pro_setting= unserialize(C('PRO_SETTING')); //jxr 2019.10.11 
	$pro_level = M('Config')->field('value')->where("name='PRO_LEVEL'")->find();
	$pro_level = unserialize($pro_level['value']);
	// print_r($pro_level);exit;
	$member_rank=idtoname($rank_id,'MemberRank','*');//自己等级信息
	$level_pro = unserialize($member_rank['level_pro']);
	// print_r($level_pro);die;
	$pid = idtoname($uid,"Member",'parent_id');
	$ppid = idtoname($pid,"Member",'parent_id');
	$pppid = idtoname($ppid,"Member",'parent_id');
	$pid_rank = idtoname($pid,"Member",'rank_id');
	$ppid_rank = idtoname($ppid,"Member",'rank_id');
	$pppid_rank = idtoname($pppid,"Member",'rank_id');
	if($level_pro['pro_type']==1){//晋升奖励 百分比  或者固定值
		foreach($pro_level['info'] as $k=>$value){
			// print_r($value);exit;
			if($rank_id==$value['one_level'] || $value['one_level']==0){
				if( ($pid_rank==$value['zhi_level']) || $value['zhi_level']==0 ){
					if( ($ppid_rank==$value['jian_level']) || $value['jian_level']==0 ){
						if( ($pppid_rank==$value['san_level']) || $value['san_level']==0 ){
							if($pid && $pro_setting['config']['fx_money_type']==3) $arr['pid_money'] = format_decimal($value['fen_money']); //固定值
							if($pid && $pro_setting['config']['fx_money_type']==1) $arr['pid_money'] = format_decimal($level_pro['buy_money']*$value['fen_money']/100); //百分比
							if($ppid && $pro_setting['config']['fx_money_type']==3) $arr['ppid_money'] = format_decimal($value['sfen_money']); //固定值
							if($ppid && $pro_setting['config']['fx_money_type']==1) $arr['ppid_money'] = format_decimal($level_pro['buy_money']*$value['sfen_money']/100);//百分比
							if($pppid && $pro_setting['config']['fx_money_type']==3) $arr['pppid_money'] = format_decimal($value['ssfen_money']); //固定值
							if($pppid && $pro_setting['config']['fx_money_type']==1) $arr['pppid_money'] = format_decimal($level_pro['buy_money']*$value['ssfen_money']/100);//百分比
						}
					}
				}
			}
		}
	}else{//分上一级 固定值
		if($member_rank['sort']>=$pro_level['item']['zi_one_level']){
			$pid_sort = idtoname($pid_rank,'MemberRank','sort');
			if($pid && ($pid_sort>=$pro_level['item']['zi_jian_level'])  ){  
				$arr['pid_money'] = $pro_level['item']['zi_fen_money'];
				if($pro_level['item']['fen_type']==2){
					$arr['point']=1; 
				}
			}
		}
	}
	if($pid && $arr['pid_money']){
		$money  = $arr['pid_money'];
		$log='被推荐人('.idtoname($uid,'Member','username;nickname').')等级晋升，将赠1级推荐人('.idtoname($pid,'Member','username;nickname').')';
		if($money>0){
		  $log.=' 余额：'.$money;
		  affiliate_log('',1,$pid,$money,0,$log,1); 
		  account_change($pid,$money,8,15,'被推荐人'.idtoname($uid,'Member','username;nickname').'等级晋升，1级推荐人得到佣金分成');
		}
		$return['status'] = 1;
	}
	if($ppid && $arr['ppid_money']){  
		$money = $arr['ppid_money'];
		$log='被推荐人('.idtoname($uid,'Member','username;nickname').')等级晋升，将赠2级推荐人('.idtoname($ppid,'Member','username;nickname').')';
		if($money>0){
		  $log.=' 余额：'.$money;
		  affiliate_log('',1,$ppid,$money,0,$log,1); 
		  account_change($ppid,$money,8,15,'被推荐人'.idtoname($uid,'Member','username;nickname').'等级晋升，2级推荐人得到佣金分成');
		}
		
		$return['status'] = 1;
	}
	if($pppid && $arr['pppid_money']){  
		$money = $arr['pppid_money'];
		$log='被推荐人('.idtoname($uid,'Member','username;nickname').')等级晋升，将赠3级推荐人('.idtoname($pppid,'Member','username;nickname').')';
		if($money>0){
		  $log.=' 余额：'.$money;
		  affiliate_log('',1,$pppid,$money,0,$log,1); 
		  account_change($pppid,$money,8,15,'被推荐人'.idtoname($uid,'Member','username;nickname').'等级晋升，3级推荐人得到佣金分成');
		}
		$return['status'] = 1;
	}
}
    //gyc 2019.1.28
    /* function change_rank_link($id,$rank_id,$old_rank_id){
        if(empty($id) || empty($rank_id))return false;
        $pid = idtoname($id,'Member','parent_id');
        $ppid = idtoname($pid,'Member','parent_id');
        if(!empty($pid))$parent_ids[]=$pid;
        if(!empty($ppid))$parent_ids[]=$ppid;   
         if(!empty($parent_ids)){
            foreach ($parent_ids as $key => $value) {
                $map = array();
                $map['uid']=$value;
                $map['rank_id']=$rank_id;
                $count = M('MemberRankLink')->where($map)->count();
                 
                if($count==0){
                    if($value==$pid){
                        $zhi_num=1;
                    }else  $zhi_num=0;
                    if($value==$ppid){
                        $jian_num=1;
                    }else  $jian_num=0;
                    $data['uid']=$value;
                    $data['rank_id']=$rank_id;
                    $data['zhi_num']=$zhi_num;
                    $data['jian_num']=$jian_num;
                    $data['all_num']=0;
                    $data['u_rank']=idtoname($value,'Member','rank_id');
                    $res = M('MemberRankLink')->add($data);
                }else{
                    $map = array();
                    $map['uid']=$value;
                    $map['rank_id']=$rank_id;
                    $old_map = array();
                    $old_map['uid']=$value;
                    $old_map['rank_id']=$old_rank_id;
                    if($value==$pid){
                        $res=M('MemberRankLink')->where($map)->setInc('zhi_num');
                        if($old_rank_id>1)$res=M('MemberRankLink')->where($old_map)->setDec('zhi_num');
                    }else if($value==$ppid){
                        $res=M('MemberRankLink')->where($map)->setInc('jian_num');
                        if($old_rank_id>1)$res=M('MemberRankLink')->where($old_map)->setDec('jian_num');
                    }
                }
                
            }
            if($res)$return['status']=1;
            else $return['status']=0;
        }
        // print_r($parent_ids);exit;
        return $return;
    } */
	
function change_rank_link($id,$rank_id,$old_rank_id=1,$is_jian=0){
    if(empty($id) || empty($rank_id))return false;
	$value=idtoname($id,'Member','parent_id','id',false);
    if(empty($value))return true;
	$field=empty($is_jian)?"zhi_num":"jian_num";
	$map = array();
	$map['uid']=$value;
	$map['rank_id']=$rank_id;
	$count = M('MemberRankLink')->where($map)->field('id')->count();
	if($count==0){
		$data=array();
		$data['uid']=$value;
		$data['rank_id']=$rank_id;
		$data['zhi_num']=empty($is_jian)?1:0;
		$data['jian_num']=empty($is_jian)?0:1;
		$data['all_num']=1;
		$data['u_rank']=idtoname($value,'Member','rank_id');
		$res = M('MemberRankLink')->add($data);
		if($res && $old_rank_id>1){		
			$old_map = $data = array();
			$old_map['uid']=$value;
			$old_map['rank_id']=$old_rank_id;
			$data[$field]=array('exp',$field.'-1');
			$data['all_num']=array('exp','all_num-1');
			M('MemberRankLink')->where($old_map)->save($data);
		}
	}else{
		$map =$data=array();
		$map['uid']=$value;
		$map['rank_id']=$rank_id;
		$data[$field]=array('exp',$field.'+1');
		$data['all_num']=array('exp','all_num+1');
		M('MemberRankLink')->where($map)->save($data);
		if($old_rank_id>1){
			$map['rank_id']=$old_rank_id;
			$data=array();
			$data[$field]=array('exp',$field.'-1');
			$data['all_num']=array('exp','all_num-1');
			M('MemberRankLink')->where($map)->save($data);
		}
	}
    return change_rank_link($value,$rank_id,$old_rank_id,1);
}
	
	
	
	
	
	
    // function pro_affiliate($uid,$rank_id){
    //     if(empty($uid) || empty($rank_id))return false;
    //     $affiliate = unserialize(C('AFFILIATE'));
    //     $pro_info = $affiliate['pro'];
    //     $member_rank=idtoname($rank_id,'MemberRank','*');
    //     $level_pro = unserialize($member_rank['level_pro']);
    //     if($level_pro['pro_type']!=1)return false;

    //     $all_money=$level_pro['buy_money'];//分佣金额
        
    //     $rank_info=ex_ranks($uid);//三级推荐人
    //        // print_r($rank_info);exit;
    //     foreach($affiliate['pro'] as $key=>$val){
    //         $affiliate['pro'][$key]['tui_id']=$rank_info[$key]['id'];
    //         // $affiliate['pro'][$key]['rank_id']=$rank_info[$key]['rank_id'];//
    //     }
         
    //      // print_r($affiliate['pro']);exit;
    //     foreach($affiliate['pro'] as $k=>$v){
    //         if(empty($v['tui_id'])) continue;
    //         if($affiliate['config']['is_level']==1){
    //             $rank_id = idtoname($v['tui_id'],'Member','rank_id');//当前会员等级
    //             $level_sort = idtoname($rank_id,'MemberRank','sort');//当前会员等级级别
    //             if($level_sort<$member_rank['sort'])continue;//判断限制等级与会员等级
    //         }

    //         if($affiliate['config']['fx_money_type']==1){//分现金
    //             $money = format_decimal($all_money*$v['pro_level_money']/100);
    //         }else{//分积分 
    //             $point  = format_decimal($all_money*$v['pro_level_money']/100); 
    //         }
            
    //         $log='被推荐人('.idtoname($uid,'Member','username;nickname').')等级晋升，将赠'.$k.'级('.idtoname($v['tui_id'],'Member','username;nickname').')推荐人';
    //         if($money>0){
    //           $log.=' 余额：'.$money;
    //         }
    //         if($point>0){
    //           $log.=' 积分：'.$point;
    //         }
    //         if($money>0 || $point>0)affiliate_log('',1,$v['tui_id'],$money,$point,$log);  
    //         $return['status'] = 1;
    //     }   
    //     // print_r($return);exit;
    // }
    //gyc
    //消费后 上级累计消费增加
function change_member_pay($id,$money){
    if(empty($id) || empty($money))return false;
    $pid = idtoname($id,'Member','parent_id');
    // $parent_ids = get_all_parent_id($id);
    $parent_id = idtoname($pid,'Member','parent_id');
    //消费自己增加
    $map = array();
    $map['id']=$id;
    $result=M('Member')->where($map)->setInc('one_buy_count',$money);
    //消费上级增加
    $map = array();
    $map['id']=$pid;
    $rest=M('Member')->where($map)->setInc('zhi_buy_count',$money);
    //消费所有上级增加
    // $ppid[]=$pid;
    // $array = array_diff($parent_ids,$ppid);
    $map = array();
    $map['id']=$parent_id;
    // $map['id']=array('in',$array);
    $res=M('Member')->where($map)->setInc('jian_buy_count',$money);
}
//会员id，返回三级父集
function ex_level($id){
    $rank_p=array();
    $where3['id']=$id;
    $rank_p[1]=$id;
    if(!empty($rank_p[1])){
        $where2['id']=$rank_p[1];
        $rank_p[2]=M('Member')->where($where2)->getField('parent_id');
    }
    if(!empty($rank_p[2])){
        $where1['id']=$rank_p[2];
        $rank_p[3]=M('Member')->where($where1)->getField('parent_id');
    }
    
    $rank_p=array_filter($rank_p);
    if(empty($rank_p))return false;
    foreach($rank_p as $key=>$val){
        $rank_info[$key]=idtoname($val,'Member','*');
    }
    return $rank_info;  
}
function getconfig($name){
    if(empty($name))return '';
    $config=C($name);
    if(!isset($config))$config=idtoname($name,'Config','value','name');
    return trim($config);
}
function tempcache($name,$value='',$time=''){
    if(empty($name))return false;
    if(is_null($value)){
        cookie($name,null);session($name,null);return true;
    }
    if(empty($time)) $time=3600*24*7;
    if(empty($value)){//获取
        $session=session($name);
        $cookie=cookie($name);
        if(!empty($session)){
            if(empty($cookie))cookie($name,$session,$time);
            return $session;
        }
        if(!empty($cookie)){
            if(empty($session))session($name,$cookie);
            return $cookie;
        }return false;
    }else{//存储
        cookie($name,$value,$time);session($name,$value);return true;
    }
}

//通过晋升方式 得到等级
function getrank_sheng($type){
    $where=$buy_list=$pt_list=array();
	$where['sort']=array('gt',1);
	$where['status']=1;
	$list=M('MemberRank')->where($where)->select();
	foreach($list as $key=>$val){
		$level_pro=unserialize($val['level_pro']);
		if(intval($level_pro['pro_type'])>0){
			if($level_pro['type_buy']==1){
				$buy_list[$val['id']]=$val['name'];
			}else{
				$pt_list[$val['id']]=$val['name'];
			}
		}
	}
	if($type==1){ //购买指定商品晋升
		return $buy_list;
	}else{ //推荐晋升
		return $pt_list;
	}
}

function getwebimageinfo($url,$type=0){
    if(empty($url))return false;
    $arrTmp=get_headers($url,true);
    if($type==1)return $arrTmp;
    if($arrTmp['Content-Type']=='image/png'){
        return 'png';
    }
    if($arrTmp['Content-Type']=='image/jpeg' || $arrTmp['Content-Type']=='image/jpg'){
        return 'jpg';
    }
    return 'jpg';
}
require(COMMON_PATH.'Common/global.func.php');
require(COMMON_PATH.'Common/extention.func.php');
?>