<?php
namespace Api\Controller;

use Think\Controller;
use Think\Exception;
use Think\Log;

header("Content-Type:text/html;CharSet=UTF-8");
class ApiController extends Controller
{


    /**
     * 保存用户信息
     */
    public function updateUserInfo()
    {
        if (!$_GET['openid'] || $_GET['openid'] == "null" || $_GET['openid'] == "undefined") {
            $data = array(
                "status" => -1,
                "msg" => "openid 有误"
            );
        } elseif (!$_GET['userInfo'] || $_GET['userInfo'] == "null" || $_GET['userInfo'] == "undefined") {
            $data = array(
                "status" => -1,
                "msg" => "userInfo 有误"
            );
        } else {
            $info = D("Users")->updateUserInfo();
            if (!$info['live_place']) {
                // 用户未绑定地区
                $info['live_place'] = 0;
            }
            $region_list = $this->regionList();
            $data = array(
                "status" => 1,
                "result" => array(
                    "live_place" => $info['live_place'],
                    "village_id" => $info['village_id'],
                    "county_id" => $info['county_id'],
                    "city_id" => $info['city_id'],
                    "province_id" => $info['province_id'],
                    "identity" => $info['identity']
                )
            );
            if ($info['village_id']) {
                // 返回村名
                $data['result']['village'] = M("regionVillage")->where("`id`={$info['village_id']}")->getField("name");
            }
            if ($info['county_id']) {
                // 返回县名
                $data['result']['county'] = M("regionCounty")->where("`id`={$info['county_id']}")->getField("name");
            }
            if ($info['city_id']) {
                // 返回市名
                $data['result']['city'] = M("regionCity")->where("`id`={$info['city_id']}")->getField("name");
            }
            if ($info['province_id']) {
                // 返回省名
                $data['result']['province'] = M("regionProvince")->where("`id`={$info['province_id']}")->getField("name");
            }
            if ($region_list) {
                // 返回地区 树状数组 & 独立数组
                $data['region_list'] = $region_list['region_list'];
                $data['provinceArr'] = $region_list['provinceArr'];
                $data['cityArr'] = $region_list['cityArr'];
                $data['countyArr'] = $region_list['countyArr'];
                $data['villageArr'] = $region_list['villageArr'];
            }
        }
        apiReturn($data);
    }

    /**
     * 获取地区列表
     */
    public function getRegionList()
    {
        $data = $this->regionList();
        apiReturn($data);
    }

    /**
     * 更改用户地区  用于控制器
     */
    public function updateRegion()
    {
        $bool_1 = $_GET['openid'] && $_GET['openid'] != "null" && $_GET['openid'] != "null";
        $bool_2 = $_GET['province_id'] && $_GET['province_id'] != "null" && $_GET['province_id'] != "null";
        $bool_3 = $_GET['city_id'] && $_GET['city_id'] != "null" && $_GET['city_id'] != "null";
        $bool_4 = $_GET['county_id'] && $_GET['county_id'] != "null" && $_GET['county_id'] != "null";
        $bool_5 = $_GET['village_id'] && $_GET['village_id'] != "null" && $_GET['village_id'] != "null";
        $bool_6 = $_GET['live_place'] && $_GET['live_place'] != "null" && $_GET['live_place'] != "null";
        if (!$bool_1) {
            $data = array("status" => -1, "msg" => "openid有误");
        } elseif (!$bool_2) {
            $data = array("status" => -1, "msg" => "省ID有误");
        } elseif (!$bool_3) {
            $data = array("status" => -1, "msg" => "市ID有误");
        } elseif (!$bool_4) {
            $data = array("status" => -1, "msg" => "县/区ID有误");
        } elseif (!$bool_5) {
            $data = array("status" => -1, "msg" => "村/小区有误");
        } elseif (!bool_6) {
            $data = array("status" => -1, "msg" => "live_place有误");
        } else {
            $result = D("Users")->updateRegion();
            if ($result) {
                $data = array("status" => 1, "msg" => "操作成功");
            } else {
                $data = array("status" => 2, "msg" => "连接成功");
            }
        }
        apiReturn($data);
    }

