<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\Order;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\Bargain;
use app\common\model\bbfxshop\Pintuan;

class OrderCreate
{

    public static function confirm($params){
        global $_W;
        $user = $params['user'];
        $user_id = $params['user_id'];
        if(empty($user)){
            $user = User::getInfo($user_id);
        }

        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $set = $_W['base'];

        $goods_id = intval($params['goods_id']);
        $total = max(1,intval($params['total']));
        $coupon_id = intval($params['coupon_id']);
        $address_id = intval($params['address_id']);
        $sku_id = intval($params['sku_id']);
        $bargain_goods_id = intval($params['bargain_goods_id']);
        $pintuan_goods_id = intval($params['pintuan_goods_id']);
        $pintuan_order_id = intval($params['pintuan_order_id']);

        // 0=普通订单，1=秒杀订单，2=拼团订单，3=砍价订单
        $create_type = intval($params['create_type']);

        if(!empty($params['cart_id']) && $create_type == 0){
            // 购物车
            $cart_id = explode(",",$params['cart_id']);
            $cart = Db::name("bbfx_user_cart")->where(['id'=>['in',$cart_id],'user_id'=>$user['id']])->select();
            if(empty($cart)){
                return __json(0,"购物车数据错误");
            }
            $goods_ids = [];
            foreach($cart as $key => $val){
                $goods_ids[] = $val['goods_id'];
            }
            $goods_list = Db::name("bbfx_goods")->where(['id'=>['in',$goods_ids],'status'=>1])->select();
            
            if(empty($goods_list)){
                return __json(0,"购物车商品信息错误");
            }
            
            $goods_list = array_skey($goods_list,"id");
            
            $goods = [];
            foreach($cart as $key => $val){
                if(empty($goods_list[$val['goods_id']])){
                    return __json(0,"购物车商品信息错误");
                }
                
                $info = $goods_list[$val['goods_id']];
                $info['total'] = $val['total'];
                if($info['is_spec'] == 1){
                    $sku = Db::name("bbfx_goods_spec_sku")->where(['id'=>$val['sku_id']])->find();
                    if(empty($sku)){
                        return __json(0,"请选择规格");
                    }
                    if(!empty($sku['thumb'])){
                        $info['thumb'] = cdnurl($sku['thumb']);
                    }
                    $info['sku'] = $sku;
                    $info['sku_id'] = $sku['id'];
                    $info['price'] = $sku['price'];
                    $info['sku_name'] = $sku['sku_name'];
                    
                }
                $goods[] = $info;
            }
            
        }
        else{

            if($create_type == 3){
                $bargain_goods = Db::name("bbfx_bargain_goods")->where(['uniacid'=>UNIACID,'id'=>$bargain_goods_id,'status'=>1])->find();
                if(empty($bargain_goods)){
                    return __json(0,"砍价商品不存在");
                }
                $goods_id = $bargain_goods['goods_id'];
            }
            else if($create_type == 2){
                $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['uniacid'=>UNIACID,'id'=>$pintuan_goods_id,'status'=>1])->find();
                if(empty($pintuan_goods)){
                    return __json(0,"拼团商品不存在");
                }
                $goods_id = $pintuan_goods['goods_id'];
            }

            $goods = Db::name("bbfx_goods")->where(['id'=>$goods_id,'status'=>1])->select();
            if(empty($goods)){
                return __json(0,"商品不存在或已下架");
            }

            if($create_type == 3){
                $goods[0]['bargain_goods'] = $bargain_goods;
            }
            else if($create_type == 2){
                $goods[0]['pintuan_goods'] = $pintuan_goods;
            }
            
            if($goods[0]['is_spec'] == 1){
                $sku = Db::name("bbfx_goods_spec_sku")->where(['id'=>$sku_id])->find();
                if(empty($sku)){
                    return __json(0,"请选择规格");
                }
                if(!empty($sku['thumb'])){
                    $goods[0]['thumb'] = cdnurl($sku['thumb']);
                }
                $goods[0]['sku'] = $sku;
                $goods[0]['sku_id'] = $sku['id'];
                $goods[0]['price'] = $sku['price'];
                $goods[0]['sku_name'] = $sku['sku_name'];
            }
            $goods[0]['total'] = $total;
        }
        
        if(empty($goods)){
            return __json(0,"商品数据错误");
        }
        
        $delivery_method_list = [];
        $delivery_method = 0;
        if($goods[0]['type'] == 2){
            $g_delivery_method = $goods[0]['delivery_method'];
            $delivery_method = intval($params['delivery_method']);
            $arr = [];
            if($g_delivery_method == 1 || $g_delivery_method == 3){
                $delivery_method_list[] = ['name'=>'快递配送','value'=>1];
                $arr[] = 1;
            }
            if($g_delivery_method == 2 || $g_delivery_method == 3){
                $delivery_method_list[] = ['name'=>'门店核销','value'=>2];
                $arr[] = 2;
            }
            if(!in_array($delivery_method,$arr)){
                $delivery_method = $arr[0];
            }
            if(empty($delivery_method)){
                $delivery_method = 1;
            }
        }
        else if(($goods[0]['type'] == 4 && $goods[0]['is_hexiao'] == 1) || $goods[0]['type'] == 3){
            $delivery_method = 2;
            $delivery_method_list[] = ['name'=>'门店核销','value'=>2];
        }

