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

namespace app\common\model\bbfxshop;

use think\Model;
use app\common\model\bbfxshop\User;
use think\Db;

class Coupon extends Model
{
    public static $config = [];
    public static function getSet(){
        $uniacid = UNIACID;

        if(!empty(self::$config)){
            return self::$config;
        }

        $coupon_set = Db::name("bbfx_coupon_set")->where(["uniacid"=>$uniacid])->find();
        if(empty($coupon_set)){
            Db::name("bbfx_coupon_set")->insert(['uniacid'=>$uniacid]);
            $coupon_set = Db::name("bbfx_coupon_set")->where(["uniacid"=>$uniacid])->find();
        }

        if(!empty($coupon_set['share_reward'])){
            $share_reward = iunserializer($coupon_set['share_reward']);
        }
        else{
            $share_reward = [];
        }

        if(!empty($coupon_set['consume_reward'])){
            $consume_reward = iunserializer($coupon_set['consume_reward']);
        }
        if(empty($consume_reward)){
            $consume_reward = [
                'status'=>0,// 状态
                'loop'=>0,// 循环奖励：0=关闭，1=开启
                'buy_goods'=>'',// 购买指定商品
                'consume_time'=>0,// 消费金额统计限制时长（天）不填或填0则不显示
                'consume_jisuan'=>1,// 消费计算：1=多人计算，2=单人计算，多人计算：一级团队的所有成员消费金额之和，单人计算：一级团队的单个成员消费金额之和
                'reward_rule'=>[],// [{consume_money1:'',consume_money1:'',reward_coupon:[]}]
            ];
        }
        if(is_null($consume_reward['consume_jisuan_time'])) $consume_reward['consume_jisuan_time'] = '';
        if(is_null($consume_reward['buy_goods'])) $consume_reward['buy_goods'] = '';
        if(is_null($consume_reward['consume_time'])) $consume_reward['consume_time'] = 0;

        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels();

        foreach($levels as $key => $val){
            $share_reward['level'.$val['id']]['share_num'] = intval($share_reward['level'.$val['id']]['share_num']);
            if(empty($share_reward['level'.$val['id']]['reward_coupon'])){
                $share_reward['level'.$val['id']]['reward_coupon'] = [];
            }
        }

        $coupon_set['levels'] = $levels;

        $coupon_set['share_reward'] = $share_reward;
        $coupon_set['consume_reward'] = $consume_reward;

        self::$config = $coupon_set;
        
        return $coupon_set;
    }