    /**
     * 地区列表
     */
    public function regionList()
    {
        $result = M("regionProvince")
            ->join("p INNER JOIN `am_region_city` city ON p.`id`=city.`province_id`")
            ->join("`am_region_county` county ON city.`id`=county.`city_id`")
            ->join("`am_region_village` v ON county.`id`=v.`county_id`")
            ->order("p.`sort` ASC,city.`sort` ASC,county.`sort` ASC")
            ->field("p.`name` AS `province`,city.`province_id`,city.`name` AS `city`,county.`city_id`,county.`name` AS `county`,county.`id` AS `county_id`,v.`name` AS `village`,v.`id` AS `village_id`,v.`type`")
            ->select();
        $villageArr = $countyArr = $cityArr = $provinceArr = array();
        // 把 村、县、市、省 组成独立数组
        foreach ($result as $key => $value) {
            // 村数组
            if ($value['village_id']) {
                array_push(
                    $villageArr,
                    array(
                        "village" => $value['village'],
                        "id" => $value['village_id'],
                        "county_id" => $value['county_id'],
                        "type" => $value['type']
                    )
                );
            }
            // 县数组
            $array = array(
                "county" => $value['county'],
                "id" => $value['county_id'],
                "city_id" => $value['city_id']
            );
            if (!in_array($array, $countyArr)) {
                array_push($countyArr, $array);
            }
            // 城市数组
            $array = array(
                "city" => $value['city'],
                "id" => $value['city_id'],
                "province_id" => $value['province_id']
            );
            if (!in_array($array, $cityArr)) {
                array_push($cityArr, $array);
            }
            // 省数组
            $array = array(
                "province" => $value['province'],
                "id" => $value['province_id']
            );
            if (!in_array($array, $provinceArr)) {
                array_push($provinceArr, $array);
            }
        }
        $data = array(
            "provinceArr" => $provinceArr,    // 纯粹的省数组
            "villageArr" => $villageArr,
            "countyArr" => $countyArr,
            "cityArr" => $cityArr
        );
        unset($key, $value, $result);
        // 把 村数组 放入 县数组
        foreach ($countyArr as $kc => $vc) {
            $countyArr[$kc]['village_list'] = array();
            foreach ($villageArr as $kv => $vv) {
                if ($vv['county_id'] == $vc['id']) {
                    array_push(
                        $countyArr[$kc]['village_list'],
                        $vv
                    );
                }
            }
            unset($kv, $vv);
        }
        unset($kc, $vc);
        // 把 新的县数组 放入 城市数组
        foreach ($cityArr as $kCity => $vCity) {
            $cityArr[$kCity]['county_list'] = array();
            foreach ($countyArr as $kCounty => $vCounty) {
                if ($vCounty['city_id'] == $vCity['id']) {
                    array_push(
                        $cityArr[$kCity]['county_list'],
                        $vCounty
                    );
                }
            }
            unset($kCounty, $vCounty);
        }
        unset($kCity, $vCity);
        // 把 新的城市数组 放入 省数组
        foreach ($provinceArr as $kp => $vp) {
            $provinceArr[$kp]['city_list'] = array();
            foreach ($cityArr as $kc => $vc) {
                if ($vc['province_id'] == $vp['id']) {
                    array_push(
                        $provinceArr[$kp]['city_list'],
                        $vc
                    );
                }
            }
            unset($kc, $vc);
        }
        unset($kp, $vp);
        // 返回组装好的新的省数组
        $data['region_list'] = $provinceArr;
        return $data;
    }

    /**
     * 上传图片
     */
    public function imgUpload()
    {
        if ($_FILES['file']['error'] != 4) {
            $upload = new \Think\Upload();    // 实例化上传类    
            // $upload->maxSize = 3145728 ;    // 设置附件上传大小 
            // 设置附件上传类型       
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->rootPath = './Uploads/';    // 设置附件上传根目录 
            $upload->savePath = 'microProgram/file/';    // 设置附件上传目录  
            $upload->autoSub = true;    // 要子文件夹
            // 上传文件
            $info = $upload->upload();
            if($info) {
                // 上传成功 获取上传文件信息
                $pic = $info['file']["savepath"] . $info['file']["savename"];
                $data = $pic;
                file_put_contents("./Logs/imgUploadSuccess.log", serialize($data) . "\r\n" . serialize($info) . "\r\n" . serialize($upload));
            } else {
                file_put_contents("./Logs/imgUpload.log", serialize($info) . "\r\n" . serialize($upload) . "\r\n\r\n", FILE_APPEND);
                file_put_contents("./Logs/imgUpload.log", $upload->getError() . "\r\n\r\n", FILE_APPEND);
            }
        }
        echo $data;
    }

