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

namespace app\api\controller\pintuan;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\Fenxiao;
use app\common\model\bbfxshop\Agent;

class Order extends Base
{
    protected $noNeedLogin = ['detail'];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Pintuan;
    }

    public function getList(){
        $status = $this->param("status/d");
        $where = ['a.uniacid'=>UNIACID,'a.is_pay'=>1,'a.order_source'=>3,'a.user_id'=>$this->user['id']];
        if($status == 1){
            $where['b.status'] = 0;
        }
        else if($status == 2){
            $where['b.status'] = 1;
        }
        else if($status == 3){
            $where['b.status'] = 2;
        }
        else{
            $where['b.status'] = ['>=',0];
        }

        $order_list = Db::name("bbfx_order")->alias("a")->join("bbfx_pintuan_order b","a.pintuan_order_id=b.id","LEFT")->where($where)->order("a.id desc")->field("b.*,a.order_no,a.is_pay,a.id as order_id")->select();
        $list = [];
        foreach ($order_list as $key => &$val){

            if($val['status'] == 1 && $val['is_pay'] == 0){
                continue;
            }

            $user_list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where(['a.uniacid'=>UNIACID,'a.is_pay'=>1,'a.pintuan_order_id'=>$val['id']])->field("a.id,a.user_id,b.nickname,b.avatar")->order("a.id asc")->select();
            
            foreach ($user_list as $k => &$v){
                $v['avatar'] = cdnurl($v['avatar']);
            }
            unset($v);
            $user_list[0]['is_tuanzhang'] = 1;
            $val['user_list'] = $user_list;
            $val['pintuan_num_ok'] = count($user_list);
            $val['progress'] = intval(($val['pintuan_num_ok'] / $val['total']) * 100);
            $downtime = 0;
            if($val['endtime'] > 0){
                $downtime = $val['endtime'] - time();
            }
            if($downtime < 0){
                $downtime = 0;
            }
            $val['downtime'] = $downtime;

            $list[] = $val;
        }
        __success("操作成功",['list'=>$list]);
    }

    public function confirm(){
        $params = $this->param(['goods_id/d','pintuan_goods_id/d','total/d','coupon_id/d','sku_id/d','address_id/d','store_id/d','pintuan_order_id/d','delivery_method/d']);
        $user = $this->user;
        $params['user_id'] = $user['id'];
        $params['user'] = $user;
        $params['create_type'] = 2;
        $result = \app\common\model\bbfxshop\OrderCreate::confirm($params);

        __result($result);
    }

    public function submit(){
        $params = $this->param(['goods_id/d','pintuan_goods_id/d','total/d','coupon_id/d','sku_id/d','address_id/d','store_id/d','pintuan_order_id/d','delivery_method/d','platform/s','hexiao_realname/s','hexiao_mobile/s','remarks/s']);
        $user = $this->user;
        $params['user_id'] = $user['id'];
        $params['user'] = $user;
        
        $params['create_type'] = 2;

        $result = \app\common\model\bbfxshop\OrderCreate::create($params);

        __result($result);
    }

    public function confirm1(){
        $params = $this->param(['goods_id/d','pintuan_goods_id/d','total/d','coupon_id/d','sku_id/d','address_id/d','store_id/d','pintuan_order_id/d','delivery_method/d']);
        
        $user = $this->user;
        
        $goods_id = intval($params['goods_id']);
        $total = max(1,intval($params['total']));
        $coupon_id = intval($params['coupon_id']);
        $sku_id = intval($params['sku_id']);
        
        $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$params['pintuan_goods_id'],'status'=>1])->find();
        
        if(empty($pintuan_goods)){
            __error("商品已下架");
        }
        
        $goods = Db::name("bbfx_goods")->where(['id'=>$pintuan_goods['goods_id'],'status'=>1])->select();
        
        if(empty($goods)){
            __error("商品已下架");
        }
        
        $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)){
                __error("请选择规格");
            }
            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;
        
        $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){
            $delivery_method = 2;
            $delivery_method_list[] = ['name'=>'门店核销','value'=>2];
        }
        
        $result = $this->model->calculateMoney($goods,$user,$delivery_method,$params['pintuan_order_id']);
        
        $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'];
        $total_fee = round($total_price + $express_fee,2);
        foreach ($goods as $key => &$val){
            $val['thumb'] = cdnurl($val['thumb']);
        }
        unset($val);
        
        $order_repurchase_currency = 0;
        $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;
            }
        }
        
        $data = array(
            'goods'=>$goods,
            'total_fee'=>$total_fee,
            'order_repurchase_currency'=>$order_repurchase_currency,
            'original_price'=>$original_price,
            'discount_price'=>$discount_price,
            'totalNum'=>$totalNum,
            'total_price'=>$total_price,
            'delivery_method_list'=>$delivery_method_list,
            'delivery_method'=>$delivery_method,
            'express_fee'=>$express_fee
        );
        
        __success("操作成功",$data);
    }
    
    public function submit1(){
        global $_W;
        $params = $this->param(['goods_id/d','pintuan_goods_id/d','total/d','coupon_id/d','sku_id/d','address_id/d','store_id/d','pintuan_order_id/d','delivery_method/d','platform/s','hexiao_realname/s','hexiao_mobile/s','remarks/s']);
        
        $user = $this->user;
        
        $goods_id = intval($params['goods_id']);
        $address_id = intval($params['address_id']);
        $total = max(1,intval($params['total']));
        $sku_id = intval($params['sku_id']);
        $store_id = intval($params['store_id']);
        $pintuan_order_id = intval($params['pintuan_order_id']);
        $form = $params['form_list'];
        User::checkStatus($user);
        
        $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$params['pintuan_goods_id'],'status'=>1])->find();
         
        if(empty($pintuan_goods)){
            __error("商品已下架");
        }
        
        // if($pintuan_goods['is_limitedtime'] == 1 && $pintuan_goods['endtime'] < time()){
        if($pintuan_goods['status'] != 1){
            __error("拼团活动已结束");
        }
        
        $goods = Db::name("bbfx_goods")->where(['id'=>$pintuan_goods['goods_id'],'status'=>1])->select();
        
        if(empty($goods)){
            __error("商品已下架");
        }
        
        $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)){
                __error("请选择规格");
            }
            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;
        
        $set = $_W['base'];
        
        if($pintuan_order_id > 0){
            $pintuan_order = Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order_id])->find();
            if(empty($pintuan_order)){
                __error("您参与的拼团不存在");
            }
            if($pintuan_order['status'] !== 0){
                __error("您参与的拼团已结束");
            }
            if($pintuan_order['residue'] == 0){
                __error("您参与的拼团人数已满");
            }
        }
        else{
            if($set['pintuan']['status'] != 1){
                __error("拼团未开启，不可开团");
            } 
        }

        if(!empty($form)){
            foreach ($form as $key => $val){
                if($val['required'] && empty($val['value'])){
                    __error("请填写".$val['label']);
                }
            }
        }
        
        $levels = \app\common\model\bbfxshop\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;
            $is_hexiao_quantity = 0;
            $is_salequota = 0;
        	foreach ($goods as $key => $item){
        	    $plugin = iunserializer($item['plugin']);
                $pay = $plugin['pay'];

                if($plugin['salequota']['status'] == 1){
                    $is_salequota = 1;
                }
                else{
                    $is_salequota = 0;
                }
                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;
                }
                $crazy = $plugin['crazy'];
                if($crazy['status'] == 1 && intval($crazy['crazy_portion']) > 0){
                    $is_crazy = 1;
                    if($key != 0){
                        throw new \Exception("疯狂卖货模式商品不可与其他商品一起下单");
                    }
                }
                else{
                    if($is_crazy == 1){
                        throw new \Exception("疯狂卖货模式商品不可与其他商品一起下单");
                    }
                }
                
                $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 && in_array($goods['id'],$cw_goods)){
        	        $is_cloud_warehouse = 1;
        	    }
        	    else{
        	        $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($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("商品不属于同一门店商品，不可下单");
        	        }
        	    }
        	    
        	    if($set['cloud_warehouse']['status'] == 1 && in_array($goods['id'],$cw_goods)){
        	        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 = \app\common\model\bbfxshop\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']])->field([])->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]])->field([])->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("每日最多购买{$user_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']}】");
                        }
                    }
                }

                $levels = iunserializer($item['levels']);
                if(!empty($levels) && !in_array($user['level'],$levels)){
                    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($item['stock_type'] == 1){
                        if(!empty($item['sku'])){
                            $res = Db::name("bbfx_goods_spec_sku")->where(['id'=>$item['sku_id']])->setDec("stock",$total);
                        }
                        else{
                            $res = Db::name("bbfx_goods")->where(['id'=>$item['id']])->setDec("stock",$total);
                        }
                        if(empty($res)){
                            Db::name("bbfx_pintuan_goods")->where(['id'=>$item['pintuan_goods']['id']])->setDec("stock",$total);
                            throw new \Exception("库存不足【{$item['title']}】");
                        }
                    }
                }
                
            }
            
            $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){
                $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("已开启核销数量不可和其他商品下单");
                        }
                    }
                }
            }
            
            $result = $this->model->calculateMoney($goods,$user,$delivery_method,$params['pintuan_order_id']);
            
            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,
                    "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'];
            }
            
            // throw new \Exception("订单金额错误");
            
            $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,
                "order_no"=>$order_no,
                'store_id'=>$store_id,
                "user_id"=>$user['id'],
                "order_type"=>$order_type,
                "order_source"=>3,
                "price"=>$price,
                "profit_amount"=>$profit_amount,
                "total_price"=>$original_price,
                "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,
                'pintuan_order_id'=>$pintuan_order_id,
                "cost_price"=>$cost_price,
                'is_crazy'=>$is_crazy,
                'is_super_maihuo'=>$is_super_maihuo,
                'gift_status'=>$gift_status,
                'is_hexiao_quantity'=>$is_hexiao_quantity,
                "createtime"=>time()
            );
            
            $extend = []; 
            if(!empty($form)){
                $extend['form'] = $form;
            }
            $order['extend'] = iserializer($extend);
            
            $order_repurchase_currency = 0;
            $repurchase_currency = floatval($user['repurchase_currency']);
            if($repurchase_currency > 0){
                if($price > $repurchase_currency){
                    $order_repurchase_currency = $repurchase_currency;
                }
                else{
                    $order_repurchase_currency = $price;
                }
            }
            $order['repurchase_currency'] = $order_repurchase_currency;
            
            $price_data = $result['price_data'];
            
            
            if($order_type == 2 && $delivery_method == 1){
                $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'];
                
                $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)){

                if($hexiao_info_required == 1){
                    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']]);
                }
                
                
                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();
                    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(8,true);
                if(!empty($store)){
                    $order['hexiao_store'] = iserializer($store);
                }
            }

            $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;
                $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,
                    "order_id"=>$order_id,
                    "user_id"=>$user['id'],
                    "total"=>$total,
                    "profit_amount"=>$profit_amount,
                    "price"=>$price_data[$key]['price'],
                    "total_price"=>$price_data[$key]['total_price'],
                    "discount_price"=>$price_data[$key]['discount_price'],
                    "goods_id"=>$item['id'],
                    "upgrade_score"=>$upgrade_score,
                    "manabonus_money"=>$manabonus_money,
                    "apabonus_money"=>$apabonus_money,
                    "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']);
                }
                
                $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("创建订单失败");
                }

                if((($order_type == 2 && $delivery_method == 2) || ($order_type == 4 && $is_hexiao == 1)) && $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();
        	$msg = $e->getMessage();
        	
        	__error($msg);
        }
        
        /*
        try {
            Fenxiao::settlement($order_id);
        } 
        catch (\Exception $e) {}
        try {
            Agent::settlement($order_id); 
        } 
        catch (\Exception $e) {}
        */
         
        __success("操作成功",["order_no"=>$order_no]);
        
    }


    
    public function detail(){
        $params = $this->param(['pintuan_order_id/d','platform/s']);
        $pintuan_order = Db::name("bbfx_pintuan_order")->where(['uniacid'=>UNIACID,'id'=>$params['pintuan_order_id'],'status'=>['>',-1]])->find();
        if(empty($pintuan_order)){
            __error("拼团数据不存在");
        }
        
        if($pintuan_order['status'] !== 0){
            __error("拼团已结束");
        }
        
        $goods = Db::name("bbfx_pintuan_goods")->alias("a")->join("bbfx_goods b","a.goods_id=b.id")->where(['a.uniacid'=>UNIACID,'a.status'=>1,'b.status'=>1,'a.id'=>$pintuan_order['pintuan_goods_id']])->field("a.*,b.title,b.subtitle,b.thumb,b.is_spec,b.price as o_price,b.slides,b.videos,b.content,b.unit")->find();
        
        if(empty($goods)){
            __error("拼团商品不存在或已下架");
        }
        
    	$goods['thumb'] = cdnurl($goods['thumb']);
    	$slides = [];
  	    $videos_list = cdnurls(iunserializer($goods['videos']));
  	    if(!empty($videos_list)){
  	        foreach ($videos_list as $key => &$val){
                  $slides[] = ['type'=>'video','url'=>$val];
              }
              unset($val);
  	    }
  	    $slides_list = cdnurls(iunserializer($goods['slides']));
  	    if(!empty($slides_list)){
              foreach ($slides_list as $key => &$val){
                  $slides[] = ['type'=>'image','url'=>$val];
              }
              unset($val);
          }
  	    $goods['slides'] = $slides;
  	    $goods['images'] = $slides_list;
  	    $goods['videos'] = $videos_list;
        
        $user_list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where(['a.uniacid'=>UNIACID,'a.is_pay'=>1,'a.pintuan_order_id'=>$pintuan_order['id']])->field("a.id,a.user_id,b.nickname,b.avatar,a.createtime")->order("a.id asc")->select();
        foreach ($user_list as $k => &$v){
            $v['avatar'] = cdnurl($v['avatar']);
            $v['createtime'] = date("m-d H:i:s",$v['createtime']);
            $invite_num = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where(['a.uniacid'=>UNIACID,'a.is_pay'=>1,'a.pintuan_order_id'=>$pintuan_order['id'],'b.sup_uid'=>$v['user_id']])->count();
            $v['invite_num'] = $invite_num;
        }
        unset($v);
        $user_list[0]['is_tuanzhang'] = 1;
        $pintuan_order['user_list'] = $user_list;
        $pintuan_order['pintuan_num_ok'] = count($user_list);
        $pintuan_order['progress'] = intval(($pintuan_order['pintuan_num_ok'] / $pintuan_order['total']) * 100);
        $pintuan_order['pintuan_residue'] = $pintuan_order['total'] - $pintuan_order['pintuan_num_ok'];
        $downtime = 0;
        if($pintuan_order['endtime'] > 0){
            $downtime = $pintuan_order['endtime'] - time();
        }
        if($downtime < 0){
            $downtime = 0;
        }
        $pintuan_order['downtime'] = $downtime;

        $page = "plugin/pintuan/pintuan_list/pintuan_list?id={$pintuan_order['id']}";
        if(!empty($this->user)){
            $page .= "&sup_uid=".$this->user['id'];
        }
        if($params['platform'] == 'wxapp' || $params['platform'] == 'WXAPP'){
            $result = \app\common\model\bbfxshop\Weixin::getUnlimitedQRCode($page, "pintuan_order_wxacode_{$pintuan_order['uniacid']}_".intval($this->user['id'])."_".$pintuan_order['id']);
        }
        else{
            $url = request()->domain()."/mobile/#/".$page;
            $result = \app\common\model\QRcode::create($url, "pintuan_order_qrcode_{$pintuan_order['uniacid']}_".intval($this->user['id'])."_".$pintuan_order['id']);
        }
        $pintuan_order['pintuan_order_qrcode'] = '';
        if($result['code'] == 1){
            $pintuan_order['pintuan_order_qrcode'] = cdnurl($result['data']['url'].'?t='.time()); 
        }

        __success("操作成功",['pintuan_order'=>$pintuan_order,'goods'=>$goods,'user_list'=>$user_list]);
    }
}