    // 兑换
    public static function exchange($user_id,$id){

        $config = self::getSet();
        if($config['status'] != 1 || $config['score_exchange'] != 1){
            return __json(0,"优惠券未开启积分兑换功能");
        }

        $coupon = Db::name("bbfx_coupon")->where(['uniacid'=>UNIACID,'id'=>$id])->find();
        if(empty($coupon)){
            return __json(0,"优惠券不存在");
        }
        if($coupon['status'] != 1){
            return __json(0,"优惠券未上架");
        }
        if($coupon['obtain_method'] != 2){
            return __json(0,"该优惠券不支持积分兑换");
        }
        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"兑换用户不存在");
        }

        if($user['score'] < $coupon['dh_score']){
            return __json(0,"积分不足");
        }


        try{
            Db::startTrans();
            $log_id = User::setUserMoney($user_id,-$coupon['dh_score'],2,57,"兑换优惠券",$coupon);
            if(empty($log_id)){
                throw new \Exception("积分不足，兑换失败");
            }

            $user_ids = [$user_id];

            self::receive($coupon,$user_ids,7,1,$log_id);

            Db::commit();
        }
        catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }
        
        return __json(1,"兑换成功");
    }

    // 转赠
    public static function transfer($id,$from_user_id,$to_user_id){
        $config = self::getSet();
        if($config['status'] != 1 || $config['score_exchange'] != 1){
            return __json(0,"优惠券未开启积分兑换转赠功能");
        }
        $coupon = Db::name("bbfx_user_coupon")->where(['uniacid'=>UNIACID,'id'=>$id,'user_id'=>$from_user_id])->find();
        if(empty($coupon)){
            return __json(0,"优惠券不存在");
        }
        if($coupon['status'] == 1){
            return __json(0,"优惠券已被使用");
        }
        if($coupon['endtime'] > 0 && $coupon['endtime'] < time()){
            return __json(0,"优惠券已过期");
        }

        $user = User::getInfo($from_user_id); 
        if(empty($user)){
            return __json(0,"转赠源用户不存在");
        }
        $to_user = User::getInfo($to_user_id);
        if(empty($to_user)){
            return __json(0,"转赠目标用户不存在");
        }

        if($config['is_crossline'] != 1){
            if($user['sup_uid'] != $to_user['id'] || $user['id'] != $to_user['sup_uid']){
                return __json(0,"转赠目标用户和自己不是上下级关系");
            }
        }

        Db::name("bbfx_user_coupon")->where(['uniacid'=>UNIACID,'id'=>$id,'user_id'=>$from_user_id])->update(['user_id'=>$to_user_id]);

        return __json(1,"优惠券转赠成功");
    }
    
    public static function setConsumeReward($user_id){
        $config = self::getSet();
        $consume_reward = $config['consume_reward'];
        if(empty($consume_reward)){
            return __json(0,"未配置奖励");
        }

        if($consume_reward['status'] != 1){
            return __json(0,"未开启奖励");
        }

        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户信息错误");
        }

        $sup_user = User::getInfo($user['sup_uid']);
        if(empty($sup_user)){
            return __json(0,"用户信息错误");
        }

        
        if($consume_reward['consume_jisuan'] == 1){

            $level1_user = \app\common\model\bbfxshop\Fenxiao::getLevelUser1($sup_user['id']);

            if(empty($level1_user)){
                return __json(0,"一级团队不存在");
            }

            $uids = array_column($level1_user,"id");
        }
        else{
            $uids = [$user_id];
        }

        if(!empty($consume_reward['consume_jisuan_time'])){
            $stime = strtotime($consume_reward['consume_jisuan_time']);
        }
        else{
            $stime = 0;
        }

        $buy_goods = trim($consume_reward['buy_goods']);
        $consume_time = intval($consume_reward['consume_time']);
        if($consume_time > 0){
            $time1 = time() - $consume_time * 86400;
            if($time1 > $stime){
                $stime = $time1;
            }
        }

        try {
            
            $where = ['o.uniacid'=>UNIACID,'o.is_pay'=>1,'o.refund_status'=>['in',[-1,2]],'o.user_id'=>['in',$uids],'o.createtime'=>['>',$stime]];
            if(!empty($buy_goods)){
                $where['og.goods_id'] = ['in',$buy_goods];
            }
            $consume_money = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where($where)->sum("og.price");

            $order_consume_money = round($consume_money,2);
            
            $reward_rule = $consume_reward['reward_rule'];
            $expand = $consume_reward['consume_jisuan']."_".$consume_reward['loop'];
            if($consume_reward['consume_jisuan'] != 1){
                $expand = $expand."_".$user_id;
            }
            if($consume_time > 0){
                $expand = $expand."_".$consume_time;
            }

            foreach($reward_rule as $k => $val){
                
                $money = round($val['consume_money'.$consume_reward['consume_jisuan']],2);
                $reward_coupon = $val['reward_coupon'];
                if($money > 0 && !empty($reward_coupon)){
                    $expand1 = $expand."_".$money;
                    if($consume_reward['loop'] == 1){
                        
                        $max_consume_money = Db::name("bbfx_coupon_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$sup_user['id'],'expand'=>$expand1])->order("consume_money desc")->value("consume_money");
                        $max_consume_money = round($max_consume_money,2);
                        
                        if($order_consume_money > $max_consume_money){
                            $money_total = $order_consume_money - $max_consume_money;
                            $num = intval($money_total / $money);
                            if($num > 0){
                                for($i = 0;$i < $num;$i++){
                                    $max_consume_money += $money;
                                    $record = Db::name("bbfx_coupon_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$sup_user['id'],'expand'=>$expand1,'consume_money'=>$max_consume_money])->find();
                                    if(empty($record)){
                                        foreach($reward_coupon as $k1 => $v1){
                                            $data = [
                                                'uniacid'=>UNIACID,
                                                'user_id'=>$sup_user['id'],
                                                'coupon_id'=>$v1,
                                                'consume_money'=>$max_consume_money,
                                                'expand'=>$expand1,
                                                'createtime'=>time()
                                            ];

                                            $record_id = Db::name("bbfx_coupon_reward_record")->insertGetId($data);

                                            self::receive(intval($v1),[$sup_user['id']],6,1,$record_id);
                                        }
                                        
                                    }
                                }
                            }
                            
                        }
                
                    }
                    else{

                        if($order_consume_money > $money){
                            $record = Db::name("bbfx_coupon_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$sup_user['id'],'expand'=>$expand1,'consume_money'=>$money])->find();
                    
                            if(empty($record)){
                                foreach($reward_coupon as $k1 => $v1){
                                    $data = [
                                        'uniacid'=>UNIACID,
                                        'user_id'=>$sup_user['id'],
                                        'coupon_id'=>$v1,
                                        'consume_money'=>$money,
                                        'expand'=>$expand1,
                                        'createtime'=>time()
                                    ];

                                    $record_id = Db::name("bbfx_coupon_reward_record")->insertGetId($data);

                                    self::receive(intval($v1),[$sup_user['id']],6,1,$record_id);
                                }
                            }
                        }
                        
                    }
                    
                }
            }
            
        } catch (\Exception $e) {
            return __json(0,$e->getMessage());
        }

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

    // 结算分享奖励
    public static function setShareReward($user_id){
        $config = self::getSet();
        $levels = $config['levels'];
        $share_reward = $config['share_reward'];
        if(empty($levels) || empty($share_reward)){
            return __json(0,"未配置奖励");
        }

        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户信息错误");
        }

        foreach($levels as $key => $val){
            $share_num = intval($share_reward['level'.$val['id']]['share_num']);
            $reward_coupon = $share_reward['level'.$val['id']]['reward_coupon'];
            if($share_num > 0 && !empty($reward_coupon)){
                $level1_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'is_distributor'=>1,'distributor_status'=>1,'level'=>$val['id']])->count();
                $level1_user = intval($level1_user);
                
                if($level1_user >= $share_num){
                    $num = intval($level1_user / $share_num);
                    $total = $num * $share_num;
                    foreach($reward_coupon as $k => $v){
                        $user_coupon = Db::name("bbfx_user_coupon")->where(['uniacid'=>UNIACID,'coupon_id'=>intval($v),'user_id'=>$user['id'],'receive_type'=>5,'item_id'=>$total])->find();
                        if(empty($user_coupon)){
                            self::receive(intval($v),[$user['id']],5,1,$total);
                        }
                    }
                }
            }
        }

        return __json(1,"操作成功");
    }
    
    // 下单赠送
    public static function give($id){
        $order = Db::name("bbfx_order")->where(['id'=>$id,'status'=>['>',0],'refund_status'=>['in',[-1,2]]])->find();
        if(empty($order)){
            return false;
        }
        
        $order_goods = Db::name("bbfx_order_goods")->where(['uniacid'=>UNIACID,'order_id'=>$order['id']])->select();
        if(empty($order_goods)){
            return false;
        }
        
        $user = Db::name("bbfx_user")->where(['id'=>$order['user_id']])->field("id,level")->find();
        if(empty($user)){
            return false;
        }
        
        $user_ids = [$user['id']];
        foreach ($order_goods as $key => $val){
            
            $goods = iunserializer($val['goods_info']);
            $total = max(1,intval($val['total']));
            $plugin = iunserializer($goods['plugin']);
            if(!empty($plugin) && !empty($plugin['coupon']) && !empty($plugin['coupon']['give_coupon_list'])){
                $give_coupon_list = $plugin['coupon']['give_coupon_list'];
                
                
                foreach ($give_coupon_list as $k => $v){
                    $user_coupon = Db::name("bbfx_user_coupon")->where(['uniacid'=>UNIACID,'coupon_id'=>intval($v['id']),'user_id'=>$user['id'],'receive_type'=>3,'item_id'=>$val['id']])->find();
                    if(empty($user_coupon)){
                        $num = $total * max(1,intval($v['number']));
                        self::receive(intval($v['id']),$user_ids,3,$num,$val['id']);
                    }
                    
                }
            }
            
        }
    }
    
    public static function receive($coupon,$user_ids,$receive_type = 0,$total = 1,$item_id = 0){
        // $receive_type 领取类型:0=后台发送,1=免费领取,2=会员卡赠送,3=下单赠送,4=抽奖奖励,5=分享奖励,6=推荐用户消费,7=积分兑换
        if(!is_array($coupon)){
            $coupon = Db::name("bbfx_coupon")->where("id",$coupon)->find();
        }
        
        if(empty($coupon)){
            return false;
        }
        
        $total = max(1,intval($total));
        
        $endtime = 0;
        if($coupon['validitytime'] > 0){
            $endtime = time() + $coupon['validitytime'] * 86400;
        }
        
        $datas = [];
        foreach ($user_ids as $key => $val){
            
            $data = array(
                "uniacid"=>UNIACID,
                "user_id"=>$val,
                "coupon_id"=>$coupon['id'],
                "type"=>$coupon['type'],
                "name"=>$coupon['name'],
                "money"=>$coupon['money'],
                "residue_money"=>$coupon['money'],
                "max_money"=>$coupon['max_money'],
                "mj_money"=>$coupon['mj_money'],
                "goods_ids"=>$coupon['goods_ids'],
                "condition_type"=>$coupon['condition_type'],
                "endtime"=>$endtime,
                "receive_type"=>$receive_type,
                "item_id"=>$item_id,
                "info"=>iserializer($coupon),
                "createtime"=>time()
            );
            
            for($i = 0;$i < $total;$i++){
                
                if($coupon['total'] > -1){
                    $max_total = Db::name("bbfx_coupon")->where("id",$coupon['id'])->value("total");
                    if($max_total <= 0){
                        break;
                    }
                }
                
                $datas[] = $data;
                
                if($coupon['total'] > -1){
                    Db::name("bbfx_coupon")->where("id",$coupon['id'])->setDec("total",1);
                }
                
            }
            
        }

        Db::name("bbfx_user_coupon")->insertAll($datas);

        return true;
    }

    public static function autoUseCoupon($user,$goods_list){
        
        $is_nouse_coupon = false;
        $goods_price = 0;
        $goods_ids = [];
        foreach($goods_list as $key => $goods){
            $plugin = iunserializer($goods['plugin']);
            if(empty($plugin) || empty($plugin['coupon']) || (!empty($plugin) && !empty($plugin['coupon']) && $plugin['coupon']['is_nouse_coupon'] != 1)){
                $is_nouse_coupon = true;
            }
            $goods_price += $goods['price'] * max(1,$goods['total']);
            $goods_ids = $goods['id'];
        }
        if(!$is_nouse_coupon){
            return false;
        }

        $goods_price = round($goods_price,2);

        $coupon_list = self::getUserCouponList($user['id'],$goods_ids,$goods_price);
        
        if(empty($coupon_list)){
            return false;
        }
        // echo "<pre>";
        // print_r($coupon_list);die; 
        $user_coupon = [];
        $min_total_price = 0;
        foreach($coupon_list as $coupon){

            if($coupon['type'] == 1){
                $coupon['money'] = $coupon['residue_money'];
            }
            
            $coupon_money = floatval($coupon['money']);
            $total_original_price = $goods_price;
            $is_coupon = false;
            $is_user_coupon = false;
            $total_price = 0;
            foreach($goods_list as $goods){
                $real_goods_price = $goods['price'];
                $total = max(1,$goods['total']);

                if(empty($is_coupon)){
                    $result = \app\common\model\bbfxshop\Order::calculateCouponGoodsPrice($goods,$coupon,$total_original_price,$coupon_money);
                    if($result['is_user_coupon']){
                        $is_user_coupon = true;
                        $coupon_money = $result['coupon_money'];
                        $price = $result['price'];
                        
                        if($coupon['condition_type'] == 1){
                            if($price < $real_goods_price * $total){
                                $is_coupon = true;
                                $user_coupon_id = $coupon['id'];
                            }
                        }
                    }
                    else{
                        $price = $real_goods_price * $total;
                    }
                }
                else{
                    $price = $real_goods_price * $total;
                }
                $total_price += $price;
            }

            if($is_user_coupon){
                if(empty($user_coupon)){
                    $user_coupon = $coupon;
                    $min_total_price = $total_price;
                }
                else{
                    if($total_price < $min_total_price){
                        $user_coupon = $coupon;
                        $min_total_price = $total_price;
                    }
                    else if($total_price == $min_total_price && $coupon['endtime'] > 0){
                        if($coupon['endtime'] > 0 && $user_coupon['endtime'] == 0){
                            $user_coupon = $coupon;
                        }
                        else if($coupon['endtime'] > 0 && $user_coupon['endtime'] > 0 && $coupon['endtime'] < $user_coupon['endtime'] && $coupon['endtime'] > time()){
                            $user_coupon = $coupon;
                        }
                    }
                }
            }
            
        }
        
        if(empty($user_coupon)){
            return false;
        }
        // print_r($user_coupon['id']);die;
        return $user_coupon['id'];
    }

    public static function getUserCouponList($user_id,$goods_ids=[],$goods_price=0){

        $where = ['uniacid'=>UNIACID,'user_id'=>$user_id,'status'=>0];

        if($goods_price > 0){
            $where['mj_money'] = ['<=',$goods_price];
        }

        $coupon_list = Db::name("bbfx_user_coupon")->where($where)->where(function($query){
            $query->whereOr(function($query){
                $query->where(['endtime'=>0]);
            });
            $query->whereOr(function($query){
                $query->where(['endtime'=>['>',time()]]);
            });
        })->order("money asc")->select();

        if(empty($coupon_list)){
            return [];
        }

        $list = [];
        foreach ($coupon_list as $key => $coupon){
            $flag = false;
                    
            if($coupon['endtime'] == 0 || ($coupon['endtime'] > 0 && $coupon['endtime'] > time())){
                if($coupon['condition_type'] == 1){
                    $coupon_goods_ids = explode(",",$coupon['goods_ids']);
                    foreach ($goods_ids as $k => $v){
                        $goods_id = intval($v);
                        if($goods_id > 0 && in_array($goods_id,$coupon_goods_ids)){
                            $flag = true;
                        }
                    }
                }
                else if($coupon['condition_type'] == 2){
                    if($coupon['mj_money'] <= $goods_price){
                        $flag = true;
                    }
                }
                else{
                    $flag = true;
                }
            }
            
            if($flag){
                $list[] = $coupon;
            }
        }

        return $list;
    }
}