    /**
     * 获取错误信息
     */
    public function errorLog()
    {
        $log = date("Y-m-d H:i:s ") . json_encode($_GET) . "\r\n";
        file_put_contents("./Logs/errorLog.log", $log, FILE_APPEND);
    }


    /**
     *获取openid
     */
    public function getOpenID($admin)
    {
        $Config=M('wechat_config');
        $result = $Config->where('admin=1'.$admin)->find();
        $code=I("code");//获取code
        $weixin=file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$result['appid']."&secret=".$result['appsecret']."&code=".$code."&grant_type=authorization_code");//通过code换取网页授权access_token
        $jsondecode=json_decode($weixin);
        //对JSON格式的字符串进行编码
        $array=get_object_vars($jsondecode);//转换成数组
        echo json($array);

    }

    /**
     * 用户信息
     * @param $openid
     */
    public function getUserinfo(){

        $result=$_REQUEST;
        $openid=$_REQUEST['openid'];
        $admin_id=$_REQUEST['admin_id'];
        $data_['openid']=$openid;
        $data_['admin_id']=$admin_id;

        $user=M('wx_users')->where($data_)->select();

        if(count($user)>0){exit(json($user));}
//            dump($data_);
        $data['openid']=$result['openid'];
        $data['nickname']=$result['nickname'];
        $data['headimgurl']=$result['headimgurl'];
        M('wx_users')->where($data_)->add($data);
        $user_=M('wx_users')->where($data_)->find();
        exit (json($user_));

    }
    public function curlGet($url)
    {
        // 使用 curl_init()函数初始化一个CURL会话，初始化成功后返回一个句柄供curl_setopt(), curl_exec(),和 curl_close() 函数使用
        $curl = curl_init();
        // 使用curl_setopt()设置要获取的URL地址
        curl_setopt($curl, CURLOPT_URL, $url);
        // 设置是否输出header 设为0 否则影响输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 设置是否输出结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 设置是否输出结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 设置是否检查服务器端的证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量
        $data = curl_exec($curl);
        // 使用 curl_close() 关闭CURL会话
        curl_close($curl);
        return $data;
    }
    /**
     * 支付
     * @param int $order_id  订单编号
     * @return array
     */
    public function payMoney($order_num){
        try{
            $Order=M('order');
            $Users=M('users');
            $order=$Order->where("order_sn=".$order_num)->find();

            $users=$Users->where('id='.$order['uid'])->find();
            $admin_id=$order['admin_id'];
            $openid=$users['openid'];
            $out_trade_no=$order_num;
            $prepayid=$order['result'];
            if($prepayid!=""||$prepayid!=null){ echo json_decode(json($prepayid), 200);exit ;}
            if($openid==""||$openid==""){ echo json_encode(array('code' => '404', 'info' => '用户未绑定微信号!'));exit ;}
            $notify_url='https://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'], '/')+1)."paysuccess";
            // 实例支付接口
            // 多门店处理,如果parent_id不等于0，获取父级id的微信配置参数
            $parent_id = M('admin')->where(array('id' => $admin_id))->getField('parent_id');
            if (!empty($parent_id)) {
                $pay = & load_wechat('Pay',$parent_id);  
            } else {
                $pay = & load_wechat('Pay',$admin_id);  
            }
            
            // 获取预支付ID