        $is_gift_goods = 0;
        $hexiao_info_required = 0;
        $is_cloud_warehouse = 0;
        $cloud_warehouse_num = 0;
        $is_repurchase_currency_pay = 0;
        foreach($goods as $key => $val){
            $plugin =  iunserializer($val['plugin']);
            $pay = $plugin['pay'];
            if(is_null($pay['weixin_pay'])){
                $pay['weixin_pay'] = 1;
            }
            if(is_null($pay['balance_pay'])){
                $pay['balance_pay'] = 1;
            }
            if(is_null($pay['repurchase_currency_pay'])){
                $pay['repurchase_currency_pay'] = 1;
            }
            if(is_null($pay['zfb_pay'])){
                $pay['zfb_pay'] = 1;
            }
            if($pay['weixin_pay'] != 1 && $pay['balance_pay'] != 1 && $pay['zfb_pay'] != 1 && $pay['repurchase_currency_pay'] == 1){
                $is_repurchase_currency_pay = 1;
            }
            if($is_repurchase_currency_pay == 0 && $pay['repurchase_currency_pay'] != 1){
                // $is_repurchase_currency_pay = 2;
            }
            if($plugin['gift']['status'] == 1){
                $is_gift_goods = 1;
            }
            if($val['hexiao_info_required'] == 1){
                $hexiao_info_required = 1;
            }
            if($set['cloud_warehouse']['status'] == 1){
                $cw_goods = explode(",",(string)$set['cloud_warehouse']['cw_goods']);
                if(in_array($val['id'],$cw_goods)){
                    $is_cloud_warehouse = 1;
                    $cloud_warehouse_num++;
                }
            }
        }
        
        $levels = FenxiaoLevel::getLevels(1);

        if($create_type == 3){
            $result = Bargain::calculateMoney($goods,$user,$delivery_method,$address_id);
        }
        else if($create_type == 2){
            $result = Pintuan::calculateMoney($goods,$user,$delivery_method,$pintuan_order_id,$address_id);
        }
        else{

            if($is_cloud_warehouse == 1 && $cloud_warehouse_num == count($goods)){
                if($levels[$user['level']]['sort'] >= $levels[$set['cloud_warehouse']['level']]['sort'] && $user['is_distributor'] == 1 && $user['distributor_status'] == 1){
                    $delivery_method_list = [];
                    $delivery_method = 0;
                }
            }

            $is_first = intval($params['is_first']);
            if($is_first == 1 && $coupon_id == 0){
                $user_coupon_id = \app\common\model\bbfxshop\Coupon::autoUseCoupon($user,$goods);
                if(!empty($user_coupon_id)){
                    $coupon_id = $user_coupon_id;
                }
            }

            $result = Order::calculateMoney($goods,$user,$coupon_id,$delivery_method,$address_id,$is_first);
        }
        
        $total_fee = $result['total_price'];
        $total_price = $result['total_price'];
        $totalNum = $result['totalNum'];
        $express_fee = $result['express_fee'];
        $discount_price = $result['discount_price'];
        $original_price = $result['original_price'];

        if($is_cloud_warehouse == 1){
            $cloud_warehouse_level = $set['cloud_warehouse']['level'];
            if($user['is_distributor'] == 1 && $user['distributor_status'] == 1){
                if($levels[$user['level']]['sort'] >= $levels[$cloud_warehouse_level]['sort']){
                    $express_fee = 0;
                }
            }
        }
            
        $total_fee = round($total_price + $express_fee,2);

        foreach ($goods as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
        }
        unset($val);
        
        $order_repurchase_currency = 0;
        if($is_repurchase_currency_pay === 0 && $set['is_repurchase_currency_deduct'] == 1){
            $repurchase_currency = floatval($user['repurchase_currency']);
            if($repurchase_currency > 0){
                if($total_fee > $repurchase_currency){
                    $order_repurchase_currency = $repurchase_currency;
                    $total_fee = round($total_fee - $repurchase_currency,2);
                }
                else{
                    $order_repurchase_currency = $total_fee;
                    $total_fee = 0;
                }
            }
        }
        
        $plugin = iunserializer($goods[0]['plugin']);
        $form_list = [];
        if($plugin['form']['status'] == 1){
            $form_list = $plugin['form']['list'];
        }
        
        $data = array(
            'is_cloud_warehouse'=>$is_cloud_warehouse,
            'form_list'=>$form_list,
            'goods'=>$goods,
            'total_fee'=>$total_fee,
            'order_repurchase_currency'=>$order_repurchase_currency,
            'original_price'=>$original_price,
            'discount_price'=>$discount_price,
            'float_price'=>$result['float_price'],
            'discount_vip_price'=>$result['discount_vip_price'],
            'discount_coupon_price'=>$result['discount_coupon_price'],
            'discount_bargain_price'=>$result['discount_bargain_price'],
            'totalNum'=>$totalNum,
            'total_price'=>$total_price,
            'delivery_method_list'=>$delivery_method_list,
            'delivery_method'=>$delivery_method,
            'express_fee'=>$express_fee,
            'hexiao_info_required'=>$hexiao_info_required,
            'is_gift_goods'=>$is_gift_goods
        );
        if(!empty($result['coupon'])){
            $data['coupon'] = $result['coupon'];
        }

