<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class OrderController extends Controller
{      
    protected $dada;// 达达配送实例

    /**
     * 查询商品价格
     */
    public function get_goods_price()
    {
        $ids = I('post.ids');

        $ids = html_entity_decode($ids);
        $ids = stripslashes($ids);
        $ids = json_decode($ids, true);
        if (empty($ids)) apiReturn(['status' => -1, 'msg' => 'id不能为空']);
        $where = 'id = ';
        foreach($ids as $id) {
            $where .= $id.' OR id = ';
        }
        $where = rtrim($where, ' OR id = ');
        $info = M('goods')->where($where)->field('id as goods_id, title, price, img')->select();
        foreach ($info as &$value) {
            $value['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$value['img'];
        }

        if (empty($info)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $info]);
        }
    }


    //两点之间距离
    function getDistance($lat1, $lng1, $lat2, $lng2){      
        $earthRadius = 6378.138; //近似地球半径千米
        //$lat1 = 22.6431990000;//$lat1 = 22.642621;
        //$lng1 = 114.0192110000;//$lng1 = 114.019326;
        //$lat2 = 22.5621010000;//$lat2 = 22.548549;$lat2 = 22.5621010000
        //$lng2 = 113.9531950000;//$lng2 = 114.143583;
        // 转换为弧度
        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;
        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;
        // 使用半正矢公式  用尺规来计算
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        //print_r(round($calculatedDistance,2));die;
        return round($calculatedDistance,2);
    }

    function get_link(){      
        $data = I('post.');
        $data['user_id'] = isset($data['user_id'])?$data['user_id']:$data['users_id'];
        $link = M('link')->where('user_id ='.$data['user_id'])->find();
        if (empty($link)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $link]);
        }

    }

    /**
     * 生成订单
     */
    public function create_order()
    {
        $data = I('post.');
        $data['user_id'] = isset($data['user_id'])?$data['user_id']:$data['users_id'];

        //保存用户联系电话和名字 2018-6-14
        $link = M('link')->where('user_id = '.$data['user_id'])->find();
        if(empty($link)){
            $links['user_id'] = $data['user_id'];
            $links['name'] = $data['address_name'];
            $links['phone']  =  $data['address_phone'];
            $links['address_area'] = $data['address_area'];
            $links['address_info']  =  $data['address_info'];
            M('link')->add($links);
        }else{
            $links['name'] = $data['address_name'];
            $links['phone']  =  $data['address_phone'];
            $links['address_area'] = $data['address_area'];
            $links['address_info']  =  $data['address_info'];
            M('link')->where('user_id ='.$data['user_id'])->save($links);
        }


        // dump($data);die;
        $this->check_param($data);
        if (empty($data['order_type'])) apiReturn(['status' => -1, 'msg' => 'order_type不能为空']);

        $this->business_status($data['business_id']);//查询商户状态

        $api_controller = new ApiController();

        $data['car_content'] = html_entity_decode($data['car_content']);
        $data['car_content'] = stripslashes($data['car_content']);
        $data['car_content'] = json_decode($data['car_content'], true);

        $sum_price = 0;// 订单总价
        foreach ($data['car_content'] as $value) {
            //2018-6-25属性价格
            /*if($value['attr_id']){
                $attr=array_filter(explode(",", $value['attr_id']));
                $attrprice = 0;
                foreach ($attr as $k => $v) {
                    $goodsattr = M('goods_attr')->where('id='.$v)->find();
                    $attrprice=$attrprice+$goodsattr['attr_price'];
                } 
                $sum_price = $sum_price+$value['sum_price']+$attrprice;   

            }else{
                $sum_price += $value['sum_price'];
            }*/
            $sum_price += $value['sum_price'];
        }

         $int = 0;// 积分初始值
        // 获取会员设置
        $member_config = M('member_config')->where(array('admin_id' => $data['business_id']))->find();
        if (empty($member_config)) {
            M('member_config')->add(array('admin_id' => $data['business_id'], 'create_time' => time()));
            $member_config = M('member_config')->where(array('admin_id' => $data['business_id']))->find();
        }
        $int_rate = $member_config['int_rate'];// 积分比例
        $int_rate = split(':', $int_rate);

        $data['order_sn'] = str_replace(' ', '', str_replace(':', '', str_replace('-', '', date('Y-m-d H:i:s').rand(100000, 999999))));// 生成订单编号

        //2018-7-2
        $data['kexiao_sn'] = rand(10000000, 99999999);// 生成核销码
        
        $business_info = M('admin')->where(array('id' => $data['business_id']))->field('delivery, boxes, business_name, is_on_waimai, up_to_send, dada_origin_shop_id')->limit(1)->select()[0];// 商户信息
        $Goods = M("goods");
        if ($data['order_type'] == 1) {// 外卖
            if ($business_info['is_on_waimai'] == 2) apiReturn(['status' => -1, 'msg' => '商家不支持外卖']);


            //判断是否超过配送范围 2018-6-14
            $scope = M('scope')->where('admin_id ='.$data['business_id'].' and status = 1')->find();
            if($scope&&$data['lng']&&$data['lat']){
                $lnglat = explode(",",$business_info['lnglat']);
                $lng1 = $lnglat['0'];
                $lat1 = $lnglat['1'];
                //$city = split('市', $matchs[2])[0];
                // 收货地址的经纬度--高德地图
                //$location = split(',', json_decode($api_controller->curlGet('http://restapi.amap.com/v3/geocode/geo?address='.$city.'市'.$data['address_info'].'&output=JSON&key=aba29ed8b30acb4e334d526b3f278c6d'), true)['geocodes'][0]['location']);
                $lng2 = $data['lng'];
                $lat2 = $data['lat'];
                $juli = $this->getDistance($lat1, $lng1, $lat2, $lng2);
                if($juli > $scope['scope']){
                    apiReturn(['status' => -1, 'msg' => '路程超过了配送范围']);
                }
            }

            $api_dada_ie = $api_controller->get_dada_ie($data['business_id']);// 是否支持达达配送，获取达达实例
            if ($api_dada_ie['code'] != 200) {// 不支持达达配送
                $price = $sum_price + $business_info['delivery'] + $business_info['boxes'];// 实际消费金额

                if (!empty($data['user_pre_id'])) {// 是否使用优惠券
                    $user_pre_info = M('user_pre')->where(array('id' => $data['user_pre_id']))->find();
                    // 检测优惠券
                    $user_pre_return = $this->check_user_pre($user_pre_info, ($sum_price + $business_info['delivery'] + $business_info['boxes']));
                    if ($user_pre_return['status'] == -1) {
                        apiReturn($user_pre_return);
                    } else {
                        $price -= $user_pre_info['pre_money'];
                    }
                }

                // 商户是否有满减活动
                $reduction_money = 0;
                $reduction = M('reduction')->where(array('admin_id' => $data['business_id']))->order('full_money ASC')->select();
                if (!empty($reduction)) {
                    foreach ($reduction as $key => $value) {
                        if ($value['full_money'] <= ( $sum_price + $business_info['delivery'] + $business_info['boxes'])) {
                            $reduction_money = $value['reduction_money'];
                        }
                    }
                }
                $price -= $reduction_money;

                if ($data['pay_type'] == 2) {# 储值卡支付，检测储值卡余额
                    $user_balance = M('user_money')->where(array('user_id' => $data['user_id']))->field('balance, money')->find();
                    if ($price > $user_balance['balance']) apiReturn(['status' => -1, 'msg' => '用户余额不足，订单自动取消！']);
                }

                if (($sum_price + $business_info['boxes']) < $business_info['up_to_send']) apiReturn(['status' => -1, 'msg' => '金额没有满起送费，不能下单']);
                if ($car_id = $this->add_car($data)) {
                    $add_data = [
                        'delivery'       =>  $business_info['delivery'],
                        'fachu_time'     =>  $data['fachu_time'],
                        'address_name'   =>  $data['address_name'],
                        'address_phone'  =>  $data['address_phone'],
                        'address_area'   =>  $data['address_area'],
                        'address_info'   =>  $data['address_info'],
                        'mark'           =>  $data['mark'],
                        'order_type'     =>  $data['order_type'],
                        'create_time'    =>  time(),
                        'status'         =>  1,
                        'order_sn'       =>  $data['order_sn'],
                        'uid'            =>  $data['users_id'],
                        'admin_id'       =>  $data['business_id'],
                        'car_id'         =>  $car_id,
                        'price'          =>  $price,
                        'total_price'    =>  $sum_price + $business_info['boxes'],
                        'admin_title'    =>  $business_info['business_name'],
                        'boxes'          =>  $business_info['boxes'],
                        'meals_num'      =>  isset($data['meals_num']) ? $data['meals_num'] : 1, // 默认1人
                        'user_pre_id'    =>  $data['user_pre_id'],// 用户使用优惠券id
                        'pay_type'       =>  empty($data['pay_type']) ? 1 : $data['pay_type'],// 支付类型
                        'pre_money'      =>  empty($data['user_pre_id']) ? 0.00 : $user_pre_info['pre_money'],// 优惠券优惠金额
                    ];
                    $add_data['int'] = intval($add_data['price'] * ($int_rate[1] / $int_rate[0]));// 积分

                    if ($order_id = M('order')->add($add_data)) {
                        $add_data['order_id'] = $order_id;
                        $add_data['business_id'] = $add_data['admin_id'];
                        unset($add_data['admin_id']);
                        unset($add_data['car_id']);
                        $add_data['order_name'] = $add_data['admin_title'];
                        unset($add_data['admin_title']);
                        $add_data['car_content'] = $data['car_content'];
                        // $this->api = new ApiController();
                        // $this->api->payMoney($data['order_sn']);

                        foreach ($add_data['car_content'] as &$vo) {
                            $vo['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($vo['goods_id'])['img'];
                        }

                        // 更改优惠券使用状态
                        if (!empty($data['user_pre_id'])) {// 使用优惠券
                            M('user_pre')->where(array('id' => $data['user_pre_id']))->setField('status', 2);
                        } 

                        if (empty($data['pay_type']) || $data['pay_type'] == 1) {# 微信支付
                            apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                        } else if ($data['pay_type'] == 2) {// 储值卡支付，并扣钱
                            $balance_result = M('user_money')->where(array('user_id' => $data['user_id']))->save(array('balance' => $user_balance['balance'] - $price, 'money' => $user_balance['money'] + $price, 'update_time' => time()));
                            if ($balance_result) {
                                $save['pay_time']=time();
                                $save['status']=2;
                                M('order')->where(array('id' => $order_id))->save($save);// 修改订单状态
                                $car=M('car')->where('order_sn='.$data['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' => $data['user_id']))->find();
                                if ($is_has_int) {
                                    $int = M('user_int')->where(array('user_id' => $data['user_id']))->getField('int');
                                    M('user_int')->where(array('user_id' => $data['user_id']))->save(array('update_time' => time(), 'int' => $int + $add_data['int']));
                                } else {
                                    M('user_int')->add(array('user_id' => $data['user_id'], 'int' => $add_data['int'], 'create_time' => time()));
                                }

                                // 小票打印机打印订单
                                $api_controller->content($data['business_id'],$data['order_sn']);

                                //邮箱推送2018-6-20
                                $sendorder=M('order')->where(array('id' => $order_id))->find();
                                if($sendorder['order_type'] == 1){
                                    D('Order') -> SendEmail($data['business_id'],$sendorder);
                                }


                                $add_data['status'] = 2;
                                apiReturn(['status' => 1, 'msg' => '生成订单成功，且扣款成功', 'data' => $add_data]);
                            } else {
                                apiReturn(['status' => -1, 'msg' => '生成订单成功，且扣款失败', 'data' => $add_data]);
                            }
                        }
                    } else {
                        M('car')->delete($car_id);
                        apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                    }
                } else {
                    apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                }
            } else {// 支持达达配送
                // 达达订单预发布，查询运费
                $address_preg = '/^([\x7f-\xff]+省)?([\x7f-\xff]+市)([\x7f-\xff]+区|县)/';
                $matchs = array();
                preg_match($address_preg, $data['address_area'], $matchs);
                $city = split('市', $matchs[2])[0];
                $cityCodeList = $api_controller->cityCodeList($data['business_id']);
                if ($cityCodeList['code'] != 200) $this->ajaxReturn(['status' => -1, 'msg' => $cityCodeList['info']]);
                foreach ($cityCodeList['data'] as $key => $value) {
                    if ($value['cityName'] == $city) {
                        $cityCode = $value['cityCode'];// 城市编号
                        break;
                    }
                 }

                 // 回调地址
                $url = substr($_SERVER['PHP_SELF'],0,strrpos($_SERVER['PHP_SELF'], '/')-1);
                $url = substr($url,0,strrpos($url, '/')-1);
                $url = substr($url,0,strrpos($url, '/'));
                $notify_url = 'https://'.$_SERVER['HTTP_HOST'].substr($url,0,strrpos($url, '/')+1).'Api/Api/dadaNotifyUrl/a_id/'.$data['business_id'];

                // 收货地址的经纬度--高德地图
                $location = split(',', json_decode($api_controller->curlGet('http://restapi.amap.com/v3/geocode/geo?address='.$city.'市'.$data['address_info'].'&output=JSON&key=aba29ed8b30acb4e334d526b3f278c6d'), true)['geocodes'][0]['location']);
                $send = array(
                        'shop_no' => $business_info['dada_origin_shop_id'],
                        'origin_id' => $data['order_sn'],
                        'city_code' => $cityCode,
                        'cargo_price' => $sum_price+$business_info['boxes'],
                        'is_prepay' => 0,
                        'receiver_name' => $data['address_name'],
                        'receiver_address' => $data['address_info'],
                        'receiver_lat' => $location[1],
                        'receiver_lng' => $location[0],
                        'callback' => $notify_url,
                        'info' => $data['mark'],
                    );
                // if (!empty($data['fachu_time'])) $data['delay_publish_time'] = $data['fachu_time'];
                // 查询运费
                $dada_return = $api_controller->queryDeliverFee($data['business_id'], $send);
                if ($dada_return['code'] != 200) $this->ajaxReturn(['status' => -1, 'msg' => $dada_return['info']]);

                $price = $sum_price + $business_info['boxes'] + $dada_return['data']['deliverFee'];// 实际消费金额

                if (!empty($data['user_pre_id'])) {// 是否使用优惠券
                    $user_pre_info = M('user_pre')->where(array('id' => $data['user_pre_id']))->find();
                    // 检测优惠券
                    $user_pre_return = $this->check_user_pre($user_pre_info, ($sum_price + $business_info['boxes']));
                    if ($user_pre_return['status'] == -1) {
                        apiReturn($user_pre_return);
                    } else {
                        $price -= $user_pre_info['pre_money'];
                    }
                }

                // 商户是否有满减活动
                $reduction_money = 0;
                $reduction = M('reduction')->where(array('admin_id' => $data['business_id']))->order('full_money ASC')->select();
                if (!empty($reduction)) {
                    foreach ($reduction as $key => $value) {
                        if ($value['full_money'] <= ( $sum_price + $business_info['boxes'])) {
                            $reduction_money = $value['reduction_money'];
                        }
                    }
                }
                $price -= $reduction_money;

                if ($data['pay_type'] == 2) {# 储值卡支付，检测储值卡余额
                    $user_balance = M('user_money')->where(array('user_id' => $data['user_id']))->field('balance, money')->find();
                    if ($price > $user_balance['balance']) apiReturn(['status' => -1, 'msg' => '用户余额不足，订单自动取消！']);
                }

                if (($sum_price + $business_info['boxes']) < $business_info['up_to_send']) apiReturn(['status' => -1, 'msg' => '金额没有满起送费，不能下单']);
                if ($car_id = $this->add_car($data)) {
                    $add_data = [
                        'delivery'       =>  $dada_return['data']['deliverFee'],// 运费
                        'fachu_time'     =>  $data['fachu_time'],
                        'address_name'   =>  $data['address_name'],
                        'address_phone'  =>  $data['address_phone'],
                        'address_area'   =>  $data['address_area'],
                        'address_info'   =>  $data['address_info'],
                        'mark'           =>  $data['mark'],
                        'order_type'     =>  $data['order_type'],
                        'create_time'    =>  time(),
                        'status'         =>  1,
                        'order_sn'       =>  $data['order_sn'],
                        'uid'            =>  $data['users_id'],
                        'admin_id'       =>  $data['business_id'],
                        'car_id'         =>  $car_id,
                        'price'          =>  $price,
                        'total_price'    =>  $sum_price + $business_info['boxes'],
                        'admin_title'    =>  $business_info['business_name'],
                        'boxes'          =>  $business_info['boxes'],
                        'meals_num'      =>  isset($data['meals_num']) ? $data['meals_num'] : 1, // 默认1人
                        'user_pre_id'    =>  $data['user_pre_id'],// 用户使用优惠券id
                        'pay_type'       =>  empty($data['pay_type']) ? 1 : $data['pay_type'],// 支付类型
                        'pre_money'      =>  empty($data['user_pre_id']) ? 0.00 : $user_pre_info['pre_money'],// 优惠券优惠金额
                        'deliveryNo' => $dada_return['data']['deliveryNo'],// 达达平台唯一编号
                    ];
                    $add_data['int'] = intval($add_data['price'] * ($int_rate[1] / $int_rate[0]));// 积分

                    if ($order_id = M('order')->add($add_data)) {
                        $add_data['order_id'] = $order_id;
                        $add_data['business_id'] = $add_data['admin_id'];
                        unset($add_data['admin_id']);
                        unset($add_data['car_id']);
                        $add_data['order_name'] = $add_data['admin_title'];
                        unset($add_data['admin_title']);
                        $add_data['car_content'] = $data['car_content'];
                        // $this->api = new ApiController();
                        // $this->api->payMoney($data['order_sn']);

                        foreach ($add_data['car_content'] as &$vo) {
                            $vo['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($vo['goods_id'])['img'];
                        }

                        // 更改优惠券使用状态
                        if (!empty($data['user_pre_id'])) {// 使用优惠券
                            M('user_pre')->where(array('id' => $data['user_pre_id']))->setField('status', 2);
                        } 

                        apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                        //---------------------------------------------------------------------------

                        //先生成存订单信息，然后去支付（微信付款/钱包支付）
                        if (empty($data['pay_type']) || $data['pay_type'] == 1) {# 微信支付
                            apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                        } 
                        else if ($data['pay_type'] == 2) {// 储值卡支付，并扣钱
                            $balance_result = M('user_money')->where(array('user_id' => $data['user_id']))->save(array('balance' => $user_balance['balance'] - $price, 'money' => $user_balance['money'] + $price, 'update_time' => time()));
                            if ($balance_result) {
                                $save['pay_time']=time();
                                $save['status']=2;
                                M('order')->where(array('id' => $order_id))->save($save);// 修改订单状态
                                $car=M('car')->where('order_sn='.$data['order_sn'])->find();
                                $goods_id=unserialize($car['car_content']);
                                foreach ($goods_id  as  $key => $val){
                                    $Goods->where('id='.$val['goods_id'])->setInc('sales',$val['goods_num']);
                                }
                                // 增加用户积分
                                $is_has_int = M('user_int')->where(array('user_id' => $data['user_id']))->find();
                                if ($is_has_int) {
                                    $int = M('user_int')->where(array('user_id' => $data['user_id']))->getField('int');
                                    M('user_int')->where(array('user_id' => $data['user_id']))->save(array('update_time' => time(), 'int' => $int + $add_data['int']));
                                } else {
                                    M('user_int')->add(array('user_id' => $data['user_id'], 'int' => $add_data['int'], 'create_time' => time()));
                                }

                                // 小票打印机打印订单
                                $api_controller->content($data['business_id'],$data['order_sn']);

                                //邮箱推送2018-6-20
                                $sendorder=M('order')->where(array('id' => $order_id))->find();
                                if($sendorder['order_type'] == 1){
                                    D('Order') -> SendEmail($data['business_id'],$sendorder);
                                }

                                // 查询运费后发单接口
                                $api_controller->addAfterQuery($business_id, $dada_return['data']['deliveryNo']);

                                $add_data['status'] = 2;
                                apiReturn(['status' => 1, 'msg' => '生成订单成功，且扣款成功', 'data' => $add_data]);
                            } else {
                                apiReturn(['status' => -1, 'msg' => '生成订单成功，且扣款失败', 'data' => $add_data]);
                            }
                        }
                  //---------------------------------------------------------------------------
                //---------------------------------------------------------------------------
                    } else {
                        M('car')->delete($car_id);
                        apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                    }
                } else {
                    apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                }
            }
            
        } elseif ($data['order_type'] == 2) {// 店内
            if (empty($data['seat'])) apiReturn(['status' => -1, 'msg' => '请输入桌位号']);

            $price = $sum_price ;// 实际消费金额
            if (!empty($data['user_pre_id'])) {// 使用优惠券
                $user_pre_info = M('user_pre')->where(array('id' => $data['user_pre_id']))->find();
                // 检测优惠券
                $user_pre_return = $this->check_user_pre($user_pre_info, $sum_price );
                if ($user_pre_return['status'] == -1) {
                    apiReturn($user_pre_return);
                } else {
                    $price -= $user_pre_info['pre_money'];
                }
            }

            if ($data['pay_type'] == 2) {# 储值卡支付，检测储值卡余额
                $user_balance = M('user_money')->where(array('user_id' => $data['user_id']))->field('balance, money')->find();
                if ($price > $user_balance['balance']) apiReturn(['status' => -1, 'msg' => '用户余额不足，订单自动取消！']);
            }
            // 商户是否有满减活动
            $reduction_money = 0;
            $reduction = M('reduction')->where(array('admin_id' => $data['business_id']))->order('full_money ASC')->select();
            if (!empty($reduction)) {
                foreach ($reduction as $key => $value) {
                    if ($value['full_money'] <= $sum_price) {
                        $reduction_money = $value['reduction_money'];
                    }
                }
            }
            $price -= $reduction_money;
            if ($car_id = $this->add_car($data)) {
                $add_data = [
                    'delivery'       =>  $business_info['delivery'],
                    'mark'           =>  $data['mark'],
                    'order_type'     =>  $data['order_type'],
                    'create_time'    =>  time(),
                    'status'         =>  1,
                    'order_sn'       =>  $data['order_sn'],
                    'uid'            =>  $data['users_id'],
                    'admin_id'       =>  $data['business_id'],
                    'car_id'         =>  $car_id,
                    'price'          =>  $price,
                    'total_price'    =>  $sum_price,
                    'admin_title'    =>  $business_info['business_name'],
                    'boxes'          =>  $business_info['boxes'],
                    'meals_num'      =>  isset($data['meals_num']) ? $data['meals_num'] : 1, // 默认1人
                    'seat'           =>  $data['seat'],
                    'user_pre_id'    =>  $data['user_pre_id'],// 用户使用优惠券id
                    'pay_type'       =>  empty($data['pay_type']) ? 1 : $data['pay_type'],// 支付类型
                    'pre_money'      =>  empty($data['user_pre_id']) ? 0.00 : $user_pre_info['pre_money'],// 优惠券优惠金额
                ];
                $add_data['int'] = intval($add_data['price'] * ($int_rate[1] / $int_rate[0]));// 积分

                if ($order_id = M('order')->add($add_data)) {
                    $add_data['order_id'] = $order_id;
                    $add_data['business_id'] = $add_data['admin_id'];
                    unset($add_data['admin_id']);
                    unset($add_data['car_id']);
                    $add_data['order_name'] = $add_data['admin_title'];
                    unset($add_data['admin_title']);
                    $add_data['car_content'] = $data['car_content'];
                    // $this->api = new ApiController();
                    // $this->api->payMoney($data['order_sn']);

                    foreach ($add_data['car_content'] as &$vo) {
                        $vo['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($vo['goods_id'])['img'];
                    }

                    // 更改优惠券使用状态
                    if (!empty($data['user_pre_id'])) {// 使用优惠券
                        M('user_pre')->where(array('id' => $data['user_pre_id']))->setField('status', 2);
                    } 

                   if (empty($data['pay_type']) || $data['pay_type'] == 1) {# 微信支付
                        apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                    } else if ($data['pay_type'] == 2) {// 储值卡支付，并扣钱
                        $balance_result = M('user_money')->where(array('user_id' => $data['user_id']))->save(array('balance' => $user_balance['balance'] - $price, 'money' => $user_balance['money'] + $price, 'update_time' => time()));
                        if ($balance_result) {
                            $save['pay_time']=time();
                            $save['status']=2;
                            M('order')->where(array('id' => $order_id))->save($save);// 修改订单状态
                            $car=M('car')->where('order_sn='.$data['order_sn'])->find();
                            $goods_id=unserialize($car['car_content']);
                            foreach ($goods_id  as  $key => $val){
                                $Goods->where('id='.$val['goods_id'])->setInc('sales',$val['goods_num']);
                            }
                            // 增加用户积分
                            $is_has_int = M('user_int')->where(array('user_id' => $data['user_id']))->find();
                            if ($is_has_int) {
                                $int = M('user_int')->where(array('user_id' => $data['user_id']))->getField('int');
                                M('user_int')->where(array('user_id' => $data['user_id']))->save(array('update_time' => time(), 'int' => $int + $add_data['int']));
                            } else {
                                M('user_int')->add(array('user_id' => $data['user_id'], 'int' => $add_data['int'], 'create_time' => time()));
                            }
                            // 小票打印机打印订单
                            $api_controller = new ApiController();
                            $api_controller->content($data['business_id'],$data['order_sn']);
                            
                            $add_data['status'] = 2;
                            
                            // 分销，生成待反的佣金记录
                            $share_switch = ShareLogicController::check_share($data['business_id']);
                            if ($share_switch == 1) {// 商户分销开关开启
                                // $user_share_status = ShareLogicController::check_user_share($data['users_id']);
                                // if ($user_share_status == 1) { // 用户是分销员
                                    ShareLogicController::create_share($data['order_sn'], $data['business_id']);// 生成待反佣金记录
                                // }
                            }

                            apiReturn(['status' => 1, 'msg' => '生成订单成功，且扣款成功', 'data' => $add_data]);
                        } else {
                            apiReturn(['status' => -1, 'msg' => '生成订单成功，且扣款失败', 'data' => $add_data]);
                        }
                    }

                } else {
                    M('car')->delete($car_id);
                    apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                }
            } else {
                apiReturn(['status' => -1, 'msg' => '生成订单失败']);
            }
        }elseif ($data['order_type'] == 3){
                $price = $sum_price + $business_info['boxes'];// 实际消费金额

                if (!empty($data['user_pre_id'])) {// 是否使用优惠券
                    $user_pre_info = M('user_pre')->where(array('id' => $data['user_pre_id']))->find();
                    // 检测优惠券
                    $user_pre_return = $this->check_user_pre($user_pre_info, ($sum_price + $business_info['delivery'] + $business_info['boxes']));
                    if ($user_pre_return['status'] == -1) {
                        apiReturn($user_pre_return);
                    } else {
                        $price -= $user_pre_info['pre_money'];
                    }
                }

                // 商户是否有满减活动
                $reduction_money = 0;
                $reduction = M('reduction')->where(array('admin_id' => $data['business_id']))->order('full_money ASC')->select();
                if (!empty($reduction)) {
                    foreach ($reduction as $key => $value) {
                        if ($value['full_money'] <= ( $sum_price + $business_info['delivery'] + $business_info['boxes'])) {
                            $reduction_money = $value['reduction_money'];
                        }
                    }
                }
                $price -= $reduction_money;

                if ($data['pay_type'] == 2) {# 储值卡支付，检测储值卡余额
                    $user_balance = M('user_money')->where(array('user_id' => $data['user_id']))->field('balance, money')->find();
                    if ($price > $user_balance['balance']) apiReturn(['status' => -1, 'msg' => '用户余额不足，订单自动取消！']);
                }

                if (($sum_price + $business_info['boxes']) < $business_info['up_to_send']) apiReturn(['status' => -1, 'msg' => '金额没有满起送费，不能下单']);
                if ($car_id = $this->add_car($data)) {
                    $add_data = [
                        'delivery'       =>  $business_info['delivery'],
                        'fachu_time'     =>  $data['fachu_time'],
                        'address_name'   =>  $data['address_name'],
                        'address_phone'  =>  $data['address_phone'],
                        'address_area'   =>  $data['address_area'],
                        'address_info'   =>  $data['address_info'],
                        'mark'           =>  $data['mark'],
                        'order_type'     =>  $data['order_type'],
                        'create_time'    =>  time(),
                        'status'         =>  1,
                        'order_sn'       =>  $data['order_sn'],
                        'uid'            =>  $data['users_id'],
                        'admin_id'       =>  $data['business_id'],
                        'car_id'         =>  $car_id,
                        'price'          =>  $price,
                        'total_price'    =>  $sum_price + $business_info['boxes'],
                        'admin_title'    =>  $business_info['business_name'],
                        'boxes'          =>  $business_info['boxes'],
                        'meals_num'      =>  isset($data['meals_num']) ? $data['meals_num'] : 1, // 默认1人
                        'user_pre_id'    =>  $data['user_pre_id'],// 用户使用优惠券id
                        'pay_type'       =>  empty($data['pay_type']) ? 1 : $data['pay_type'],// 支付类型
                        'pre_money'      =>  empty($data['user_pre_id']) ? 0.00 : $user_pre_info['pre_money'],// 优惠券优惠金额
                        'kexiao_sn'     =>  $data['kexiao_sn'],
                        'qucan_time'     =>  strtotime($data['qucan_time']),
                    ];
                    $add_data['int'] = intval($add_data['price'] * ($int_rate[1] / $int_rate[0]));// 积分

                    if ($order_id = M('order')->add($add_data)) {
                        $add_data['order_id'] = $order_id;
                        $add_data['business_id'] = $add_data['admin_id'];
                        unset($add_data['admin_id']);
                        unset($add_data['car_id']);
                        $add_data['order_name'] = $add_data['admin_title'];
                        unset($add_data['admin_title']);
                        $add_data['car_content'] = $data['car_content'];
                        // $this->api = new ApiController();
                        // $this->api->payMoney($data['order_sn']);

                        foreach ($add_data['car_content'] as &$vo) {
                            $vo['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($vo['goods_id'])['img'];
                        }

                        // 更改优惠券使用状态
                        if (!empty($data['user_pre_id'])) {// 使用优惠券
                            M('user_pre')->where(array('id' => $data['user_pre_id']))->setField('status', 2);
                        } 

                        if (empty($data['pay_type']) || $data['pay_type'] == 1) {# 微信支付
                            apiReturn(['status' => 1, 'msg' => '生成订单成功', 'data' => $add_data]);
                        } else if ($data['pay_type'] == 2) {// 储值卡支付，并扣钱
                            $balance_result = M('user_money')->where(array('user_id' => $data['user_id']))->save(array('balance' => $user_balance['balance'] - $price, 'money' => $user_balance['money'] + $price, 'update_time' => time()));
                            if ($balance_result) {
                                $save['pay_time']=time();
                                $save['status']=2;
                                M('order')->where(array('id' => $order_id))->save($save);// 修改订单状态
                                $car=M('car')->where('order_sn='.$data['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' => $data['user_id']))->find();
                                if ($is_has_int) {
                                    $int = M('user_int')->where(array('user_id' => $data['user_id']))->getField('int');
                                    M('user_int')->where(array('user_id' => $data['user_id']))->save(array('update_time' => time(), 'int' => $int + $add_data['int']));
                                } else {
                                    M('user_int')->add(array('user_id' => $data['user_id'], 'int' => $add_data['int'], 'create_time' => time()));
                                }

                                // 小票打印机打印订单
                                $api_controller->content($data['business_id'],$data['order_sn']);

                                //邮箱推送2018-6-20
                                $sendorder=M('order')->where(array('id' => $order_id))->find();
                                if($sendorder['order_type'] == 1){
                                    D('Order') -> SendEmail($data['business_id'],$sendorder);
                                }
                                

                                $add_data['status'] = 2;
                                apiReturn(['status' => 1, 'msg' => '生成订单成功，且扣款成功', 'data' => $add_data]);
                            } else {
                                apiReturn(['status' => -1, 'msg' => '生成订单成功，且扣款失败', 'data' => $add_data]);
                            }
                        }
                    } else {
                        M('car')->delete($car_id);
                        apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                    }
                } else {
                    apiReturn(['status' => -1, 'msg' => '生成订单失败']);
                }
        } else {
            apiReturn(['status' => -1, 'msg' => 'order_type参数错误']);
        }
    }

    /**
     * 获取订单列表
     */
    public function get_order_list()
    {
        $data = I('post.');
        $this->check_param($data);
        if (empty($data['page'])) apiReturn(['status' => -1, 'msg' => 'page参数必须']);

        $this->business_status($data['business_id']);//查询商户状态

        $where = array('am_order.admin_id' => $data['business_id'], 'am_order.uid' => $data['users_id']);

        if (empty($data['status']) || $data['status'] == 0) {
            $where['status'] = array('lt', 5);
        } elseif ($data['status'] == 1) { # 待付
            $where['status'] = 1;
        } elseif ($data['status'] == 2) { # 已下单
            $where['status'] = 2;
        } elseif ($data['status'] == 3) { # 已完成 
            $where['status'] = 3;
        } elseif ($data['status'] == 4) { # 已退款 
            $where['status'] = 4;
        } elseif ($data['status'] == 5) { # 已取消
            $where['status'] = 5;
        }
        $where['is_del'] = 0;
        $order_list = M('order')
        ->join('am_car ON am_car.id = am_order.car_id')
        ->where($where)
        ->field('am_order.order_sn, am_order.kexiao_sn,am_order.qucan_time,delivery, boxes, price, seat, status, order_type, mark, am_order.create_time, pay_time, fachu_time, address_name, address_phone, address_area, address_info, am_car.car_content, meals_num, total_price, pay_type')
        ->order('am_order.create_time DESC')
        ->page($data['page'].', 5')
        ->select();
        if (empty($order_list)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            foreach ($order_list as $key => &$value) {
                $value['car_content'] = unserialize($value['car_content']);
                foreach ($value['car_content'] as $k => &$v) {
                    $v['title'] = M('goods')->where(array('id' => $v['goods_id']))->getField('title');
                    $v['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($v['goods_id'])['img'];

                    //获取属性标题2018-6-25
                    if($v['attr_id']){
                        $attr=array_filter(explode(",", $v['attr_id']));
                        $text="";
                        foreach ($attr as $ke => $val) {
                            $goodsattr = M('goods_attr')->where('id='.$val)->find();
                            if($ke==0){
                              $text=$goodsattr['attr_title'];
                            }else{
                              $text.="+".$goodsattr['attr_title'];
                            }
                        }

                        $v['attr_title']=$text;
                    }

                }
            }
        }
        apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $order_list]);
    }

    /**
     * 查询桌位号
     */
    public function get_seats()
    {    
        $business_id = I('post.business_id');
        if (empty($business_id)) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $this->business_status($business_id);//查询商户状态

        $list = M('table')->where(array('admin_id' => $business_id))->field('id,name,pid')->select();

        // $layer = M('table')->where(array('admin_id' => $business_id, 'pid' => 0))->field('id, name, pid')->select();
        // $table = M('table')->where(array('admin_id' => $business_id, 'pid' => array('gt', 0)))->field('id, name, pid')->select();

        // $arr = array();
        // foreach ($layer as $key => $value) {
        //     foreach ($table as $k => $v) {
        //         if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
        //             // $arr[$value['name']][] = $v['name'];
        //             $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
        //         }
        //     }
        // }
        if (empty($list)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' =>  $this->class2($list)]);
            // apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' =>  $arr]);
        }
    }

    //预约订单，查询桌位号
    public function get_reservation_seats(){
    	$business_id = I('post.business_id');
        if (empty($business_id)) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);

        $this->business_status($business_id);//查询商户状态

        $list = M('table')->where(array('admin_id' => $business_id))->field('id,name,pid')->select();

        // $layer = M('table')->where(array('admin_id' => $business_id, 'pid' => 0))->field('id, name, pid')->select();
        // $table = M('table')->where(array('admin_id' => $business_id, 'pid' => array('gt', 0)))->field('id, name, pid')->select();

        // $arr = array();
        // foreach ($layer as $key => $value) {
        //     foreach ($table as $k => $v) {
        //         if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
        //             // $arr[$value['name']][] = $v['name'];
        //             $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
        //         }
        //     }
        // }
        if (empty($list)) {
            apiReturn(['status' => -1, 'msg' => '没有数据']);
        } else {
            apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' =>  $this->class2_reservation($list)]);
            // apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' =>  $arr]);
        }
    }



    /**
     * 查询订单信息
     */
    public function get_order_info()
    {   
        $order_sn = I('post.order_sn');
        if (empty($order_sn)) apiReturn(['status' => -1, 'msg' => '订单编号不能为空']);

        $info = M('order')
            ->join('am_car ON am_order.car_id = am_car.id')
            ->field('am_order.order_sn,am_order.kexiao_sn, am_order.qucan_time, delivery, boxes, price, seat, status, order_type, mark, am_order.create_time, pay_time, fachu_time, address_name, address_phone, address_area, address_info, meals_num, am_car.car_content, am_order.admin_id')
            ->where(array('am_order.order_sn' => $order_sn))
            ->find();

        if (empty($info)) apiReturn(['status' => -1, 'msg' => '订单不存在']);

        $info['car_content'] = unserialize($info['car_content']);
        foreach ($info['car_content'] as $k => &$v) {
            $v['title'] = M('goods')->where(array('id' => $v['goods_id']))->getField('title');
            $v['img'] = 'https://'.$_SERVER['SERVER_NAME'].'/canyin/Uploads/'.$this->get_goods_info($v['goods_id'])['img'];
            //获取属性标题2018-6-25
            if($v['attr_id']){
                $attr=array_filter(explode(",", $v['attr_id']));
                $text="";
                foreach ($attr as $key => $value) {
                    $goodsattr = M('goods_attr')->where('id='.$value)->find();
                    if($key==0){
                      $text=$goodsattr['attr_title'];
                    }else{
                      $text.="+".$goodsattr['attr_title'];
                    }
                }

                $v['attr_title']=$text;
            }
        }

        // 外卖订单--查看配送信息
        $info['is_dada'] = 0;// 不显示达达配送信息  默认不显示达达信息
        if ($info['order_type'] == 1) {
            $api_controller = new ApiController();
            $dada_ie_status = $api_controller->get_dada_ie($info['admin_id']);// 获取达达配送实例
            // 请求配送订单状态
            if ($dada_ie_status['code'] == 200){
                $info['dada_order'] = $api_controller->dada->query(array('order_id' => $info['order_sn']));
                $info['is_dada'] = 1;// 显示达达配送信息
            }
        }
        unset($info['admin_id']);
        apiReturn(['status' => 1, 'msg' => '已获取订单数据', 'data' => $info]);
    }

    /**
     * 提交预约订单
     */
    public function create_app_order()
    {
        $data = I('post.');

        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['time'])) apiReturn(['status' => -1, 'msg' => '日期不能为空']);
        if (empty($data['time_interval'])) apiReturn(['status' => -1, 'msg' => '用餐时段不能为空']);
        if (empty($data['nums'])) apiReturn(['status' => -1, 'msg' => '用餐人数不能为空']);
        if (empty($data['name'])) apiReturn(['status' => -1, 'msg' => '联系人不能为空']);
        if (empty($data['mobile'])) apiReturn(['status' => -1, 'msg' => '联系方式不能为空']);
        if (empty($data['table_id'])) apiReturn(['status' => -1, 'msg' => '桌位号id不能为空']);
        if (empty($data['user_id'])) apiReturn(['status' => -1, 'msg' => '用户id参数不能为空']);
        // if (empty($data['app_status'])) apiReturn(['status' => -1, 'msg' => '是否需要定金参数不能为空']);

        $add = array(
                'admin_id' => $data['business_id'],
                'time' => $data['time'],
                'time_interval' => $data['time_interval'],
                'nums' => $data['nums'],
                'table_id' => $data['table_id'],
                'name' => $data['name'],
                'mobile' => $data['mobile'],
                'status' => 1,
                // 'app_status' => $data['app_status'],
                'create_time' => time(),
                'user_id' => $data['user_id']
            );

        // if ($data['app_status'] == 1) {
        //     if (empty($data['money'])) apiReturn(['status' => -1, 'msg' => '定金不能为空']);

        //     $add['money'] = $data['money'];
        // }

        $result = M('appointment')->add($add);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '提交成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '提交失败']);
        }
    }

    /**
     * 获取预约订单列表
     */
    public function get_app_list()
    {
        $data = I('post.');

        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['user_id'])) apiReturn(['status' => -1, 'msg' => '用户id不能为空']);
        // if (empty($data['page'])) apiReturn(['status' => -1, 'msg' => '分页参数不能为空']);

        $list = M('appointment')->field('time, time_interval, nums, name, mobile, status, table_id, create_time')->where(array('admin_id' => $data['business_id'], 'user_id' => $data['user_id']))->select();
        if (empty($list)) apiReturn(['status' => -1, 'msg' => '没有数据']);

        foreach ($list as $key => &$value) {
                $value['table'] = '';
                $table_info = M('table t')
                            ->join('LEFT JOIN am_table tp ON tp.id = t.pid')
                            ->where(array('t.id' => $value['table_id']))
                            ->field('t.name, tp.name pname')
                            ->find();
                            
                $value['table'] = $table_info['pname'].' '.$table_info['name'];
                unset($list[$k]['table_id']);
                $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            }

        apiReturn(['status' => 1, 'msg' => '已获取数据', 'data' => $list]);
    }

    /**
     * 确认预约订单
     */
    public function sure_o()
    {
        $data = I('post.');

        if (empty($data['id'])) {
            $this->ajaxReturn(['status' => -1, 'msg' => 'id不能为空']);die;
        }

        $result = M('appointment')->where(array('id' => $data['id']))->setField('status', 2);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '确认成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '确认失败']);
        }
    }

    /**
     * [reduction 获取满减信息]
     * @AuthorHTL
     * @DateTime  2018-03-15T16:04:18+0800
     * @return    [type]                   [description]
     */
    public function reduction()
    {
        $data = I('post.');

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

        $list = M('reduction')->where(array('admin_id' => $data['business_id']))->field('id, full_money, reduction_money')->select();

        if (empty($list)) {
            $this->ajaxReturn(['status' => -1, 'msg' => '满减活动为空']);
        }

        $this->ajaxReturn(['status' => 1, 'msg' => '已获取活动信息', 'data' => $list]);
    }

    /**
     * [order_cancle 订单取消]
     * @AuthorHTL
     * @DateTime  2018-03-16T18:23:11+0800
     * @return    [type]                   [description]
     */
    public function order_cancle()
    {
        $data = I('post.');

        if (empty($data['order_sn'])) $this->ajaxReturn(['status' => -1, 'msg' => '订单编号为空']);

        $result = M('order')->where(array('order_sn' => $data['order_sn']))->setField('status', 5);

        if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '订单取消成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '订单取消失败']);
        }
    }

    // public function get_app_config()
    // {
    //     $data = I('post.');

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

    //     $info = M('appointment_config')->where(array('admin_id' => $data['business_id']))->find();

    //     if (empty($info)) {
    //         M('appointment_config')->add(array('admin_id' => $data['business_id'], 'create_time' => time()));
    //          $info = M('appointment_config')->where(array('admin_id' => $data['business_id']))->find();
    //     }

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

    private function class2($array = array())
    {
        if (!is_array($array)) return false;
        $arr = array();
        foreach ($array as $key => $value) {
            if ($value['pid'] == 0) {
                foreach ($array as $k => $v) {
                    if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
                        $arr[$value['name']][] = $v['name'];
                        // $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
                    }
                }
            }
        }
        return $arr;
    }

    private function class2_reservation($array = array())
    {
        if (!is_array($array)) return false;
        $arr = array();
        foreach ($array as $key => $value) {
            if ($value['pid'] == 0) {
                foreach ($array as $k => $v) {
                    if ($v['pid'] != 0 && $v['pid'] == $value['id']) {
                        $arr[$value['name']][] = array('table_id' => $v['id'],'name' => $v['name']);
                        // $arr[$value['name']][] = ['id' => $v['id'], 'name' => $v['name']];
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 获取商品信息
     */
    private function get_goods_info($id = '')
    {
        $info = M('goods')->where(array('id' => $id))->field('img')->find();
        return $info;
    }

    /**
     * 添加购物车信息
     */
    private function add_car($data = '')
    {
        // $data = I('post.');
        // $this->check_param($data);
        if (empty($data['car_content'])) apiReturn(['status' => -1, 'msg' => '购物车信息不能为空']);

        $temp = array();
        foreach ($data['car_content'] as $key => $vo) {
            $vo['price'] = $vo['sum_price'] / $vo['goods_num'];
            $temp[] = $vo;
        }
        $data['car_content'] = $temp;
        $data['car_content'] = serialize($data['car_content']);
        $data['admin_id'] = $data['business_id'];
        unset($data['business_id']);
        $data['create_time'] = time();

        if ($insert_id = M('car')->add($data)) {
           return $insert_id;
        } else {
            return false;
        }
    }

    /**
     * 检查参数
     */
    private function check_param($data = '')
    {
        if (empty($data['business_id'])) apiReturn(['status' => -1, 'msg' => '商户id不能为空']);
        if (empty($data['users_id'])) apiReturn(['status' => -1, 'msg' => '用户id不能为空']); 
    }

    /**
     * 查询商户状态
     */
    private function business_status($business_id = '')
    {
        $result = M('admin')->where('id = '.$business_id.' AND is_business <> 2')->field('status')->select();
        if (empty($result)) {
            apiReturn(['status' => -1, 'msg' => '该商户不存在']);
        } elseif ($result[0]['status'] == -1) {
            apiReturn(['status' => -1, 'msg' => '该商户已被禁用']);
        }
    }

    /**
     * [check_user_pre 用户生成订单检测优惠券使用合法性]
     * @AuthorHTL
     * @DateTime  2018-02-26T10:44:23+0800
     * @param     [type]                   $user_pre_info [用户优惠券信息]
     * @param     [type]                   $sum_money   [消费总金额]
     * @return    [type]                                [description]
     */
    private function check_user_pre($user_pre_info, $sum_money)
    {   
        if (empty($user_pre_info)) return ['status' => -1, 'msg' => '没有此优惠券，订单自动取消！'];
        if ($user_pre_info['status'] == 2)  return ['status' => -1, 'msg' => '优惠券已使用，无法使用优惠券，订单自动取消！'];
        if ($user_pre_info['end_time'] <= time() && $user_pre_info['status'] == 1)  return ['status' => -1, 'msg' => '优惠券已过期，无法使用优惠券，订单自动取消！'];
        if ($sum_money < $user_pre_info['full_money']) return ['status' => -1, 'msg' => '消费金额没有满￥'.$user_pre_info['full_money'].'，无法使用优惠券，订单自动取消！'];

        return ['status' => 1, 'msg' => '使用优惠券合法'];
    }

    /**
     * 删除订单
     * @param  string $user_id  [用户编号]
     * @param  string $order_sn [订单编号]
     */
    public function delOrderInfo ($user_id = "", $order_sn = ""){
    	if (empty($user_id) || empty($order_sn)) {
    		$this->ajaxReturn(array("status"=>-1,"msg"=>'请检查参数'),"JSON");
    	}
    	$result = M('order')->where(array('order_sn' => $order_sn,"uid"=>$user_id))->setField('is_del', 1);
    	if ($result) {
            $this->ajaxReturn(['status' => 1, 'msg' => '订单删除成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '订单删除失败']);
        }
    }

    /**
     * 订单完成
     * @param  string $user_id  [用户编号]
     * @param  string $order_sn [订单编号]
     */
    public function completeOrder($user_id = "", $order_sn = ""){
    	if (empty($user_id) || empty($order_sn)) {
    		$this->ajaxReturn(array("status"=>-1,"msg"=>'请检查参数'),"JSON");
    	}
    	$result = M('order')->where(array('order_sn' => $order_sn,"uid"=>$user_id))->setField('status', 3);
    	if ($result) {
            ShareLogicController::send_share($order_sn);
            $this->ajaxReturn(['status' => 1, 'msg' => '结束订单成功']);
        } else {
            $this->ajaxReturn(['status' => -1, 'msg' => '结束订单失败']);
        }
    }
}