//        $result = $pay->getPrepayId($user->open_id, $order->name, $out_trade_no, $order->price*100, $notify_url, $trade_type = "JSAPI");
            $result = $pay->getPrepayId($openid, $order['admin_title'], $out_trade_no, $order['price']*100, $notify_url, $trade_type = "JSAPI");

            // 处理创建结果
            if($result===FALSE){
                // 接口失败的处理
                echo json_encode(array('code' => '404', 'info' => '订单生成失败'.$pay->errMsg));die;
                // return json(['msg' => '支付失败'], 200);
            }else{
                $time="".time();
                $prepay_id='prepay_id='.$result['prepay_id'];
                // 多门店处理,如果parent_id不等于0，获取父级id的微信配置参数
                $parent_id = M('admin')->where(array('id' => $admin_id))->getField('parent_id');
                if (!empty($parent_id)) {
                    $result_ = M('wechat_config')->where('admin_id='.$parent_id)->field('partnerkey')->find();  
                } else {
                  $result_ = M('wechat_config')->where('admin_id='.$admin_id)->field('partnerkey')->find();  
                }
                $post="appId=".$result['appid']."&nonceStr=".$result['nonce_str']."&package=".$prepay_id."&signType=MD5&timeStamp=".$time."&key=".$result_['partnerkey'];
                $key=md5($post);
                $prepay_id='prepay_id='.$result['prepay_id'];
                $result=['appId'=>$result['appid'],'timeStamp'=>$time,'nonceStr'=>$result['nonce_str'],'package'=>$prepay_id,'signType'=>'MD5','paySign'=>$key];
                $Order->where("order_sn=".$order_num)->save(['result' => json_encode($result)]);
                echo json_encode($result, 200);
            }

        }catch (Exception $e){
            echo json_encode(array('code' => '404', 'info' => '参数错误',"order"=>$e->getMessage()));exit;
            // return json(['msg' => '参数错误',"order"=>$e->getMessage()], 200);
        }
    }

    public function test()
    {
        echo 111;
    }

    /**
     * 支付成功回调
     * @param $id
     * @param $tenant_id
     * @return \think\\Xml
     */
    public function paysuccess(){

        // 实例支付接口
        $pay = & load_wechat('Pay');

        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        Log::record('测试日志信息');
        Log::record($notifyInfo);

        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            Log::record($pay->errMsg);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                // 支付状态完全成功，可以更新订单的支付状态了
                $trade_no=$notifyInfo['out_trade_no'];
                $transaction_id=$notifyInfo['transaction_id'];
                $this->paychange($trade_no,$transaction_id);


                // @todo
                // 返回XML状态，至于XML数据可以自己生成，成功状态是必需要返回的。
                // <xml>
                //    return_code><![CDATA[SUCCESS]]></return_code>
                //    return_msg><![CDATA[OK]]></return_msg>
                // </xml>
                return xml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
            }
        }
    }

    /**
     * 修改订单状态
     * @param $trade_no
     * @param $transaction_id
     */
    public function paychange($trade_no,$transaction_id){
        $Order=M('order');
        $Goods=M('goods');
        $Car=M('car');
        $da['order_sn']=$trade_no;
        $da['status']=1;
        $order=$Order->where($da)->find();
        if(count($order)>0){
            $data['transaction_id']=$transaction_id;
            $data['order_sn']=$trade_no;
            $data['pay_time']=time();
            $data['status']=2;
            $Order->where('order_sn='.$trade_no)->save($data);
            $car=$Car->where('order_sn='.$trade_no)->find();
            $goods_id=unserialize($car['car_content']);
            foreach ($goods_id  as  $val){
                $Goods->where('id='.$val['goods_id'])->setInc('sales',$val['goods_num']);
            }
            // 增加用户积分
            $is_has_int = M('user_int')->where(array('user_id' => $order['uid']))->find();
            if ($is_has_int) {
                $int = M('user_int')->where(array('user_id' => $order['uid']))->getField('int');
                M('user_int')->where(array('user_id' => $order['uid']))->save(array('update_time' => time(), 'int' => $int + $order['int']));
            } else {
                M('user_int')->add(array('user_id' => $order['uid'], 'int' => $order['int'], 'create_time' => time()));
            }
            // 增加用户累计消费金额
            $is_has_money = M('user_money')->where(array('user_id' => $order['uid']))->find();
            if ($is_has_money) {
                $money = M('user_money')->where(array('user_id' => $order['uid']))->getField('money');
                M('user_money')->where(array('user_id' => $order['uid']))->save(array('update_time' => time(), 'money' => $money + $order['price']));
            } else {
                M('user_money')->add(array('user_id' => $order['uid'], 'money' => $order['price'], 'create_time' => time()));
            }
            $admin_id=$order['admin_id'];
            $this->content($admin_id,$trade_no);

        }




    }
    /**
     *
     */
    public  $http = 'http://www.open.mstching.com/home/';

    /**
     *
     */
    public function userbind(){
        $url =$this->http."userbind";
        $admin_id=13;
        $Print_=M('print');
        $print_=$Print_->where('admin_id='.$admin_id)->find();
        $post_data_=$this->signa();
        $post_data['Uuid']=$print_['uuid'];
        $post_data['UserId']=$admin_id;
        $res = $this->request_post($url,$ispost=true,$post_data,$post_data_);
        exit(json_decode(json_encode($res)));
    }

    public function statusbind(){
        $url =$this->http."getdevicestate";
        $admin_id=1;
        $Print_=M('print');
        $print_=$Print_->where('admin_id='.$admin_id)->find();
        $post_data_=$this->signa();
        $post_data['Uuid']=$print_['uuid'];
        $res = $this->request_post($url,$ispost=true,$post_data,$post_data_);
        exit(json_decode(json_encode($res)));
    }

    /**
     * 发送打印机内容
     */
    public function content($admin_id,$order_sn){
        $url =$this->http."printcontent2";
        $Print_=M('print');
        $Order=M('order');
        $Goods=M('goods');
        $Car=M('car');
        // $print_=$Print_->where('admin_id='.$admin_id)->find();
        $print_=$Print_->where('admin_id='.$admin_id)->select();
        if(count($print_)<1){}
        $order  =$Order->where('order_sn='.$order_sn)->find();
        $car=$Car->where('order_sn='.$order_sn)->find();
//        dump($order);
        $content=unserialize($car['car_content']);

        // $post_data_=$this->signa();
        // $post_data['Uuid']=$print_['uuid'];
        // $post_data['OpenUserId']=$print_['open_user_id'];
        $PrintContent='';
        $i='';
        $PrintContent.=$this->PrintContent(1,$order['admin_title'],1,1);
        $PrintContent.='@'.$this->PrintContent(0,'订单号：'.$order['order_sn'],1,0);
        if($order['order_type']==1){
            $i='外卖';
        }
        if($order['order_type']==2){
            $i='店内';
        }
        $PrintContent.='@'.$this->PrintContent(0,'桌号：'.$order['seat'].$i,0,0);
        $PrintContent.='@'.$this->PrintContent(0,'---------------菜品-------------',1,0);
        foreach ($content as $val){
            $goods=$Goods->where('id='.$val['goods_id'])->getField('title');
            $PrintContent.='@'.$this->PrintContent(0,$goods,0,0);
            $PrintContent.='@'.$this->PrintContent(0,$this->mingcheng('',12).'x'.$val['goods_num'].' '.$val['sum_price'],1,0);
        }
        $PrintContent.='@'.$this->PrintContent(0,''.$order['mark'],1,0);

        $PrintContent.='@'.$this->PrintContent(0,'--------------------------------',1,0);
        if($order['order_type']==1){
            $PrintContent.='@'.$this->PrintContent(0,'收货人:'.$order['address_name'],1,0);
            $PrintContent.='@'.$this->PrintContent(0,'联系电话:'.$order['address_phone'],1,0);
            $PrintContent.='@'.$this->PrintContent(0,'街道:'.$order['address_area'],1,0);
            $PrintContent.='@'.$this->PrintContent(0,'详细地址:'.$order['address_info'],1,0);
        }
        $PrintContent.='@'.$this->PrintContent(0,'合计：'.$this->mingcheng(''.$order['price'],8).'支付金额:'.$order['price'],1,0);
        $PrintContent.='@'.$this->PrintContent(0,'下单时间：'.date('Y-m-d H:i:s',time()),0,0);
        $PrintContent.='@'.$this->PrintContent(0,' ',0,0);
        $PrintContent.='@'.$this->PrintContent(1,'极速上线小程序提供技术支持',0,0);
        $PrintContent.='@'.$this->PrintContent(1,'--------------------------------',0,0);
        $hello = explode('@',$PrintContent);
        $array=array();
        foreach($hello as $k=>$v){
            $array[$k]=json_decode($hello[$k],true);
        }
        $PrintContents = json_encode($array);
//         $post_data['PrintContent']=$PrintContents;
// //        dump($post_data);
//         $res = $this->request_post($url,$ispost=true,$post_data,$post_data_);
        foreach ($print_ as $key => $value) {
            $post_data_=$this->signa();
            $post_data['Uuid']=$value['uuid'];
            $post_data['OpenUserId']=$value['open_user_id'];
            $post_data['PrintContent']=$PrintContents;
            $res[] = $this->request_post($url,$ispost=true,$post_data,$post_data_);
        }
        exit(json_decode(json_encode($res)));


    }

    function mingcheng($content,$shuliang)		//名称处理
    {
        $dingyic = $shuliang;				//定义长度
        $li = (string)$content;		//字符串化
        $long = mb_strlen($li,'UTF8');		//计算长度 ，一个中文三个字节
        $kongge = '';
        if($long>$dingyic)
        {
            // $substr = $dingyic-1;
            $res = mb_substr($li,0,$dingyic,'utf-8');
        }
        else
        {
            $nums = $dingyic-$long;
            for($i=0;$i<$nums;$i++)
            {
                $kongge.='  ';
            }
            $res = $li.$kongge;
        }
        return $res;
    }

    ///排版参数
    function PrintContent($Alignment=1,$BaseText,$Bold=0,$FontSize=0,$PrintType=0){

        $PrintContent =Array ( 'Alignment'=> $Alignment, 'BaseText' => base64_encode($this->charsetToGBK($BaseText)),'Bold' => $Bold, 'FontSize' =>$FontSize, 'PrintType' => $PrintType ) ;
        return json_encode($PrintContent);
    }
    //gbk格式
    function charsetToGBK($mixed)
    {
        if (is_array($mixed)) {
            foreach ($mixed as $k => $v) {
                if (is_array($v)) {
                    $mixed[$k] = $this->charsetToGBK($v);
                } else {
                    $encode = mb_detect_encoding($v, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
                    if ($encode == 'UTF-8') {
                        $mixed[$k] = iconv('UTF-8', 'GBK', $v);
                    }
                }
            }
        } else {
            $encode = mb_detect_encoding($mixed, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
            //var_dump($encode);
            if ($encode == 'UTF-8') {
                $mixed = iconv('UTF-8', 'GBK', $mixed);
            }
        }
        return $mixed;
    }

    public function tasksbind(){
        $url =$this->http."getprinttaskstate";
    }


    function randStr($len=9,$format='ALL') {
        switch($format) {
            case 'ALL':
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; break;
            case 'CHAR':
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
            case 'NUMBER':
                $chars='0123456789'; break;
            default :
                $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
                break;
        }
        mt_srand((double)microtime()*40400*getmypid());
        $password="";
        while(strlen($password)<$len)
            $password.=substr($chars,(mt_rand()%strlen($chars)),1);
        return $password;
    }

    /**
     * 签名
     * @return mixed
     */
    function signa(){

        $Print=M('print_config');
        $print=$Print->where('id=2')->find();
        $strs='';
        $params = array();
        $time=time();
        $nonce=$this->randStr();
        $param['nonce'] = strval($params['nonce'] = $nonce);//随机数
        $param['timestamp'] = strval($params['timestamp'] = $time);
        $params['appsecret'] = $print['app_secret'];
        $params['nonce'] = $param['nonce'];
        $params['timestamp'] = $param['timestamp'];
        asort($params,SORT_LOCALE_STRING );
        foreach($params as $kk=>$vv){
            $strs.=$vv;
        }
        $param['signature'] = sha1($strs);
        $post_data['appid']=$print['app_key'];
        $post_data['nonce']= $param['nonce'];
        $post_data['timestamp']=$param['timestamp'];
        $post_data['signature']=$param['signature'] ;
        return $post_data;
    }

    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    public function request_post($url = '',$ispost, $post_data = array(), $post_data_ = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }

        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $key=md5(base64_encode($post_data));
        if($ispost){
            $url=$url.'?appid='.$post_data_['appid'].'&nonce='.$post_data_['nonce'].'&timestamp='.$post_data_['timestamp'].'&signature='.$post_data_['signature'];

        }else{
            $url = $url.'?'.$post_data;
        }

        $curlPost = 'key='.$key;
        header("Content-type: text/html; charset=UTF-8");
        $ch = curl_init();//初始化curl
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
//        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if($ispost){
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * 获取商户经纬度
     */
    public function get_lnglat()
    {
        $data = I('post.');

        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $get_lnglat_info = M('admin')->where(array('admin_id' => $data['business_id']))->field('lnglat')->find();

        if (empty($get_lnglat_info)) apiReturn(['status' => -1, 'msg' => '无法获取经纬度']);
        
        $array = split(',', $get_lnglat_info['lnglat']);

        $return['lng'] = $array[0];
        $return['lat'] = $array[1];

        apiReturn(['status' => 1, 'msg' => '已获取经纬度', 'lnglat' => $return]);
    }
}