<?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 $dada;// 达达配送实例
    /**
     * 上传图片
     */
    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');
            $Goods = M("goods");
            $order=$Order->where("order_sn=".$order_num)->find();

            if ($order['status'] != '1') {
               $this->ajaxReturn(['code' => 200, 'info' => '扣款成功']);
            }

            $users=$Users->where('id='.$order['uid'])->find();
            $admin_id=$order['admin_id'];

            if ($order['pay_type'] == 1) { # 微信支付
                $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/a_id/".$admin_id;
                // 实例支付接口
                // 多门店处理,如果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);
                }
            } else { # 余额支付
                 $user_id = $order['uid'];
                 $user_balance = M('user_money')->where(array('user_id' => $user_id))->field('money, balance')->find();

                 // 检测用户余额
                 if ($user_balance['balance'] < $order['price']) $this->ajaxReturn(['code' => 404, 'info' => '余额不足！']);

                 // 扣款并添加累计消费
                 $balance_result = M('user_money')->where(array('user_id' => $user_id))->save(array('money' => $user_balance['money'] + $order['price'], 'balance' => $user_balance['balance'] - $order['price'], 'update_time' => time()));
                
                 if ($balance_result) {
                    $data['pay_time']=time();
                    $data['status']=2;
                    M('order')->where(array('id' => $order['id']))->save($data);
                    $car=M('car')->where('order_sn='.$order['order_sn'])->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()));
                    }   

                    // 分销，生成待反的佣金记录
                    $share_switch = ShareLogicController::check_share($order['admin_id']);
                    if ($share_switch == 1) {// 商户分销开关开启
                        // $user_share_status = ShareLogicController::check_user_share($order['uid']);
                        // if ($user_share_status == 1) { // 用户是分销员
                            ShareLogicController::create_share($order['order_sn'], $order['admin_id']);// 生成待返佣金记录
                        // }
                    }

                    $return = $this->get_dada_ie($order['admin_id']);// 获取达达实例
                    if ($return['code'] == 200 && !empty($order['deliveryNo'])) {
                       $this->dada->addAfterQuery(array('deliveryNo' => $order['deliveryNo']));// 查询运费后发单接口
                    }

                    $trade_no = $order_num;

                    //邮箱推送2018-6-20
                    //$sendorder=M('order')->where(array('id' => $order_id))->find();
                    if($order['order_type'] == 1){
                        D('Order') -> SendEmail($admin_id,$order);
                    }
                    
                    // 小票打印机打印订单
                    $this->content($admin_id,$trade_no);

                    $this->ajaxReturn(['code' => 200, 'info' => '扣款成功']);
                 } else {
                    $this->ajaxReturn(['code' => 404, 'info' => '扣款失败']);
                 }
            }   

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

    /**
     * [addDadaOrder 达达配送--下单]
     * @AuthorHTL
     * @DateTime  2018-03-26T13:17:05+0800
     */
    public function addDadaOrder($business_id, $order_sn)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         $this->ajaxReturn($return);
            // return $return;

        $business_info = M('admin')->where(array('id' => $business_id))->field('id, dada_origin_shop_id, business_address')->find();// 获取商户门店号、地址等信息

        $order = M('order')->where(array('order_sn' => $order_sn))->field('order_type, total_price, address_name, address_info, address_phone, address_area, mark, fachu_time')->find();

        if ($order['order_type'] == 1) {// 判断外卖订单
            $address_preg = '/([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)/';
            preg_match($address_preg, $order['address_area'], $matchs);
            $city = split('市', $matchs[2])[0];
            $cityCodeList = $this->dada->cityCodeList('');
            foreach ($cityCodeList as $key => $value) {
                if ($value['cityName'] == $city) {
                    $cityCode = $value['cityCode'];// 城市编号
                    break;
                }
             }

             Log::record('http://restapi.amap.com/v3/geocode/geo?address='.$city.'市'.$order['address_info'].'&output=JSON&key=aba29ed8b30acb4e334d526b3f278c6d');
            // 收货地址的经纬度--高德地图
            $location = split(',', json_decode($this->curlGet('http://restapi.amap.com/v3/geocode/geo?address='.$city.'市'.$order['address_info'].'&output=JSON&key=aba29ed8b30acb4e334d526b3f278c6d'), true)['geocodes'][0]['location']);
            $data = array(
                    'shop_no' => $business_info['dada_origin_shop_id'],
                    'origin_id' => $order_sn,
                    'city_code' => $cityCode,
                    'cargo_price' =>$order['total_price'],
                    'is_prepay' => 0,
                    'receiver_name' => $order['address_name'],
                    'receiver_address' => $order['address_info'],
                    'receiver_lat' => $location[1],
                    'receiver_lng' => $location[0],
                    'callback' => 'https://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'], '/')+1)."dadaNotifyUrl/a_id/".$business_id,
                    'receiver_phone' => $order['address_phone'],
                    'info' => $order['mark'],
                );
            // if (!empty($order['fachu_time'])) $data['delay_publish_time'] = $order['fachu_time'];
            $dada_return = $this->dada->addOrder($data); 

            if ($this->dada->errCode == 0) {
                // code
            }

            $this->ajaxReturn(['code' => $this->dada->errCode, 'info' => $this->dada->errMsg]);
            // return ['code' => $this->dada->errCode, 'info' => $this->dada->errMsg];
        } else {
            $this->ajaxReturn(['code' => 404, 'info' => '订单不是外卖订单']);
            // return ['code' => 404, 'info' => '不是外卖订单'];
        }
    }

    public function test_()
    {
        dump(json_decode($this->curlGet("http://restapi.amap.com/v3/geocode/geo?address=北京市朝阳区阜通东大街6号&output=JSON&key=aba29ed8b30acb4e334d526b3f278c6d"), true));
    }

    /**
     * [get_dada_ie 获取达达配送实例]
     * @AuthorHTL
     * @DateTime  2018-03-28T10:24:56+0800
     * @return    [type]                   [description]
     */
    public function get_dada_ie($business_id)
    {
        try {
            // 多门店-主账号business_id   主账号绑定app_key  app_secret  source_id
            $parent_id = M('admin')->where(array('id' => $business_id))->getField('parent_id');
            if (empty($parent_id)) {
                $config_p_id = $business_id;// 主门店id
            } else {
                $config_p_id = $this->parent_id;// 主门店id
            }

            $dada_config = M('dada_business')->where(array('admin_id' => $config_p_id))->field('id, source_id, app_key, app_secret')->find();

            if (empty($dada_config)) {
                return ['code' => 404, 'info' => '未绑定达达配送信息'];
            } else {
                $this->dada = new \Common\Controller\DadaController($config_p_id);
                return ['code' => 200, 'info' => '已获取达达配送实例'];
            }
        } catch (Exception $e) {
            return ['code' => 404, 'info' => $e->getMessage()];   
        }
    }

    /**
     * [cancelReasons 获取取消原因接口]
     * @return [type] [description]
     */
    public function cancelReasons($business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;
        $dada_return = $this->dada->cancelReasons('');
        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => '已获取数据', 'data' => $dada_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg, 'data' => $dada_return];
        } else {
            // $this->ajaxReturn(['code' => 404, 'info' => '没有数据']);
            return ['code' => 404, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [complaintReason 获取商家投诉达达原因]
     * @AuthorHTL
     * @DateTime  2018-03-30T12:41:35+0800
     * @param     [type]                   $business_id [description]
     * @return    [type]                                [description]
     */
    public function complaintReason($business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;

        $dada_return = $this->dada->complaintReasons('');
        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => '已获取数据', 'data' => $dada_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg, 'data' => $dada_return];
        } else {
            // $this->ajaxReturn(['code' => 404, 'info' => '没有数据']);
            return ['code' => 404, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [formalCancel 取消配送订单]
     * @param  [type] $business_id      [商户id]
     * @param  [type] $order_sn         [订单编号]
     * @param  [type] $cancel_reason_id [取消原因id]
     * @param  string $cancel_reason    [取消原因]
     * @return [type]                   [description]
     */
    public function formalCancel($business_id, $order_sn, $cancel_reason_id, $cancel_reason = '')
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;
        $dada_return = $this->dada->formalCancel(array('order_id' => $order_sn, 'cancel_reason_id' => $cancel_reason_id, 'cancel_reason' => $cancel_reason));
        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => '已获取数据', 'data' => $dada_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg];
        } else {
            // $this->ajaxReturn(['code' => 404, 'info' => '没有数据']);
            return ['code' => 404, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [complaintDada 投诉达达]
     * @AuthorHTL
     * @DateTime  2018-03-30T12:45:30+0800
     * @param     [type]                   $business_id [description]
     * @param     [type]                   $order_sn    [description]
     * @param     [type]                   $reason_id   [description]
     * @return    [type]                                [description]
     */
    public function complaintDada($business_id, $order_sn, $reason_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;
        $dada_return = $this->dada->complaintDada(array('order_id' => $order_sn, 'reason_id' => $reason_id));
        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => '已获取数据', 'data' => $dada_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg];
        } else {
            // $this->ajaxReturn(['code' => 404, 'info' => '没有数据']);
            return ['code' => 404, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [dadaNotifyUrl 达达订单状态回调地址]
     * @AuthorHTL
     * @DateTime  2018-03-23T19:02:10+0800
     * @return    [type]                   [description]
     */
    public function dadaNotifyUrl($a_id)
    {
        try {
            $return = $this->get_dada_ie($a_id);// 获取达达实例
            if ($return['code'] != 200)
            // $this->ajaxReturn($return);
            return $return;

            $notifyInfo = $this->dada->notifyUrl();

            if (empty($notifyInfo)) return false;

            $order_info = M('order')->where(array('order_sn' => $notifyInfo['order_id']))->find();// 订单信息

            if ($order_info['status'] == 2 && $notifyInfo['order_status'] == 4) {
                $result = M('order')->where(array('order_sn' => $notifyInfo['order_id']))->setField('status', 3);

                if ($result) {
                    $rec=M('distribution_rec')->where('order_sn='.$notifyInfo['order_id'])->select();
                    foreach($rec as $i => $val){
                      M('distribution_rec')->where('id='.$val['id'])->setField('status',1);//修改佣金状态
                      M('users')->where('id='.$val['user_id'])->setInc('count_sale',$val['money']);//累计可用提现佣金
                    }

                    Log::record('改变订单状态（已完成）成功');
                } else {
                    Log::record('改变订单状态（已完成）失败');
                }
            } else {
                Log::record('未改变订单状态');
            }
        } catch (Exception $e) {
            Log::record($e->getMessage());
        }
    }

    /**
     * [queryDeliverFee 订单预发布]
     * @AuthorHTL
     * @DateTime  2018-03-30T14:00:06+0800
     * @return    [type]                   [description]
     */
    public function queryDeliverFee($business_id, $data)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;
        
        $dada_return = $this->dada->queryDeliverFee($data); 

        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => $this->dada->errMsg, 'data' => $data_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg,  'data' => $dada_return];
        } else {
            // $this->ajaxReturn(['code' => $this->dada->errCode, 'info' => $this->dada->errMsg]);
            return ['code' => $this->dada->errCode, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [addAfterQuery 查询运费后发单接口]
     * @AuthorHTL
     * @DateTime  2018-03-30T16:09:33+0800
     * @param     [type]                   $business_id [description]
     * @param     [type]                   $deliveryNo  [description]
     */
    public function addAfterQuery($business_id, $deliveryNo)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;
        
        $dada_return = $this->dada->addAfterQuery($data); 

        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => $this->dada->errMsg, 'data' => $data_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg,  'data' => $dada_return];
        } else {
            // $this->ajaxReturn(['code' => $this->dada->errCode, 'info' => $this->dada->errMsg]);
            return ['code' => $this->dada->errCode, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [cityCodeList description]
     * @AuthorHTL
     * @DateTime  2018-03-30T16:15:43+0800
     * @param     [type]                   $business_id [description]
     * @return    [type]                                [description]
     */
    public function cityCodeList($business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         // $this->ajaxReturn($return);
            return $return;

        $dada_return = $this->dada->cityCodeList(''); 

        if ($this->dada->errCode == 0) {
            // $this->ajaxReturn(['code' => 200, 'info' => $this->dada->errMsg, 'data' => $dada_return]);
            return ['code' => 200, 'info' => $this->dada->errMsg,  'data' => $dada_return];
        } else {
            // $this->ajaxReturn(['code' => $this->dada->errCode, 'info' => $this->dada->errMsg]);
            return ['code' => $this->dada->errCode, 'info' => $this->dada->errMsg];
        }
    }

    /**
     * [accept 达达-模拟接单]
     * @AuthorHTL
     * @DateTime  2018-03-28T18:00:32+0800
     * @param     [type]                   $order_sn [description]
     * @return    [type]                             [description]
     */
    public function accept($order_sn, $business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         $this->ajaxReturn($return);
            // return $return;
            // 
        $dada_return = $this->dada->accept(array('order_id' => $order_sn));
        dump($dada_return);
    }   

    /**
     * [fetch_ 达达-模拟取货]
     * @AuthorHTL
     * @DateTime  2018-03-28T18:04:34+0800
     * @param     [type]                   $order_sn    [description]
     * @param     [type]                   $business_id [description]
     * @return    [type]                                [description]
     */
    public function fetch_($order_sn, $business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         $this->ajaxReturn($return);
            // return $return;
        $dada_return = $this->dada->fetch(array('order_id' => $order_sn));
        dump($dada_return);
    }  
    
    /**
     * [finish 达达-模拟完成订单]
     * @AuthorHTL
     * @DateTime  2018-03-28T18:06:25+0800
     * @param     [type]                   $order_sn    [description]
     * @param     [type]                   $business_id [description]
     * @return    [type]                                [description]
     */
    public function finish($order_sn, $business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         $this->ajaxReturn($return);
            // return $return;
            // 
        $dada_return = $this->dada->finish(array('order_id' => $order_sn));
        dump($dada_return);
    }   

    /**
     * [cancel 达达-模拟取消订单]
     * @AuthorHTL
     * @DateTime  2018-03-29T11:50:41+0800
     * @param     [type]                   $order_sn    [description]
     * @param     [type]                   $business_id [description]
     * @return    [type]                                [description]
     */
    public function cancel($order_sn, $business_id)
    {
        $return = $this->get_dada_ie($business_id);// 获取达达实例
        if ($return['code'] != 200)
         $this->ajaxReturn($return);
            // return $return;
            // 
        $dada_return = $this->dada->cancel(array('order_id' => $order_sn));
        dump($dada_return);
    }   

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

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

        // 获取支付通知
        $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($order['status'] == '1'){
            $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);
            $order['pay_time'] = $data['pay_time'];
            $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()));
            }

            $return = $this->get_dada_ie($order['admin_id']);// 获取达达实例
            if ($return['code'] == 200 && !empty($order['deliveryNo'])) {
               $this->dada->addAfterQuery(array('deliveryNo' => $order['deliveryNo']));// 查询运费后发单接口
            }
            
            // 分销，生成待反的佣金记录
            $share_switch = ShareLogicController::check_share($order['admin_id']);
                if ($share_switch == 1) {// 商户分销开关开启
                    // $user_share_status = ShareLogicController::check_user_share($order['uid']);
                    // if ($user_share_status == 1) { // 用户是分销员
                        ShareLogicController::create_share($order['order_sn'], $order['admin_id']);// 生成待返佣金记录
                // }
            }

            $admin_id=$order['admin_id'];
            $this->content($admin_id,$trade_no);
            if($order['order_type'] == 1){
                D('Order') -> SendEmail($admin_id,$order);
            }
            
        }
    }
    /**
     *
     */
    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 -> field('title,seat_no')->where('id='.$val['goods_id'])->find();
            $PrintContent.='@'.$this->PrintContent(0,$goods['seat_no'].' '.$goods['title'],0,0);
            $PrintContent.='@'.$this->PrintContent(0,$this->mingcheng('',10).'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)));
        return 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]);
    }

    /**
     * [get_about_us 获取关于我们]
     * @AuthorHTL
     * @DateTime  2018-03-20T12:19:11+0800
     * @return    [type]                   [description]
     */
    public function get_about_us()
    {
        $data = I('post.');

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

        $about_us = M('admin')->where(array('admin_id' => $data['business_id']))->getField('about_us');

        $this->ajaxReturn(['status' => 1, 'msg' => '已获取数据', 'data' => htmlspecialchars_decode($about_us)]);
    }

    /**
     * 充值卡--支付成功回调
     * @param $id
     * @param $tenant_id
     * @return \think\\Xml
     */
    public function cardsNotifyUrl($a_id){

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

        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        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->payCardsChange($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
     */
    private function payCardsChange($trade_no,$transaction_id)
    {   
        $info = M('cards_log')->where(array('pay_no' => $trade_no))->find();

        if ($info['status'] == 1) {
            // 增加账户余额
            $balance = M('user_money')->where(array('user_id' => $info['user_id']))->getField('balance');

            if (empty($balance)) {// 添加数据
                $result = M('user_money')->add(array('user_id' => $info['user_id'], 'balance' => $info['preferential_money'], 'create_time' => time(), 'update_time' => time()));
            } else {// 更新数据
                $result = M('user_money')->where(array('user_id' => $info['user_id']))->save(array('balance' => $balance + $info['preferential_money'], 'update_time' => time()));
            }
            
            if ($result) {
                M('cards_log')->where(array('pay_no' => $trade_no))->save(array('status' => 2, 'transaction_id' => $transaction_id, 'pay_time' => time()));// 更改定单状态

                return array('status' => 1, 'msg' => '订单状态改变成功');
            } else {
                return array('status' => -1, 'msg' => '订单状态改变失败');
            }
        }
    }
}