        return __json(1,"操作成功",$data);
    }

    public static function create($params){
        global $_W;
        $user = $params['user'];
        $user_id = $params['user_id'];
        if(empty($user)){
            $user = User::getInfo($user_id);
        }

        if(empty($user)){
            return __json(0,"用户不存在");
        }

        $set = $_W['base'];
        
        $goods_id = intval($params['goods_id']);
        $address_id = intval($params['address_id']);
        $total = max(1,intval($params['total']));
        $coupon_id = intval($params['coupon_id']);
        $sku_id = intval($params['sku_id']);
        $store_id = intval($params['store_id']);
        $bargain_goods_id = intval($params['bargain_goods_id']);
        $pintuan_goods_id = intval($params['pintuan_goods_id']);
        $pintuan_order_id = intval($params['pintuan_order_id']);
        $form = $params['form_list'];
        $address = $params['address'];

        // 0=普通订单，1=秒杀订单，2=拼团订单，3=砍价订单
        $create_type = intval($params['create_type']);

        User::checkStatus($user);
        
        if($set['fenxiao']['sup_user_buyorder'] == 1){
            if($user['sup_uid'] <= 0 && $user['first_sup_uid'] <= 0){
                $first_uid = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->order("id asc")->value("id");
                if($first_uid != $user['id']){
                    return __json(0,"您还没有推荐人，无法下单");
                }
            }
        }
        
        if(!empty($params['cart_id']) && $create_type == 0){
            // 购物车
            $cart_id = explode(",",$params['cart_id']);
            $cart = Db::name("bbfx_user_cart")->where(['id'=>['in',$cart_id],'user_id'=>$user['id']])->select();
            if(empty($cart)){
                return __json(0,"购物车数据错误");
            }
            $goods_ids = [];
            foreach($cart as $key => $val){
                $goods_ids[] = $val['goods_id'];
            }
            $goods_list = Db::name("bbfx_goods")->where(['id'=>['in',$goods_ids],'status'=>1])->select();
            
            if(empty($goods_list)){
                return __json(0,"购物车商品信息错误");
            }
            
            $goods_list = array_skey($goods_list,"id");
            
            $goods = [];
            foreach($cart as $key => $val){
                if(empty($goods_list[$val['goods_id']])){
                    return __json(0,"购物车商品信息错误");
                }
                
                $info = $goods_list[$val['goods_id']];
                $info['total'] = $val['total'];
                if($info['is_spec'] == 1){
                    $sku = Db::name("bbfx_goods_spec_sku")->where(['id'=>$val['sku_id']])->find();
                    if(empty($sku)){
                        return __json(0,"请选择规格");
                    }
                    if(!empty($sku['thumb'])){
                        $info['thumb'] = cdnurl($sku['thumb']);
                    }
                    $info['sku'] = $sku;
                    $info['sku_id'] = $sku['id'];
                    $info['price'] = $sku['price'];
                    $info['stock'] = $sku['stock'];
                    $info['sku_name'] = $sku['sku_name'];
                    $info['profit_amount'] = $sku['profit_amount'];
                    $info['cost_price'] = $sku['cost_price'];
                }
                $goods[] = $info;
            }
            
        }
        else{
            
            if($create_type == 99){
                $params['platform'] = $user['platform'];
                $goods_all = $params['goods'];
                if(empty($goods_all)){
                    return __json(0,"请选择下单商品");
                }
                
                $goods_ids = [];
                foreach($goods_all as $key => $val){
                    $goods_ids[] = $val['id'];
                }
                $goods_list = Db::name("bbfx_goods")->where(['id'=>['in',$goods_ids],'status'=>1])->select();
                
                if(empty($goods_list)){
                    return __json(0,"下单商品信息错误");
                }

                $goods_list = array_skey($goods_list,"id");
                $goods = [];
                foreach($goods_all as $key => $val){
                    if(empty($goods_list[$val['id']])){
                        return __json(0,"下单商品信息错误");
                    }
                    
                    $info = $goods_list[$val['id']];
                    $info['total'] = $val['total'];
                    if($info['is_spec'] == 1){
                        $sku = Db::name("bbfx_goods_spec_sku")->where(['id'=>$val['sku_id']])->find();
                        if(empty($sku)){
                            return __json(0,"请选择规格");
                        }
                        if(!empty($sku['thumb'])){
                            $info['thumb'] = cdnurl($sku['thumb']);
                        }
                        $info['sku'] = $sku;
                        $info['sku_id'] = $sku['id'];
                        $info['price'] = $sku['price'];
                        $info['sku_name'] = $sku['sku_name'];
                        
                    }
                    $goods[] = $info;
                    $order_type = $info['type'];;
                }
                $delivery_method = intval($params['delivery_method']);
                if($order_type == 2 && $delivery_method == 1){
                    if(empty($address)){
                        return __json(0,"请填写收货信息");
                    }
                    if(empty($address['consignee'])){
                        return __json(0,"请填写收货人");
                    }
                    if(empty($address['phone'])){
                        return __json(0,"请填写收货人电话");
                    }
                    if(empty($address['province_name'])){
                        return __json(0,"请填写收货人地址");
                    }  
                }
            }
            else{
                if($create_type == 3){
                    $bargain_goods = Db::name("bbfx_bargain_goods")->where(['uniacid'=>UNIACID,'id'=>$bargain_goods_id,'status'=>1])->find();
                    if(empty($bargain_goods)){
                        return __json(0,"砍价商品不存在");
                    }
                    $goods_id = $bargain_goods['goods_id'];

                    if($bargain_goods['etime'] < time()){
                        return __json(0,"砍价活动已结束");
                    }
                }
                else if($create_type == 2){
                    $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['uniacid'=>UNIACID,'id'=>$pintuan_goods_id,'status'=>1])->find();
                    if(empty($pintuan_goods)){
                        return __json(0,"拼团商品不存在");
                    }
                    if($pintuan_goods['status'] != 1){
                        return __json(0,"拼团活动已结束");
                    }
                    if($pintuan_order_id > 0){
                        $pintuan_order = Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order_id])->find();
                        if(empty($pintuan_order)){
                            return __json(0,"您参与的拼团不存在");
                        }
                        if($pintuan_order['status'] !== 0){
                            return __json(0,"您参与的拼团已结束");
                        }
                        if($pintuan_order['residue'] == 0){
                            return __json(0,"您参与的拼团人数已满");
                        }
                    }
                    else{
                        if($set['pintuan']['status'] != 1){
                            return __json(0,"拼团未开启，不可开团");
                        } 
                    }
                    $goods_id = $pintuan_goods['goods_id'];
                }

                $goods = Db::name("bbfx_goods")->where(['id'=>$goods_id,'status'=>1])->select();
                if(empty($goods)){
                    return __json(0,"商品不存在或已下架");
                }
                if($goods[0]['is_spec'] == 1){
                    $sku = Db::name("bbfx_goods_spec_sku")->where(['id'=>$sku_id])->find();
                    if(empty($sku)){
                        return __json(0,"请选择规格");
                    }
                    if(!empty($sku['thumb'])){
                        $goods[0]['thumb'] = cdnurl($sku['thumb']);
                    } 
                    $goods[0]['sku'] = $sku;
                    $goods[0]['sku_id'] = $sku['id'];
                    $goods[0]['stock'] = $sku['stock'];
                    $goods[0]['price'] = $sku['price'];
                    $goods[0]['sku_name'] = $sku['sku_name'];
                    $goods[0]['profit_amount'] = $sku['profit_amount'];
                    $goods[0]['cost_price'] = $sku['cost_price'];
                }
                
                $goods[0]['total'] = $total;

                if($create_type == 3){
                    $goods[0]['bargain_goods'] = $bargain_goods;
                }
                else if($create_type == 2){
                    $goods[0]['pintuan_goods'] = $pintuan_goods;
                }
            }
        }
        
        if(!empty($form)){
            foreach ($form as $key => $val){
                if($val['required'] && empty($val['value'])){
                    return __json(0,"请填写".$val['label']);
                }
            }
        }
        
        if(empty($goods)){
            return __json(0,"商品不存在");
        }
        
        $levels = FenxiaoLevel::getLevels(1);
        
        try {
        	Db::startTrans();
        	
        	$order_type = 0;
        	
        	$goods_ids = [];
        	
        	$is_cloud_warehouse = -1;
        	$cw_goods = explode(",",(string)$set['cloud_warehouse']['cw_goods']);
        	$profit_amount = 0;
        	$cost_price = 0;
        	$mid = 0;
        	$is_crazy = 0;
        	$is_super_maihuo = 0;
        	$is_repurchase_currency_pay = 0;
            $gift_status = -1;
            $goods_gift_status = intval($params['goods_gift_status']);
            $is_hexiao_quantity = 0;
        	$cloud_warehouse_num = 0;
            $is_salequota = 0;
            $yuyue_status = 0;

        	foreach ($goods as $key => $item){
        	    $plugin = iunserializer($item['plugin']);
                $pay = $plugin['pay'];
                if($item['type'] == 3 && $item['yuyue_status'] == 1){
                    $yuyue_status = 1;
                }

                if($plugin['salequota']['status'] == 1){
                    if($key != 0){
                        throw new \Exception("开始销售配额商品不可与其他商品一起下单");
                    }
                    $is_salequota = 1;
                }
                else{
                    if($is_salequota == 1){
                        throw new \Exception("开始销售配额商品不可与其他商品一起下单");
                    }
                }
                
                if(is_null($pay['weixin_pay'])){
                    $pay['weixin_pay'] = 1;
                }
                if(is_null($pay['balance_pay'])){
                    $pay['balance_pay'] = 1;
                }
                if(is_null($pay['repurchase_currency_pay'])){
                    $pay['repurchase_currency_pay'] = 1;
                }
                if(is_null($pay['zfb_pay'])){
                    $pay['zfb_pay'] = 1;
                }
                if($pay['weixin_pay'] != 1 && $pay['balance_pay'] != 1 && $pay['zfb_pay'] != 1 && $pay['repurchase_currency_pay'] == 1){
                    $is_repurchase_currency_pay = 1;
                }
                if($is_repurchase_currency_pay == 0 && $pay['repurchase_currency_pay'] != 1){
                    // $is_repurchase_currency_pay = 2;
                }
                
                if($set['crazy']['status'] == 1){
                    $crazy = $plugin['crazy'];
                    if($crazy['status'] == 1 && intval($crazy['crazy_portion']) > 0){
                        $is_crazy = 1;
                        if($key != 0){
                            throw new \Exception("疯狂卖货模式商品不可与其他商品一起下单1");
                        }
                    }
                    else{
                        if($is_crazy == 1){
                            throw new \Exception("疯狂卖货模式商品不可与其他商品一起下单2");
                        }
                    }
                }
                
                if($set['super_maihuo']['status'] == 1){
                    $super_maihuo = $plugin['super_maihuo'];
                    if($super_maihuo['status'] == 1 && intval($super_maihuo['super_maihuo_portion']) > 0){
                        $is_super_maihuo = 1;
                        if($key != 0){
                            throw new \Exception("超级卖货模式商品不可与其他商品一起下单");
                        }
                    }
                    else{
                        if($is_super_maihuo == 1){
                            throw new \Exception("超级卖货模式商品不可与其他商品一起下单");
                        }
                    }
                }
                
        	    if($set['cloud_warehouse']['status'] == 1){
                    if(in_array($item['id'],$cw_goods)){
                        if($is_cloud_warehouse == 0){
                            throw new \Exception("云仓商品不能和其他商品一起下单");
                        }
                        $is_cloud_warehouse = 1;
                        $cloud_warehouse_num++;
                        
                        $goods[$key]['is_cloud_warehouse'] = 1;
                    }
                    else{
                        if($is_cloud_warehouse == 1){
                            throw new \Exception("云仓商品不能和其他商品一起下单");
                        }
                        $is_cloud_warehouse = 0;
                    }
                }

                if($set['gift']['status'] == 1){
                    $gift = $plugin['gift'];
                    if($gift['status'] == 1){
                        $gift_status = 0;
                        if($key > 0){
                            throw new \Exception('礼品商品不能和其他商品一起下单');
                        }
                    }
                    else{
                        if($gift_status === 0){
                            throw new \Exception('礼品商品不能和其他商品一起下单');
                        }
                    }
                }
                if($gift_status === 0 && $is_cloud_warehouse == 1){
                    throw new \Exception('礼品商品不能绑定云仓商品');
                }
        	    
        	    if($mid == 0 && $item['mid'] > 0){
        	        $mid = $item['mid'];
        	        if($key != 0){
        	            throw new \Exception("商品不属于同一门店商品，不可下单");
        	        }
        	    }
        	    else{
        	        if($mid != $item['mid']){
        	            throw new \Exception("商品不属于同一门店商品，不可下单");
        	        }
        	    }

        	    $goods_ids[] = $item['id'];
        	    if($order_type == 0){
        	        $order_type = $item['type'];
        	    }
        	   
        	    if($item['type'] != $order_type){
        	        if($order_type == 1 || $order_type == 4){
        	            throw new \Exception("虚拟商品不能和其他类型商品通过购物车一起下单【{$item['title']}】");
        	        }
        	        else if($order_type == 2){
        	            throw new \Exception("实物商品不能和其他类型商品通过购物车一起下单【{$item['title']}】");
        	        }
        	        else if($order_type == 3){
        	            throw new \Exception("服务商品不能和其他类型商品通过购物车一起下单【{$item['title']}】");
        	        }
        	        else{
        	            throw new \Exception("未知商品类型不能和其他类型商品通过购物车一起下单【{$item['title']}】");
        	        }
        	    }
        	    $total = max(1,intval($item['total']));
        	    $profit_amount += $total * $item['profit_amount'];
        	    $cost_price += $total * $item['cost_price'];
        	    $result = CloudWarehouse::checkStock($user['id'],$total,$item['id']);
        	    if($result['code'] != 1){
        	        throw new \Exception($result['message']);
        	    }
        	    
                $minbuy = max(1,intval($item['minbuy']));
                $maxbuy = intval($item['maxbuy']);
                $total_maxbuy = intval($item['total_maxbuy']);
                $daily_buy = intval($item['daily_buy']);
                $monthly_buy = intval($item['monthly_buy']); 
                if($total < $minbuy){
                    throw new \Exception("单次最低购买{$minbuy}{$item['unit']}【{$item['title']}】");
                }
                if($maxbuy > 0 && $total > $maxbuy){
                    throw new \Exception("单次最多购买{$maxbuy}{$item['unit']}【{$item['title']}】");
                }
                if($total_maxbuy > 0){
                    $user_total_maxbuy = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","o.id=og.order_id")->where(['o.uniacid'=>UNIACID,'o.refund_status'=>['in',[-1,2]],'o.user_id'=>$user['id'],'og.goods_id'=>$item['id']])->count();
                    $user_total_maxbuy = intval($user_total_maxbuy);
                    if(($user_total_maxbuy + $total) > $total_maxbuy){
                        throw new \Exception("最多可购买{$total_maxbuy}{$item['unit']}【{$item['title']}】");
                    }
                }
                if($daily_buy > 0){
                    $user_daily_buy = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","o.id=og.order_id")->where(['o.uniacid'=>UNIACID,'o.refund_status'=>['in',[-1,2]],'o.user_id'=>$user['id'],'og.goods_id'=>$item['id'],'o.createtime'=>['>',strtotime(date("Y-m-d 00:00:00"))],'o.status'=>['>=',0]])->count();
                    $user_daily_buy = intval($user_daily_buy);
                    if(($user_daily_buy + $total) > $daily_buy){
                        $buy_num = $daily_buy - $user_daily_buy;
                        if($buy_num == 0){
                            throw new \Exception("每日最多购买{$daily_buy}{$item['unit']}【{$item['title']}】");
                        }
                        else{
                            throw new \Exception("今日最多还可购买{$buy_num}{$item['unit']}【{$item['title']}】");
                        }
                    }
                }
                if($monthly_buy > 0){
                    $user_monthly_buy = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","o.id=og.order_id")->where(['o.uniacid'=>UNIACID,'o.refund_status'=>['in',[-1,2]],'o.user_id'=>$user['id'],'og.goods_id'=>$item['id'],'o.createtime'=>['>',strtotime(date("Y-m-01 00:00:00"))],'o.status'=>['>=',0]])->count();
                    $user_monthly_buy = intval($user_monthly_buy);
                    if(($user_monthly_buy + $total) > $monthly_buy){
                        $buy_num = $monthly_buy - $user_monthly_buy;
                        if($buy_num == 0){
                            throw new \Exception("每月最多购买{$monthly_buy}{$item['unit']}【{$item['title']}】");
                        }
                        else{
                            throw new \Exception("本月最多还可购买{$buy_num}{$item['unit']}【{$item['title']}】");
                        }
                    }
                }
                $glevels = iunserializer($item['levels']);
                if($user['is_distributor'] != 1 || $user['distributor_status'] != 1){
                    $user['level'] = -1;
                }
                if(!empty($glevels) && !in_array($user['level'],$glevels)){
                    if(!empty($set['buylevel_tips'])){
                        throw new \Exception($set['buylevel_tips']);
                    }
                    else{
                        throw new \Exception("商品【{$item['title']}】当前等级不能购买");
                    }
                }
        	    
                if($item['type'] == 1){
                    $serial_number = Db::name("bbfx_serial_number")->where(["uniacid"=>UNIACID,'status'=>0,"goods_id"=>$item['id']])->select();
                    if(empty($serial_number) || count($serial_number) < $total){
                        throw new \Exception("库存不足【{$item['title']}】");
                    }
                }
                else{
                    if($item['stock'] < $total){
                        throw new \Exception("库存不足【{$item['title']}】");
                    }
                }
                if($create_type == 3){
                    if($item['bargain_goods']['stock'] < $total){
                        throw new \Exception("库存不足【{$item['title']}】");
                    }
                    // Db::name("bbfx_bargain_goods")->where(['id'=>$item['bargain_goods']['id']])->setDec("stock",$total);
                }
                else if($create_type == 2){
                    if($item['pintuan_goods']['is_sync_stock'] != 1){
                        if($item['pintuan_goods']['stock'] < $total){
                            throw new \Exception("库存不足【{$item['title']}】");
                        }
                        // Db::name("bbfx_pintuan_goods")->where(['id'=>$item['pintuan_goods']['id']])->setDec("stock",$total);
                    }
                }
            }
            
            $delivery_method = 0;
            $is_hexiao = 0;
            if($order_type == 2){
                $g_delivery_method = $goods[0]['delivery_method'];
                $delivery_method = intval($params['delivery_method']);
                $delivery_method_list = [];
                $arr = [];
                if($g_delivery_method == 1 || $g_delivery_method == 3){
                    $arr[] = 1;
                }
                if($g_delivery_method == 2 || $g_delivery_method == 3){
                    $arr[] = 2;
                }
                if(!in_array($delivery_method,$arr)){
                    $delivery_method = $arr[0];
                }
                
                if($delivery_method == 2){
                    $is_hexiao = 1;
                }
            }
            else if(($order_type == 4 && $goods[0]['is_hexiao'] == 1) || $order_type == 3){
                $delivery_method = 2;
                $is_hexiao = 1;
            }
            $hexiao_info_required = 0;
            $hexiao_store_type = 0;
            foreach ($goods as $key => $item){
                if($item['hexiao_info_required'] == 1){
                    $hexiao_info_required = 1;
                }
                if($is_hexiao == 1){
                
                    if($item['hexiao_store_type'] == 1){
                        $store_goods = Db::name("bbfx_store_goods")->where(['uniacid'=>UNIACID,'goods_id'=>$item['id']])->find();
                        if(empty($store_goods)){
                            throw new \Exception("商品核销门店错误【{$item['title']}】");
                        }
                        $store_id = $store_goods['store_id'];
                        $hexiao_store_type = 1;
                    }
                    
                    if($is_hexiao_quantity == 0 && $item['is_hexiao_quantity'] == 1){
                        if($key > 0){
                            throw new \Exception("已开启核销数量不可和其他商品下单");
                        }
                        $is_hexiao_quantity = 1;
                    }
                    else{
                        if($is_hexiao_quantity == 1){
                            throw new \Exception("已开启核销数量不可和其他商品下单");
                        }
                    }
                }

            }
            $create_method = 0;
            $is_bargain_order = 0;
            if($create_type == 3){
                $result = Bargain::calculateMoney($goods,$user,$delivery_method,$address_id);
                $order_source = 10;
                $is_bargain_order = 1;
                if($bargain_goods['buy_interval_day'] > 0){
                    $buy_interval_day_time = strtotime(date('Y-m-d 00:00:00')." -".$bargain_goods['buy_interval_day']." day");
                }
                else{
                    $buy_interval_day_time = strtotime(date('Y-m-d 00:00:00'));
                }

                $bargain_order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'createtime'=>['>',$buy_interval_day_time],'user_id'=>$user['id'],'is_bargain_order'=>$is_bargain_order])->order("id desc")->find();
                if(!empty($bargain_order)){
                    if($bargain_goods['buy_interval_day'] > 0){
                        throw new \Exception("请间隔".$bargain_goods['buy_interval_day']."天后购买");
                    }
                    else{
                        throw new \Exception("您今日已购买过该商品");
                    }
                }
            }
            else if($create_type == 2){
                // throw new \Exception("创建类型错误");
                $result = Pintuan::calculateMoney($goods,$user,$delivery_method,$pintuan_order_id,$address_id);
                $order_source = 3;
                if($result['pintuan_order_id'] == 0){
                
                    $tz_price = $pintuan_goods['price'];
                    $pintuan_price = $pintuan_goods['price'];
                    if($pintuan_goods['is_tuanzhangyh'] == 1){
                        $tz_price = $pintuan_goods['kaituan_price'];
                    }
                    if($goods[0]['is_spec'] == 1){
                        $tz_price = $goods[0]['sku']['pintuan_price'];
                        if($pintuan_goods['is_tuanzhangyh'] == 1){
                            $tz_price = $goods[0]['sku']['kaituan_price'];
                        }
                        $pintuan_price = $goods[0]['sku']['pintuan_price'];
                    }
                    
                    $pintuan_order = array(
                        "uniacid"=>UNIACID,
                        "mid"=>$mid,
                        "pintuan_goods_id"=>$pintuan_goods['id'],
                        "total"=>$pintuan_goods['pintuan_num'],
                        "residue"=>$pintuan_goods['pintuan_num']-1,
                        "tz_user_id"=>$user['id'],
                        "tz_price"=>$tz_price,
                        "price"=>$pintuan_price,
                        "status"=>-1,
                        "goods"=>iserializer($goods[0]),
                        "createtime"=>time()
                    );
                    
                    $pintuan_order_id = Db::name("bbfx_pintuan_order")->insertGetId($pintuan_order);
                    if(empty($pintuan_order_id)){
                        throw new \Exception("创建拼团订单失败");
                    }
                }
                else{
                    $pintuan_order_id = $result['pintuan_order_id'];
                }
            }
            else if($create_type == 99){
                $result = Order::calculateMoney($goods,$user,$coupon_id,$delivery_method,$address,0);
                $order_source = 7;
                $create_method = 1;
            }
            else{
                $result = Order::calculateMoney($goods,$user,$coupon_id,$delivery_method,$address_id,0);
                $order_source = 0;
            }
            
            
            
            // throw new \Exception("订单类型：".$order_type);
            
            $price = floatval($result['total_price']);
            $express_fee = floatval($result['express_fee']);
            $original_price = floatval($result['original_price']);
            $discount_price = floatval($result['discount_price']);
            if($price <= 0){
                $price = 0;
                // throw new \Exception("订单金额错误");
            }
            $total_price = $original_price;
            
            $order_no = date('YmdHis').random(8,true);  
            $remarks = $params['remarks'];
            $order = array(
                "uniacid"=>UNIACID,
                "mid"=>$mid,
                "order_no"=>$order_no,
                'store_id'=>$store_id,
                "user_id"=>$user['id'],
                "order_type"=>$order_type,
                "price"=>$price,
                "profit_amount"=>$profit_amount,
                "cost_price"=>$cost_price,
                "total_price"=>$original_price,
                "float_price"=>$result['float_price'],
                "discount_vip_price"=>round($result['discount_vip_price'],2),
                "discount_coupon_price"=>round($result['discount_coupon_price'],2),
                "discount_bargain_price"=>round($result['discount_bargain_price'],2),
                "discount_price"=>$discount_price,
                "original_price"=>$original_price,
                "goods_info"=>iserializer($goods),
                'remarks'=>$remarks,
                'platform'=>$params['platform'],
                'is_cloud_warehouse'=>$is_cloud_warehouse,
                'delivery_method'=>$delivery_method,
                'is_hexiao'=>$is_hexiao,
                'is_crazy'=>$is_crazy,
                'is_super_maihuo'=>$is_super_maihuo,
                'gift_status'=>$gift_status,
                'is_hexiao_quantity'=>$is_hexiao_quantity,
                'pintuan_order_id'=>intval($pintuan_order_id),
                'sup_path'=>$user['sup_path'],
                'order_source'=>$order_source,
                'is_bargain_order'=>$is_bargain_order,
                'create_method'=>$create_method,
                'yuyue_status'=>$yuyue_status,
                'deduct_stock'=>0,
                "createtime"=>time()
            );
            $extend = []; 
            if(!empty($form)){
                $extend['form'] = $form;
            }
            $order['extend'] = iserializer($extend);
            if($is_cloud_warehouse == 1 && $cloud_warehouse_num == count($goods)){
                if($levels[$user['level']]['sort'] >= $levels[$set['cloud_warehouse']['level']]['sort'] && $user['is_distributor'] == 1 && $user['distributor_status'] == 1){
                    // $order['order_source'] = 8;
                }
            }

            
            $price_data = $result['price_data'];
            
            if(!empty($result['coupon'])){
                $order['user_coupon_id'] = $result['coupon']['id'];
                if($result['coupon']['type'] == 1){
                    $res = Db::name("bbfx_user_coupon")->where(["id"=>$result['coupon']['id'],'user_id'=>$user['id'],'status'=>0])->setDec("residue_money",$result['discount_coupon_price']);
                    if($res){
                        $residue_money = Db::name("bbfx_user_coupon")->where(["id"=>$result['coupon']['id'],'status'=>0])->value("residue_money");
                        $residue_money = floatval($residue_money);
                        if($residue_money == 0){
                            Db::name("bbfx_user_coupon")->where(["id"=>$result['coupon']['id'],'user_id'=>$user['id'],'status'=>0])->update(['status'=>1]);
                        }
                    }
                }
                else{
                    $res = Db::name("bbfx_user_coupon")->where(["id"=>$result['coupon']['id'],'user_id'=>$user['id'],'status'=>0])->update(['status'=>1]);
                }
                
                if(empty($res)){
                    throw new \Exception("优惠券错误");
                }
            }
            
            if($order_type == 2 && $delivery_method == 1){
                
                if(($gift_status == -1 && $order['order_source'] != 8) || ($gift_status != -1 && $goods_gift_status != 1)){

                    if($create_type == 99){
                        $address = $params['address'];
                    }
                    else{
                        $address = Db::name("bbfx_user_address")->where(['id'=>$address_id])->find();
                    }
                    if(empty($address)){
                        throw new \Exception("请选择收货地址");
                    }

                    $order['delivery_username'] = $address['consignee'];
                    $order['delivery_mobile'] = $address['phone'];
                    $order['delivery_province'] = $address['province_name'];
                    $order['delivery_city'] = $address['city_name'];
                    $order['delivery_area'] = $address['area_name'];
                    $order['delivery_street'] = $address['street_name'];
                    $order['delivery_address'] = $address['address'];
                }

                $is_cloud_warehouse_user = false;
                if($is_cloud_warehouse == 1){
                    $cloud_warehouse_level = $set['cloud_warehouse']['level'];
                    if($user['is_distributor'] == 1 && $user['distributor_status'] == 1){
                        if($levels[$user['level']]['sort'] >= $levels[$cloud_warehouse_level]['sort']){
                            $is_cloud_warehouse_user = true;
                        }
                    }
                }

                if(!$is_cloud_warehouse_user){
                    $order['express_fee'] = $express_fee;
                    $order['price'] = $price + $express_fee;
                    $order['total_price'] = $original_price + $express_fee;
                }
            }
            else if(($order_type == 2 && $delivery_method == 2) || ($order_type == 4 && $is_hexiao == 1) || $order_type == 3){

                if($gift_status == -1 && $hexiao_info_required == 1 && $order['order_source'] != 8){
                    if(empty($params['hexiao_realname'])){
                        throw new \Exception("请输入姓名");
                    }
                    if(empty($params['hexiao_mobile'])){
                        throw new \Exception("请输入联系方式");
                    }
                    $order['hexiao_realname'] = $params['hexiao_realname'];
                    $order['hexiao_mobile'] = $params['hexiao_mobile'];
                    Db::name("bbfx_user")->where(['id'=>$user['id']])->update(['hexiao_realname'=>$order['hexiao_realname'],'hexiao_mobile'=>$order['hexiao_mobile']]);
                }
                else{
                    if((!empty($params['hexiao_realname']) && empty($params['hexiao_mobile'])) || (empty($params['hexiao_realname']) && !empty($params['hexiao_mobile']))){
                        throw new \Exception("请填写完整核销信息");
                    }
                }

                if(!empty($params['hexiao_realname']) && !empty($params['hexiao_mobile'])){
                    $order['hexiao_realname'] = $params['hexiao_realname'];
                    $order['hexiao_mobile'] = $params['hexiao_mobile'];
                }
                
                if($mid > 0){
                    // $store = Db::name("bbfx_store")->where(['id'=>$store_id,'mid'=>$mid,'uniacid'=>UNIACID])->field("id,name,logo,realname,mobile,province,city,area,address,lat,lng")->find();
                    $store = Db::name("bbfx_store")->where(['type'=>1,'main'=>1,'mid'=>$mid,'uniacid'=>UNIACID])->field("id,name,logo,realname,mobile,province,city,area,address,lat,lng")->find();
                    if(empty($store)){
                        throw new \Exception("请选择核销门店");
                    }
                }
                else{
                    
                    $store = Db::name("bbfx_store")->where(['id'=>$store_id,'type'=>0,'mid'=>0,'uniacid'=>UNIACID])->field("id,name,logo,realname,mobile,province,city,area,address,lat,lng")->find();
                    if(empty($store) && $hexiao_store_type == 1){
                        throw new \Exception("商品指定的核销门店信息错误");
                    }
                }
                
                
                $order['hexiao_total'] = max(1,$goods[0]['hexiao_num']);
                $order['hexiao_num'] = max(1,$goods[0]['hexiao_num']);
                $order['hexiao_code'] = random(9,true);
                if(!empty($store)){
                    $order['hexiao_store'] = iserializer($store);
                }
            }
            
            
            $order_repurchase_currency = 0;
            if($is_repurchase_currency_pay === 0 && $set['is_repurchase_currency_deduct'] == 1 && $create_type != 99){
                $repurchase_currency = floatval($user['repurchase_currency']);
                if($repurchase_currency > 0){
                    if($order['price'] > $repurchase_currency){
                        $order_repurchase_currency = $repurchase_currency;
                    }
                    else{
                        $order_repurchase_currency = $order['price'];
                    }
                }
                $order['repurchase_currency'] = $order_repurchase_currency;
            }
            
            $order_id = Db::name("bbfx_order")->insertGetId($order);
            if(empty($order_id)){
                throw new \Exception("创建订单失败");
            }
            
            $order['id'] = $order_id;
            
            if($order_repurchase_currency > 0){
                $res = User::setUserMoney($user['id'],-$order_repurchase_currency,4,1,"商品支付",$order);
                if(empty($res)){
                    throw new \Exception("创建订单失败");
                }
            }
            
            
            foreach ($goods as $key => $item){
                $total = max(1,intval($item['total']));
                $profit_amount = $item['profit_amount'] * $total;
                $cost_price = $item['cost_price'] * $total;
                $upgrade_score = $item['upgrade_score'] * $total;
                $item['upgrade_score'] = $upgrade_score;
                $plugin = iunserializer($item['plugin']);
                $manabonus_money = 0;
                if(!empty($plugin['manabonus']) && $plugin['manabonus']['status'] == 1){
                    $manabonus_money = $plugin['manabonus']['money'] * $total;
                }
                $apabonus_money = 0;
                if(!empty($plugin['apabonus']) && $plugin['apabonus']['status'] == 1){
                    $apabonus_money = $plugin['apabonus']['money'] * $total;
                }
                if(empty($plugin['fenxiao'])){
                    $plugin['fenxiao'] = ['achievement_jisuan'=>1];
                }
                $is_achievement_jisuan = $plugin['fenxiao']['achievement_jisuan'];
                $order_goods = array(
                    "uniacid"=>UNIACID,
                    "mid"=>$mid,
                    "order_id"=>$order_id,
                    "user_id"=>$user['id'],
                    "total"=>$total,
                    "profit_amount"=>$profit_amount,
                    "cost_price"=>$cost_price,
                    "price"=>$price_data[$key]['price'],
                    "total_price"=>$price_data[$key]['total_price'],
                    "float_price"=>$price_data[$key]['float_price'],
                    "discount_price"=>$price_data[$key]['discount_price'],
                    "discount_vip_price"=>$price_data[$key]['discount_vip_price'],
                    "discount_coupon_price"=>$price_data[$key]['discount_coupon_price'],
                    "discount_bargain_price"=>$price_data[$key]['discount_bargain_price'],
                    "goods_id"=>$item['id'],
                    "upgrade_score"=>$upgrade_score,
                    "manabonus_money"=>$manabonus_money,
                    "apabonus_money"=>$apabonus_money,
                    "is_cloud_warehouse"=>intval($item['is_cloud_warehouse']),
                    "goods_info"=>iserializer($item),
                    "is_achievement_jisuan"=>$is_achievement_jisuan,
                    "createtime"=>time()
                );
                
                if(!empty($item['sku'])){
                    $order_goods['sku_id'] = $item['sku_id'];
                    $order_goods['sku_name'] = $item['sku_name'];
                    $order_goods['sku'] = iserializer($item['sku']);
                }
                
                if(!empty($price_data[$key]['user_coupon_id'])){
                    $order_goods['user_coupon_id'] = $price_data[$key]['user_coupon_id'];
                }
                
                if($price_data[$key]['type'] == 1){
                    $order_goods['type'] = 1;
                    $order_goods['seckill_activity_id'] = $price_data[$key]['seckill_activity_id'];
                    $order_goods['seckill_goods_id'] = $price_data[$key]['seckill_goods_id'];
                }

                if($create_type == 3){ 
                    $order_goods['bargain_goods_id'] = $item['bargain_goods']['id'];
                }
                else if($create_type == 2){ 
                    $order_goods['pintuan_goods_id'] = $item['pintuan_goods']['id'];
                }
                
                $og_id = Db::name("bbfx_order_goods")->insertGetId($order_goods);
                if(empty($og_id)){
                    throw new \Exception("创建订单失败");
                }
                
                $order_goods['id'] = $og_id;
                
                if($item['stock_type'] == 1){
                    // $result = Goods::setStock($item['id'],intval($item['sku_id']),-$total,$user['id'],1,1,"用户下单",$order_goods,false);
                    
                    // if($result['code'] != 1){
                    //     throw new \Exception($result['message']."【{$item['title']}】");
                    // }
                }

                if((($order_type == 2 && $delivery_method == 2) || ($order_type == 4 && $is_hexiao == 1) || $order_type == 3) && $is_hexiao_quantity == 1){
                    for ($i = 0;$i < $total;$i++){
                        $hxcode_data = [
                            "uniacid"=>UNIACID,
                            "order_id"=>$order_id,
                            "pid"=>$og_id,
                            "goods_id"=>$item['id'],
                            "hexiao_total"=>max(1,$item['hexiao_num']),
                            "hexiao_num"=>max(1,$item['hexiao_num']),
                            "hexiao_code"=>random(9,true),
                            "createtime"=>time()
                        ];
                        Db::name("bbfx_order_goods_hxcode")->insertGetId($hxcode_data);
                    }
                }
            }
        	
        	
        	Db::commit();
        } catch (\Exception $e) {
        	Db::rollback();
            if(strstr($e->getMessage(), 'stock')){
                return __json(0,'库存不足');
            }
        	return __json(0,$e->getMessage());
        }
        
        if(!empty($params['cart_id'])){
            Db::name("bbfx_user_cart")->where(['id'=>['in',$cart_id],'user_id'=>$user['id']])->delete();
        }
        
        /*
        try {
            Fenxiao::settlement($order_id);
        } 
        catch (\Exception $e) {}
        try {
            Agent::settlement($order_id); 
        } 
        catch (\Exception $e) {}
        */
        try {
            $printer = $set['printer'];
            if(!empty($printer) && $printer['printer_type'] == 1){
                // \app\common\model\bbfxshop\Printer::orderPrint($order['id']);
            }
        } 
        catch (\Exception $e) {}

        return __json(1,"操作成功",['order_no'=>$order_no,'order_id'=>$order_id,'price'=>$order['price']]);
    }
}