<?php
/**
 * 管理员登录管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Wxsmall\Model;
use Think\Model;
class LoginModel extends Model{
    protected $tableName = 'Member';
    public function __construct(){
        if(C('BOUND_STATUS')==2){
            $extappid=I('extappid');
            if(empty($extappid)){
                $extappid=C('appid');
            }
            $wx = new \Common\Vendor\Weixinopen;
            $wxinfo=$wx->wxconfig($extappid,'',1);
            $this->APPID=$wxinfo['authorization_info']['authorizer_appid'];
            if(empty($this->APPID))$this->APPID=C('appid');
        }else{
            $this->APPID =getconfig('WX_SHOP_APPID');
            $this->SECRET = getconfig('WX_SHOP_APPSERCRET');
        }
    }
    private $config = array(
        'iv'     => 'hanchao123456',//AES加密初始向量
        'sessiontime'     => '7200',//会员信息有效时间
        'try_count'     => '3'//登录异常限制次数
    );
    /**
     * 获取微信openid和unionid
     * @param string $code 用户登录标识
     * @return array 成功时 session_key和openid和unionid 失败时 errcode和errmsg
     */
    public function get_wxinfo($code){
        $APPID = $this->APPID;
        $SECRET = $this->SECRET;
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$APPID."&secret=".$SECRET."&js_code=".$code."&grant_type=authorization_code";
        $param=array();
        $res=curlget($url,$param,'POST');
        $res=json_decode($res,1);
        return $res;

    }
    public function AESencode($data) {
        $key=$this->APPID;
        $randstr=32-strlen($key);
        if($randstr>0)$key.=str_repeat("0",$randstr);
        $algorithm = MCRYPT_RIJNDAEL_128; // 加密算法
        $mode = MCRYPT_MODE_CBC; // 加密或解密的模式    
        $iv = mcrypt_create_iv(mcrypt_get_iv_size($algorithm, $mode), MCRYPT_RAND);
        $ciphertext = mcrypt_encrypt($algorithm, $key,$data, $mode, $iv);
        $ciphertext = $iv . $ciphertext;
        return base64_encode($ciphertext);# 对密文进行 base64 编码
    }
    public function AESdecode($data) {
        $key=$this->APPID;
        $randstr=32-strlen($key);
        if($randstr>0)$key.=str_repeat("0",$randstr);
        $algorithm = MCRYPT_RIJNDAEL_128; // 加密算法
        $mode = MCRYPT_MODE_CBC; // 加密或解密的模式    
        $iv_size = mcrypt_get_iv_size($algorithm, $mode);
        $ciphertext_dec = base64_decode($data);
        $iv_dec = substr($ciphertext_dec, 0, $iv_size);
        $ciphertext_dec = substr($ciphertext_dec, $iv_size);
        return mcrypt_decrypt($algorithm, $key,$ciphertext_dec, $mode, $iv_dec);
    }

    /**
     * 登录验证
     * @param array $data 登录数据
     * @return array
     */
    public function dologin($param) {//登录
        $return = array('status'=>3,'msg'=>'参数错误');
        $code = $param['js_code'];
        $salt = 'HANCHAO';

        if(empty($param['is_true'])) {
            if(empty($code))return $return;
            $result = $this->get_wxinfo($code);
        }else{
            $map=array();
            $map['id']=$param['id'];
            $result=M("Member")->where($map)->field(true)->find();
            if(!empty($result)){
                $result['session_key']=$result['wxsmall_session_key'];
                $result['unionid']=$result['wx_unionid'];
                $result['openid']=$result['wxsmall_openid'];
            }
            if(empty($result['session_key'])){
                $result['session_key']=$param['session_key'];
            }
        }
        if(empty($result['openid'])){
            $return['msg']="登录超时，请重试";
            return $return;
        }
        if(!isset($result['unionid'])){//未关注公众号，使用解析加密串的方式获取unionid
            $pc = new  \Common\Vendor\WxsmalldataCrypt($this->APPID, $result['session_key']);
            $errCode = $pc->decryptData($param['encryptedData'], $param['iv'], $data );
            if ($errCode == 0) {
                $data = json_decode($data,true);
                $result['unionid'] = $data['unionId'];
                if(empty($result['openid'])){
                    $result['openid'] = $data['openId'];
                }
            }
        }
        $map = $savedata = $res = $count= array();
        $invite_key = '';
        $this->model = M('Member');
        if(isset($result['session_key'])&&isset($result['openid'])){
            $map = array();
            /* if($result['unionid']){
                 $map['openid'] = $result['unionid'];
                 $lock_to_id =  M('OauthMember')->where($map)->getField('lock_to_id');
                 $map = array();
                 if($lock_to_id>0){
                     $map['id'] = $lock_to_id;
                 }
             }*/
            if($param['id']){
                $map['id'] = $param['id'];
            }elseif($result['unionid']) {
                $map['wx_unionid'] = $result['unionid'];
            }elseif($result['openid']) {
                $map['wxsmall_openid'] = $result['openid'];
            }
            $memberinfo = $this->model->where($map)->find();
            if (!empty($memberinfo)) {//更新会员session_key
                $savedata['login_count'] = array('exp', 'login_count+1');
                $savedata['last_login'] = NOW_TIME;
                $savedata['last_ip'] = get_client_ip(1);
                $savedata['wxsmall_session_key'] = $result['session_key'];
                $savedata['username'] = $param['nickName'];
                $savedata['nickname'] = $param['nickName'];
                $savedata['header_img'] = $param['avatarUrl'];
                $savedata['wx_unionid'] = $result['unionid'];

                if (empty($memberinfo['wxsmall_openid'])) {
                    $savedata['wxsmall_openid'] = $result['openid'];
                }
                $this->model->where($map)->save($savedata);
                $result['nickName'] = $param['nickName'];
                $result['avatarUrl'] = $param['avatarUrl'];
                $invite_key = $memberinfo['id'];
                //$sync= new \Common\Vendor\Syncmember;$sync->send_sync($memberinfo['id']);//执行会员同步 xiaogg 2019/8/31
            } else {//新增会员
                if ($param['invite_key']) $savedata['parent_id'] = intval(base64_decode($param['invite_key']));
                /* if ($savedata['parent_id']) TooKeenAward('', 1, 'bean', $savedata['parent_id']);*///新增粉丝给推荐人奖励
                $savedata['username'] = $param['nickName'];
                $savedata['nickname'] = $param['nickName'];
                $savedata['avatars'] = $param['avatarUrl'];
                $savedata['reg_time'] = $savedata['last_login'] = NOW_TIME;
                $savedata['reg_ip'] = $savedata['last_ip'] = get_client_ip(1);
                $savedata['wxsmall_session_key'] = $result['session_key'];
                $savedata['wxsmall_openid'] = $result['openid'];
                $savedata['wx_unionid'] = $result['unionid'];
                $savedata['rank_id'] = 1;
                $savedata['status'] = 1;
                $res = $this->model->add($savedata);
                if($param['invite_key'] && $res!==false){
                    TooKeenAward('',1,'bean',$savedata['parent_id']);//新增粉丝给推荐人奖励
                }
                $invite_key = $res;
                $result['nickName'] = $param['nickName'];
                $result['avatarUrl'] = $param['avatarUrl'];
                //$sync= new \Common\Vendor\Syncmember;$sync->send_sync($res);//执行会员同步 xiaogg 2019/8/31
            }
            //记录到第三方会员表
            $result['is_new']=$param['is_new'];
            $this->saveoauthmember($result);
            //end
        } else {
            $return['errcode'] = $result['errcode'];
            $return['msg'] = $result['errmsg'];
            $return['code'] = $code;
            return $return;
        }
        if ($res !== false) {
            $return['status'] = 1;
            $return['msg'] = '请求成功！';
            $return['data']['invite_key'] = base64_encode($invite_key);
            $return['data']['key'] = $this->creat_wxsmall_code($invite_key);
            $result['is_new']=$param['is_new'];
            $member_info = $this->get_member_info($result);
            if(!empty($param['extappid'])){
                $SUBMIT_DATA = unserialize(getconfig('WXSMALL_SUBMIT_DATA'));
                if(!empty($SUBMIT_DATA[$param['extappid']]['QQMap_key']))$member_info['data']['QQMap_key']=$SUBMIT_DATA[$param['extappid']]['QQMap_key'];
            }
            $return['data']['member_info'] = $member_info['data'];
            $return['data']['lshop_id'] = $this->get_lshop_id($invite_key,$param['lshop_id']);
        }

        return $return;

    }

    /**根据openid找会员信息
     * @param $param
     * @return array
     */
    public function get_member_info($param){
        $return=array('status'=>3,'msg'=>'参数错误');
        $key=$param['open_key'];
        if(empty($param)) return $return;
        $map=array();
        $map['wxsmall_openid'] = $param['openid'];
        $map['wx_unionid'] = $param['unionid'];
        $map['_logic'] = 'OR';
        $member=M("Member")->where($map)->field(true)->find();
        if(empty($member['username'])){$member['username']=' ';}
        if(empty($member['nickname'])){$member['nickname']=' ';}
        if($member){
            $return['data']=$member;
        }
        return $return;
    }
    /**
     * 记录到第三方会员表
     * @param param 回调数据
     * @return string
     */
    public function saveoauthmember($param) {
        $map = array();
        $map['wxsmall_openid'] = $param['openid'];
        $map['wx_unionid'] = $param['unionid'];
        $map['_logic'] = 'OR';
        $memberinfo = M('Member')->where($map)->field(true)->find();
        $OMember = M('OauthMember');$ipid=get_client_ip(1);
        $id=$memberinfo['id'];
        $res=$OMember->where("`openid`='".$param['unionid']."'")->field('login_times')->find();
        $login_times=$res['login_times'];
        if($login_times){
            $data = array(
                'last_login_time'	 => NOW_TIME,
                'last_login_ip'		 => $ipid,
                'login_times'		 => array('exp', 'login_times+1'),
                '_name'				 => $param['nickName'],
                'head_img'			 => $param['avatarUrl'],
            );
            $OMember->where("`_from`='wxsmall' AND `openid`='".$param['unionid']."'")->save($data);
        }else{
            $data = array(
                '_from'				 => 'wxsmall',
                '_name'				 => $param['nickName'],
                'head_img'			 => $param['avatarUrl'],
                'create_time'		 => NOW_TIME,
                'lock_to_id'		 => $id?$id:0,
                'last_login_time'	 => NOW_TIME,
                'last_login_ip'		 => $ipid,
                'login_times'		 => 1,
                'status'			 => 1,
                'access_token'		 => 0,
                'expires_date'		 => 0,
                'openid'			 => $param['unionid'],
            );
            $OMember->add($data);
        }
    }

    /**
     * 生成会员登录信息
     * @param string $uid 会员id
     * @return string
     */
    public function creat_wxsmall_code($uid) {
        return $this->AESencode($uid.'_'.(NOW_TIME+$this->config['sessiontime']));
    }
    /**
     * 校验当前登录标识是否有效
     * @param array $param 登录信息
     * @return array
     */
    public function check_wxsmall_code($param) {
        $code = $param['HCtoken'];
        $return = array('status'=>3,'msg'=>'登录信息失效，请重新登录');
        $str = $this->AESdecode($code);
        $checkarr = explode('_',$str);
        if(count($checkarr)==2){//检验位数
            $map = array();
            $map['id'] = $checkarr[0];
            if($checkarr[1]>NOW_TIME){
                $return['status'] = 1;
                $return['uid'] = $checkarr[0];
                $savedata['try_login_count'] = 0;//初始化异常次数
                M('Member')->where($map)->save($savedata);
                unset($return['msg']);
                if(!isset($param['HCshopid'])||$param['HCshopid']==0){
                    $result = $this->bind_shop(array('uid'=>$checkarr[0]));
                    if($result['status']==1){
                        $return['code'] = 'bind_shop_success';
                        $return['bind_shop_id'] = $result['data']['id'];
                        $return['send'] = $result['send'];
                        $return['location_n'] = $result['location_n'];
                    }else{
                        $return['code'] = 'bind_shop_error';
                    }
                }elseif($param['HCshopid']>0&&$param['HCtemp']!=1){//由于当前HCshopid是临时缓存，需重新定位匹配门店
                    $return['code'] = 'bind_shop_error';
                }
            }else{
                $try_login_count = idtoname($checkarr[0],'Member','try_login_count','id',false);
                if($try_login_count>=$this->config['try_count']){
                    $return['code'] = 'errorLogin';//账号异常登录
                }else{
                    $savedata['try_login_count'] = array('exp', 'try_login_count+1');//异常次数+1
                    M('Member')->where($map)->save($savedata);
                    $return['code'] = 'reLogin';//使小程序自动拉取会员授权信息，重新登录
                }
            }
        }
        return $return;
    }
    /**
     * 给当前用户默认绑定门店
     * @param array $param 当前用户信息
     * @return array
     */
    public function bind_shop($param=array()) {
        $return = array('status'=>3,'msg'=>'附近无可配送的门店');
        if(isset($param['uid'])&&$param['uid']>0){
            $map = array();
            $map['uid'] = $param['uid'];
            $data = M('MemberAddress')->where($map)->order('status desc,id desc')->field('xpoint,ypoint,address')->find();
            if($data&&$data['xpoint']&&$data['ypoint']){
                $result = $this->bind_shop_param($data['xpoint'],$data['ypoint']);
                $newarr = $this->judge_shop($data['xpoint'],$data['ypoint'],$result['data']['id']);
                $result['send'] = $newarr['status']==1?$newarr['send']:0;
                $result['location_n'] = $data['address'];//匹配地址
                return $result;
            }
        }
        if(isset($param['xpoint'],$param['ypoint'])&&$param['xpoint']>0&&$param['ypoint']>0){
            $result = $this->bind_shop_param($param['xpoint'],$param['ypoint']);
            $newarr = $this->judge_shop($data['xpoint'],$data['ypoint'],$result['data']['id']);
            $result['send'] = $newarr['status']==1?$newarr['send']:0;
            return $result;
        }
        return $return;
    }

    /**
     * 给当前用户默认绑定门店
     * @param float $lng 经度 对应xpoint
     * @param float $lat 纬度 对应ypoint
     * @param float $type 返回类型 0匹配到的一个门店 1匹配到的门店列表
     * @return array 匹配到可送达的门店信息
     */
    public function bind_shop_param($xpoint=0,$ypoint=0,$type=0){
        $return  = array('status'=>3);
        if(empty($xpoint)||empty($ypoint)){
            return $return;
        }
        //获取同城
        $city_shop=$this->get_city_shop($xpoint,$ypoint,$type);
        //获取快递
        $express_shop=$this->get_express_shop($xpoint,$ypoint,$type);
        if($type>0){
            if($express_shop && $city_shop) {
                foreach ($express_shop as $key => $val) {
                    foreach ($city_shop as $k => $v) {
                        if ($val['id'] == $v['id']) {
                            unset($express_shop[$key]);
                        }
                    }
                }
                $return['status'] = 1;
                $return['data'] = array_merge($city_shop, $express_shop);
            }elseif(empty($express_shop) && $city_shop){
                $return['status'] = 1;
                $return['data'] =$city_shop;
            }elseif(empty($city_shop) && $express_shop){
                $return['status'] = 1;
                $return['data'] =$express_shop;
            }
        }else{
            if($city_shop){
                $return['status'] = 1;
                $return['data'] = $city_shop;
            }elseif($express_shop){
                $return['status'] = 1;
                $return['data'] = $express_shop;
            }
        }
        /*$pi = PI();  //圆周率
		$r = 6378137;  //地球平均半径(米)
        $field_str = "(ACOS(SIN(($ypoint * $pi)/180)*SIN((s.ypoint*$pi)/180 )+COS(($ypoint*$pi)/180 )* COS((s.ypoint*$pi)/180)*COS(($xpoint*$pi)/180-(s.xpoint*$pi)/180))*$r)/1000";
        
        $field = array("s.id",$field_str=>"distance");
        $join = 'LEFT JOIN __SHOPS__ s ON s.id=sd.shop_id AND sd.scale>'.$field_str;
        $map = array();
		$map['s.status'] = 1;
        $result = M('ShopsDelivery')->alias('sd')->where($map)->join($join)->order('distance asc')->field($field)->select();
        if($result){
//            去掉重复的门店
            $new_id=array();
            foreach($result as $k=>$v){
                $new_id[]=$v['id'];
            }

            // 获取去掉重复数据的数组
            $unique_arr = array_unique ($new_id);
            // 获取去掉重复数据的数组
            $repeat_arr = array_diff_assoc ($new_id,$unique_arr);
            foreach($repeat_arr as $kk=>$vv){
                unset($result[$kk]);
            }
//            去掉重复的门店
            $return['status'] = 1;
            $return['data'] = $type==1?$result:$result[0];
        }else{
            //无同城配送的门店后走快递接口
            $results = $this->bind_shop_fee($xpoint,$ypoint);
            // 去掉重复的门店
            $new_id=array();
            foreach($results['data'] as $k=>$v){
                $new_id[]=$v['id'];
            }

            // 获取去掉重复数据的数组
            $unique_arr = array_unique ($new_id);
            // 获取去掉重复数据的数组
            $repeat_arr = array_diff_assoc ($new_id,$unique_arr);
            foreach($repeat_arr as $kk=>$vv){
                unset($results['data'][$kk]);
            }
//            去掉重复的门店
            if($results['status'] == 1){
                $return['status'] = 1;
                $return['data'] = $type==1?$results['data']:$results['data'][0];
            }
        }*/
        return $return;
    }

    /**获取同城的门店
     * @param $xpoint
     * @param $ypoint
     * @param $type
     * @return array
     */
    public function get_city_shop($xpoint=0,$ypoint=0,$type=0){
        if(empty($xpoint)||empty($ypoint)){
            return false;
        }
        $pi = PI();  //圆周率
        $r = 6378137;  //地球平均半径(米)
        $field_str = "(ACOS(SIN(($ypoint * $pi)/180)*SIN((s.ypoint*$pi)/180 )+COS(($ypoint*$pi)/180 )* COS((s.ypoint*$pi)/180)*COS(($xpoint*$pi)/180-(s.xpoint*$pi)/180))*$r)/1000";

        $field = array("s.id",$field_str=>"distance");
        $join = 'LEFT JOIN __SHOPS__ s ON s.id=sd.shop_id AND sd.scale>'.$field_str;
        $map = array();
        $map['s.status'] = 1;
        $result = M('ShopsDelivery')->alias('sd')->where($map)->join($join)->order('distance asc')->field($field)->select();
//            去掉重复的门店
        $new_id=array();
        foreach($result as $k=>$v){
            $new_id[]=$v['id'];
        }

        // 获取去掉重复数据的数组
        $unique_arr = array_unique ($new_id);
        // 获取去掉重复数据的数组
        $repeat_arr = array_diff_assoc ($new_id,$unique_arr);
        foreach($repeat_arr as $kk=>$vv){
            unset($result[$kk]);
        }
        $data= $type==1?$result:$result[0];
        return $data;
    }

    /**获取快递的门店（无同城配送的门店后走快递接口）
     * @param $xpoint
     * @param $ypoint
     * @param $type
     */
    public function get_express_shop($xpoint=0,$ypoint=0,$type=0){
        if(empty($xpoint)||empty($ypoint)){
            return false;
        }
        $results = $this->bind_shop_fee($xpoint,$ypoint);
        // 去掉重复的门店
        $new_id=array();
        foreach($results['data'] as $k=>$v){
            $new_id[]=$v['id'];
        }

        // 获取去掉重复数据的数组
        $unique_arr = array_unique ($new_id);
        // 获取去掉重复数据的数组
        $repeat_arr = array_diff_assoc ($new_id,$unique_arr);
        foreach($repeat_arr as $kk=>$vv){
            unset($results['data'][$kk]);
        }
//            去掉重复的门店
        if($results['status'] == 1){
            $data = $type==1?$results['data']:$results['data'][0];
        }
        return $data;
    }
    /**
     * 判断所传坐标是否为同城还是快递
     * @param float $lng 经度 对应xpoint
     * @param float $lat 纬度 对应ypoint
     * @param float $shop_id 门店ID
     * @return array 返回是同城配送还是快递配送
     */
    public function judge_shop($xpoint=0,$ypoint=0,$shop_id=0){
        $return  = array('status'=>3);
        if(empty($xpoint)||empty($ypoint)){
            return $return;
        }
        $pi = PI();  //圆周率
        $r = 6378137;  //地球平均半径(米)
        $field_str = "(ACOS(SIN(($ypoint * $pi)/180)*SIN((s.ypoint*$pi)/180 )+COS(($ypoint*$pi)/180 )* COS((s.ypoint*$pi)/180)*COS(($xpoint*$pi)/180-(s.xpoint*$pi)/180))*$r)/1000";

        $field = array("s.id",$field_str=>"distance");
        $join = 'LEFT JOIN __SHOPS__ s ON s.id=sd.shop_id AND sd.scale>'.$field_str;
        $map = array();
        $map['s.status'] = 1;
        $result = M('ShopsDelivery')->alias('sd')->where($map)->join($join)->order('distance asc')->field($field)->select();
        if($result){
            $ids = i_array_column($result,'id');
            if(in_array($shop_id,$ids)){
                $return['status'] = 1;
                $return['send'] = 1;
            }else{
                $results = $this->bind_shop_fee($xpoint,$ypoint);
                $ids = i_array_column($results['data'],'id');
                if(in_array($shop_id,$ids)){
                    $return['status'] = 1;
                    $return['send'] = 2;
                }
            }
        }else{
            $results = $this->bind_shop_fee($xpoint,$ypoint);
            $ids = i_array_column($results['data'],'id');
            if(in_array($shop_id,$ids)){
                $return['status'] = 1;
                $return['send'] = 2;
            }
        }
        return $return;
    }
    /**
     * 快递接口
     * @param float $lng 经度 对应xpoint
     * @param float $lat 纬度 对应ypoint
     * @return array 匹配到可送达的门店信息
     */
    public function bind_shop_fee($xpoint=0,$ypoint=0){
        $return = array('status'=>3);
        $param = array();
        $param['xpoint'] = $xpoint;
        $param['ypoint'] = $ypoint;
        $geodata = D('Common/Area')->geocoding($param);
        $cityname = $geodata['result']['addressComponent']['city'];
        if($cityname){
            $city=strlen($cityname)>6?strtr($cityname,array('省'=>'','市'=>'','县'=>'','区'=>'','自治区'=>'',)):$cityname;
            $map=array();
            $map['status']=1;
            $map['name']=array('like','%'.$city.'%');
        $city_info=M('Area')->where($map)->field('id,pid,name')->cache(true)->find();
            $city_id=$city_info['id'];
            if($city_id){//定位到城市
                $field = array("sf.*");
//                $join = 'LEFT JOIN __SHIPPING_FEE__ sf ON s.id=sf.shop_id AND s.city_id='.$city_id;
                $join = 'LEFT JOIN __SHIPPING_FEE__ sf ON s.id=sf.shop_id';
                $map = array();
                $map['s.status'] = 1;
                $shop_shipinfo = M('Shops')->alias('s')->where($map)->join($join)->field($field)->select();
                if($shop_shipinfo){
                    $i = 0;
                    foreach($shop_shipinfo as $k=>$v){
                        $area_ids =array_unique(array_filter(explode(',',$v['area_region'])));
                        if(in_array($city_id, $area_ids) || in_array($city_info['pid'], $area_ids)){
                            $return['status'] = 1;
                            $return['data'][$i]['id'] = $v['shop_id'];
                            $i++;
                        }
                    }
					
                }
            }
        }
		//2019.06.25 start
		if(empty($return['data'])){
			$return['status'] = 1;
			$return['data'][0]['id'] = 1;
		}
		//2019.06.25 end
        return $return;
    }
    /**
     * 用定位信息给当前用户匹配门店
     * @param float $param 经,纬度信息 对应xpoint，ypoint
     * @return array 匹配到可送达的门店信息
     */
    public function setshopid($param=array()){
        $return  = array('status'=>3);
        if(empty($param['xpoint'])||empty($param['ypoint'])){
            // 4-3 zjn
            $ip = get_client_ip();
            $ak = C('BAIDU_WEB_KEY');
            $url = file_get_contents("http://api.map.baidu.com/location/ip?ip=$ip&ak=$ak");
            $data = json_decode($url,true);
            if($data){
                $param['xpoint']=$data['content']['point']['x'];
                $param['ypoint']=$data['content']['point']['y'];
            }
            // ----end-----
        }
        if(empty($param['xpoint'])||empty($param['ypoint'])){
            return $return;
        }
        $point = $this->Convert_GCJ02_To_BD09($param['ypoint'],$param['xpoint']);
        $result = $this->bind_shop_param($point['lng'],$point['lat']);
        $newarr = $this->judge_shop($point['lng'],$point['lat'],$result['data']['id']);
        if($result['status']==1){
            $return['status'] = 1;
            $return['bind_shop_id'] = $result['data']['id'];
            $return['send'] = $newarr['status']==1?$newarr['send']:0;
        }
        return $return;
    }
    /*
    * 中国正常GCJ02坐标---->百度地图BD09坐标
    * 腾讯地图用的也是GCJ02坐标
    * @param double $lat 纬度
    * @param double $lng 经度
    */

    public function Convert_GCJ02_To_BD09($lat,$lng){
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $lng;
        $y = $lat;
        $z =sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) + 0.000003 * cos($x * $x_pi);
        $lng = $z * cos($theta) + 0.0065;
        $lat = $z * sin($theta) + 0.006;
        return array('lng'=>$lng,'lat'=>$lat);
    }
    /*
    * 百度地图BD09坐标---->中国正常GCJ02坐标
    * 腾讯地图用的也是GCJ02坐标
    * @param double $lat 纬度
    * @param double $lng 经度
    * @return array();
    */
    public function Convert_BD09_To_GCJ02($lat,$lng){
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $lng - 0.0065;
        $y = $lat - 0.006;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $lng = $z * cos($theta);
        $lat = $z * sin($theta);
        return array('lng'=>$lng,'lat'=>$lat);
    }
    /**
     * aes解密会员数据
     * @param 会员信息
     */
    public function datacrypt($param){
        $return = array('status' => 3,'msg'=>'参数错误');
        $appid = $this->APPID;
        if(empty($param['encryptedData'])||empty($param['iv'])||empty($param['uid'])){
            return $return;
        }
        $sessionKey = idtoname($param['uid'],'Member','wxsmall_session_key','id',false);
        $encryptedData=$param['encryptedData'];
        $iv = $param['iv'];
        $pc = new  \Common\Vendor\WxsmalldataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $return['status'] = 1;
            $return['data'] = json_decode($data,true);
        }
        return $return;
    }
    /*
    * $uid 会员id $lshop_id 小店id
    */
    public function get_lshop_id($uid,$lshop_id=0){
        if(!$uid) return false;
        if($lshop_id) return $lshop_id;
        $user_shop_id = intval(idtoname($uid,'LittleShop','id','uid',false));
        if($user_shop_id) return $user_shop_id;
        $parent_id = intval(idtoname($uid,'Member','parent_id'));
        $parent_shop_id = intval(idtoname($parent_id,'LittleShop','id','uid',false));
        if($parent_shop_id) return $parent_shop_id;
        return false;
    }
}
