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

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\Order;
use app\common\model\bbfxshop\Printer;
use app\common\model\bbfxshop\RebatePintuan;
use app\common\model\bbfxshop\PintuanMiandan;

class Pintuan extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        return $base['pintuan'];
    }
    
    public static function jisuan(){
        $uniacid = UNIACID;
        $config = self::getSet();
        if($config['status'] != 1){
            return __json(0,"未开启拼团活动");
        }
        
        $goods = Db::name("bbfx_pintuan_goods")->where(['uniacid'=>$uniacid])->field("id,auto_pintuan_success")->select();
        
        $goods = array_skey($goods,"id");
        $pintuan_order_list = Db::name("bbfx_pintuan_order")->where(['uniacid'=>$uniacid,'status'=>0])->order("id asc")->select();
        
        foreach ($pintuan_order_list as $key => $val){
            $endtime = $val['endtime'];
            $is_end = false;
            
            $total = (int)$val['total'];
                
            $pintuan_num = Db::name("bbfx_order_goods")->alias("a")->join("bbfx_order b","a.order_id=b.id")->where(['b.uniacid'=>$uniacid,'b.is_pay'=>1,'b.order_source'=>3,'b.pintuan_order_id'=>$val['id'],'b.refund_status'=>-1])->count();
            $pintuan_num = intval($pintuan_num);
            
            if($pintuan_num >= $total){
                $is_end = true;
            }
            else{
                if(($endtime > 0 && $endtime <= time()) || empty($goods[$val['pintuan_goods_id']])){
                    $is_end = true;
                }
            }
            
            if($is_end){
                
                $auto_pintuan_success = $goods[$val['pintuan_goods_id']]['auto_pintuan_success'];
                if($auto_pintuan_success == 1 && $pintuan_num < $total){
                    $pintuan_num = $total;
                }
                
                if($pintuan_num >= $total){
                    self::success($val);
                }
                else{
                    self::fail($val);
                }
            }
        }
        
    }
    
    public function success($pintuan_order){
        global $_W;
        $uniacid = $pintuan_order['uniacid'];
        
        $res = Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id'],'status'=>0])->update(['status'=>1]);
        if(empty($res)){
            return false;
        }
        Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id']])->update(['jiesuantime'=>time()]);
        Db::name("bbfx_order")->where(['pintuan_order_id'=>$pintuan_order['id']])->update(['pintuan_status'=>1]);
        
        $order_list = Db::name("bbfx_order")->where(['uniacid'=>$uniacid,'is_pay'=>1,'refund_status'=>['in',[-1,2]],'pintuan_order_id'=>$pintuan_order['id'],'order_source'=>3])->select();
        
        $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$pintuan_order['pintuan_goods_id']])->find();
        $plugin = iunserializer($pintuan_goods['plugin']);
        $rebate_pintuan = $_W['base']['rebate_pintuan'];
        $pintuan_miandan = $_W['base']['pintuan_miandan'];
        $rebate_pintuan_goods = $plugin['rebate_pintuan'];
        $pintuan_miandan_goods = $plugin['pintuan_miandan'];
        if($rebate_pintuan['status'] == 1 && $rebate_pintuan_goods['status'] == 1){
            RebatePintuan::jiesuan($pintuan_order,$order_list,$pintuan_goods);
            return true;
        }
        else{
            if($pintuan_miandan['status'] == 1 && $pintuan_miandan_goods['status'] == 1){
                PintuanMiandan::jiesuan($pintuan_order,$order_list,$pintuan_goods);
                return true;
            }
        }

        foreach ($order_list as $key => $order){
            Order::execute($order);
        }


        /*
        $arr1 = [];
        $arr = [];
        $rebate_pintuan_goods = [];
        if($rebate_pintuan['status'] == 1){
            $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$pintuan_order['pintuan_goods_id']])->find();
            $rebate_pintuan_goods = iunserializer($pintuan_goods['plugin'])['rebate_pintuan'];
            if($rebate_pintuan_goods['status'] == 1){
                $pintuan_success_num = $rebate_pintuan_goods['pintuan_success_num'];
                $pintuan_fail_num = $pintuan_order['total'] - $pintuan_success_num;
                
                foreach ($order_list as $k => $v){
                    $arr1[] = $k;
                }
                
                shuffle($arr1);
                
                foreach ($arr1 as $k => $v){
                    if($pintuan_success_num > $k){
                        $arr[$v] = true;
                    }
                    else{
                        $arr[$v] = false;
                    }
                }
            }
        }
        
        foreach ($order_list as $key => $order){
            if($rebate_pintuan['status'] == 1 && $rebate_pintuan_goods['status'] == 1){
                if($arr[$key]){
                    $rebate_pintuan_status = 1;
                    Order::execute($order);
                }
                else{
                    $rebate_pintuan_status = 0;
                    
                    $order_id = $order['id'];
                    $refund = Db::name("bbfx_order_refund")->where(['order_id'=>$order['id'],'uniacid'=>$uniacid])->find();
                    if(empty($refund)){
                        $order_no = date('YmdHis').random(8,true);
                        $data = array(
                            "uniacid"=>$uniacid,
                            "user_id"=>$order['user_id'],
                            "order_no"=>$order_no,
                            "money"=>$order['price'],
                            "order_id"=>$order_id,
                            "content"=>"未拼中退款",
                            "createtime"=>time()
                        );
                        
                        $refund_id = Db::name("bbfx_order_refund")->insertGetId($data);
                
                        if(!empty($refund_id)){
                            Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>0]);
                            Order::refund($order_id,1);
                        }
                    }
                    else{
                        if($refund['status'] != 0){
                            Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>$refund['status']]);
                        }
                        else{
                            Db::name("bbfx_order")->where(['id'=>$order_id])->update(['content'=>"未拼中退款"]);
                            Order::refund($order_id,1);
                        }
                    }
                    
                }
                Db::name("bbfx_order")->where(['id'=>$order['id']])->update(['rebate_pintuan_status'=>$rebate_pintuan_status]);
                if($rebate_pintuan_status === 0){
                    RebatePintuan::setReward($order['id']);
                }
            }
            else{
                Order::execute($order);
            }
        }
        */
        return true;
    }
    
    public function fail($pintuan_order){
        $uniacid = $pintuan_order['uniacid'];
        $res = Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id'],'status'=>0])->update(['status'=>2]);
        if(empty($res)){
            return false;
        }
        Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id']])->update(['jiesuantime'=>time()]);
        Db::name("bbfx_order")->where(['pintuan_order_id'=>$pintuan_order['id']])->update(['pintuan_status'=>2]);
        
        $order_list = Db::name("bbfx_order")->where(['uniacid'=>$uniacid,'is_pay'=>1,'refund_status'=>-1,'pintuan_order_id'=>$pintuan_order['id'],'order_source'=>3])->select();
        foreach ($order_list as $key => $order){
            $order_id = $order['id'];
            $refund = Db::name("bbfx_order_refund")->where(['order_id'=>$order['id'],'uniacid'=>$uniacid])->find();
            if(empty($refund)){
                $order_no = date('YmdHis').random(8,true);
                $data = array(
                    "uniacid"=>$uniacid,
                    "user_id"=>$order['user_id'],
                    "order_no"=>$order_no,
                    "money"=>$order['price'],
                    "order_id"=>$order_id,
                    "content"=>"拼团失败退款",
                    "createtime"=>time()
                );
                
                $refund_id = Db::name("bbfx_order_refund")->insertGetId($data);
        
                if(!empty($refund_id)){
                    Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>0]);
                    Order::refund($order_id,1);
                }
            }
            else{
                if($refund['status'] != 0){
                    Db::name("bbfx_order")->where(['id'=>$order_id])->update(['refund_status'=>$refund['status']]);
                }
                else{
                    Db::name("bbfx_order")->where(['id'=>$order_id])->update(['content'=>"拼团失败退款"]);
                    Order::refund($order_id,1);
                }
            }
            
        }
        
        return true;
    }
    
    public static function refund($order){
        if($order['order_source'] != 3){
            return false;
        }
        
        $pintuan_order = Db::name("bbfx_pintuan_order")->where(['uniacid'=>$order['uniacid'],'id'=>$order['pintuan_order_id'],'status'=>0])->find();
        if(empty($pintuan_order)){
            return false;
        }
        
        if($pintuan_order['tz_user_id'] != $order['user_id']){
            return false;
        }
        
        $pintuan_user = Db::name("bbfx_order")->where(['uniacid'=>$order['uniacid'],'user_id'=>['<>',$pintuan_order['tz_user_id']],'pintuan_order_id'=>$pintuan_order['id'],'status'=>['>=',0]])->count();
        $pintuan_user = intval($pintuan_user);
        
        if($pintuan_user == 0){
            return false;
        }
        
        $res = Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id']])->update(['status'=>-2]);
        if(empty($res)){
            return false;
        }
        
        try {
            
            $order_goods = Db::name("bbfx_order_goods")->where(['uniacid'=>UNIACID,'order_id'=>$order['id']])->select();
        
            foreach ($order_goods as $key => $val){
                $total = max(1,$val['total']);
                Db::name("bbfx_pintuan_goods")->where(['id'=>$val['pintuan_goods_id']])->setInc("stock",$total);
            }
            
            
        } catch (\Exception $e) { }
    }
    
    public static function payResult($pintuan_order_id,$order){
        
        try {
            Db::startTrans();
            
            $res = Db::name("bbfx_order")->where(['id'=>$order['id'],'pintuan_status'=>-1])->update(['pintuan_status'=>0]);
            if(empty($res)){
                throw new \Exception("已更新状态");
            }
            $pintuan_order = Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order_id])->find();
            if(empty($pintuan_order)){
                throw new \Exception("拼团订单不存在");
            }
            
            if($pintuan_order['status'] == -1){
                $pintuan_goods = Db::name("bbfx_pintuan_goods")->where(['id'=>$pintuan_order['pintuan_goods_id']])->find();
                $endtime = 0;
                $starttime = time();
                if($pintuan_goods['is_limitedtime'] == 1){
                    $endtime = $pintuan_goods['endtime'];
                    $endtime = $starttime + $pintuan_goods['yx_day'] * 60 * 60;
                }
                $data = ['status'=>0,'starttime'=>$starttime,'endtime'=>$endtime];
                Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id']])->update($data);
            }
            else{
                // 更新拼团剩余人数
                if($pintuan_order['residue'] > 0){
                    if($pintuan_order['residue'] == 1){
                        Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id']])->update(["residue"=>0]);
                    }
                    else{
                        Db::name("bbfx_pintuan_order")->where(['id'=>$pintuan_order['id']])->setDec("residue",1);
                    }
                }
            }
            
            $order_goods = Db::name("bbfx_order_goods")->where(['uniacid'=>$order['uniacid'],'pintuan_goods_id'=>$pintuan_order['pintuan_goods_id'],'order_id'=>$order['id']])->find();
            if(!empty($order_goods) && $order_goods['stock'] > 0){
                Db::name("bbfx_pintuan_goods")->where(['id'=>$pintuan_goods['id']])->setDec("stock",$order_goods['total']);
            }
            
            Db::commit();
        } 
        catch (\Exception $e) { 
            Db::rollback();
            // print_r($e->getMessage());die;
        }
        
        return true;
    }
    
    public static function calculateMoney($goods,$user,$delivery_method=1,$pintuan_order_id=0,$address_id=0){
        // 总商品金额(折扣后价格)
        $total_price = 0;
        // 快递费
        $express_fee = 0;
        // 折扣金额
        $total_discount_price = 0;
        // 总商品原价金额
        $total_original_price = 0;
        $totalNum = 0;
        
        $price_data = [];
        
        foreach ($goods as $key => $item){
            $total_original_price += max(1,intval($item['total'])) * floatval($item['price']);
        }
        
        if($pintuan_order_id > 0){
            $pintuan_order = Db::name("bbfx_pintuan_order")->where(['uniacid'=>UNIACID,'id'=>$pintuan_order_id,'status'=>0])->find();
            
            if(empty($pintuan_order)){
                $pintuan_order_id = 0;
            }
            
        }
        
        foreach ($goods as $key => $item){
            $total = max(1,intval($item['total']));
            $totalNum += $total;
    	    $goods_price = floatval($item['price']);
    	    
            $real_goods_price = $goods_price;
            $type = 0;
            $price = floatval($item['pintuan_goods']['price']);
            if($item['pintuan_goods']['is_tuanzhangyh'] == 1 && $pintuan_order_id <= 0){
                $price = floatval($item['pintuan_goods']['kaituan_price']);
            }
            
            $discount_price = $goods_price * $total - $price * $total;
            
            if($item['is_spec'] == 1){
                $goods_price = floatval($item['sku']['price']);
                $price = $item['sku']['pintuan_price'];
                if($item['pintuan_goods']['is_tuanzhangyh'] == 1 && $pintuan_order_id <= 0){
                    $price = $item['sku']['kaituan_price'];
                }
                $discount_price = $goods_price * $total - $price * $total;
            }
            
            $original_price = $goods_price * $total;
            
            $total_price += $price * $total;
            $total_discount_price += $discount_price;
            
            $price_data[] = array(
                'float_price'=>0,
                'price'=>round($price,2),
                'total_price'=>round($original_price,2),
                'discount_price'=>max(0,round($discount_price,2)),
                'discount_bargain_price'=>0,
                'discount_coupon_price'=>0,
                'discount_vip_price'=>0,
                'type'=>$type,
            );
        }

        if($delivery_method == 1){
            $express_fee = \app\common\model\bbfxshop\Shippingfee::calculateShippingFee($goods,$address_id,$total_price);
        }
        
        $result = array(
            'float_price'=>0,
            "express_fee"=>round($express_fee,2),
            "total_price"=>round($total_price,2),
            "original_price"=>round($total_original_price,2),
            "discount_price"=>max(0,round($total_discount_price,2)),
            "discount_vip_price"=>0,
            "discount_coupon_price"=>0,
            "discount_bargain_price"=>0,
            "price_data"=>$price_data,
            "totalNum"=>$totalNum,
            "pintuan_order_id"=>$pintuan_order_id,
        );
        // echo "<pre>";
        // print_r($result);die;
        return $result;
    }
    
}

