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

namespace app\common\model\bbfxshop;

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

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

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

        $luckywheel = Db::name("bbfx_luckywheel")->where(["uniacid"=>$uniacid])->find();
        if(empty($luckywheel)){
            Db::name("bbfx_luckywheel")->insert(['uniacid'=>$uniacid]);
            $luckywheel = Db::name("bbfx_luckywheel")->where(["uniacid"=>$uniacid])->find();
        }
        $lottery_obtain = explode(',',$luckywheel['lottery_obtain']);
        foreach($lottery_obtain as &$val){
            $val = intval($val);
        }
        unset($val);
        $luckywheel['lottery_obtain'] = $lottery_obtain;

        $lottery_method = explode(',',$luckywheel['lottery_method']);
        foreach($lottery_method as &$val){
            $val = intval($val);
        }
        unset($val);
        $luckywheel['lottery_method'] = $lottery_method;

        if(!empty($luckywheel['lottery_obtain_rule'])){
            $lottery_obtain_rule = iunserializer($luckywheel['lottery_obtain_rule']);
        }
        if(empty($lottery_obtain_rule)){
            $lottery_obtain_rule = ['consume'=>[]];
        }
        $luckywheel['lottery_obtain_rule'] = $lottery_obtain_rule;

        $luckywheel['bg'] = cdnurl($luckywheel['bg']);
        $luckywheel['yp_bg'] = cdnurl($luckywheel['yp_bg']);
        $luckywheel['pointer_image'] = cdnurl($luckywheel['pointer_image']);
        $luckywheel['title_image'] = cdnurl($luckywheel['title_image']); 
        $luckywheel['lottery_btn_image'] = cdnurl($luckywheel['lottery_btn_image']);
        $luckywheel['record_btn_image'] = cdnurl($luckywheel['record_btn_image']);
        $luckywheel['rule_btn_image'] = cdnurl($luckywheel['rule_btn_image']);
        $luckywheel['popup_image'] = cdnurl($luckywheel['popup_image']);
        if(empty($luckywheel['bg'])) $luckywheel['bg'] = cdnurl('/assets/images/luckywheel/lottery_bg.png');
        if(empty($luckywheel['yp_bg'])) $luckywheel['yp_bg'] = cdnurl('/assets/images/luckywheel/lottery_circle.png');
        if(empty($luckywheel['pointer_image'])) $luckywheel['pointer_image'] = cdnurl('/assets/images/luckywheel/zhizheng.png');
        if(empty($luckywheel['title_image'])) $luckywheel['title_image'] = cdnurl('/assets/images/luckywheel/lottery_title.png');
        if(empty($luckywheel['lottery_btn_image'])) $luckywheel['lottery_btn_image'] = cdnurl('/assets/images/luckywheel/lottery_mainbtn.png');
        if(empty($luckywheel['record_btn_image'])) $luckywheel['record_btn_image'] = cdnurl('/assets/images/luckywheel/lottery_mainbtn.png');
        if(empty($luckywheel['rule_btn_image'])) $luckywheel['rule_btn_image'] = cdnurl('/assets/images/luckywheel/lottery_mainbtn.png');
        if(empty($luckywheel['popup_image'])) $luckywheel['popup_image'] = cdnurl('/assets/images/luckywheel/lottery_pop.png');

        self::$config = $luckywheel;
        
        return $luckywheel;
    }
 
    // 抽奖
    public static function luckdraw($user_id,$num=1,$lottery_method=1){
        
        $config = self::getSet();
        if($config['status'] != 1){
            return __json(0,"未开启抽奖");
        }
        
        $user = User::getInfo($user_id);
        if(empty($user)){
            return __json(0,"用户信息错误");
        }
        $lottery_score = max(0,intval($config['lottery_score']));
        $num = max(1,intval($num));
        if($lottery_method == 2){
            if(!in_array(2,$config['lottery_method'])){
                return __json(0,"未开启积分抽奖");
            }
            if($lottery_score <= 0){
                return __json(0,"未配置抽奖积分");
            }
            if($user['score'] <= 0 || $user['score'] < $lottery_score * $num){
                return __json(0,"抽奖积分不足");
            }
        }
        else{
            $lottery_method = 1;
            if(!in_array(1,$config['lottery_method'])){
                return __json(0,"未开启次数抽奖");
            }
            if($user['lottery_num'] <= 0 || $user['lottery_num'] < $num){
                return __json(0,"抽奖次数不足");
            }
        }
        
        $list = Db::name("bbfx_luckywheel_prize")->where(['uniacid'=>UNIACID,'status'=>1])->select();
        if(empty($list)){
            return __json(0,"未配置抽奖奖品");
        }
        
        $user_zhidings = Db::name("bbfx_luckywheel_zhiding")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'status'=>0])->order("id asc")->limit(0,$num)->select();
        $prizes = [];
        if(!empty($user_zhidings)){
            foreach($user_zhidings as $k => $v){
                $prizes[] = Db::name("bbfx_luckywheel_prize")->where(['uniacid'=>UNIACID,'status'=>1,'id'=>$v['prize_id']])->find();
            }
            
        }
        
        if(count($prizes) < $num){
            $prize_list = [];
            foreach ($list as $key => $val){
                $probability = round($val['probability'],2) * 100;
                for($i = 0;$i < $probability;$i++){
                    $prize_list[] = $key;
                }
            }
            
            shuffle($prize_list);
            
            $min = 0; 
            $max = count($prize_list); // 范围最大值
            $len = $num - count($prizes);
            for($i = 0;$i < $len;$i++){
                $randomNumber = mt_rand($min, $max);
                $prizeIndex = $prize_list[$randomNumber];
                $prizes[] = $list[$prizeIndex];
            }
            
        }
        
        if(empty($prizes)){
            return __json(0,"抽奖奖品错误");
        }
        
        try {
            Db::startTrans();
            
            $record = [];
            foreach($prizes as $k => $prize){
                $data = [
                    'uniacid'=>UNIACID,
                    'user_id'=>$user['id'],
                    'lottery_method'=>$lottery_method,
                    'type'=>$prize['type'],
                    'prize_id'=>$prize['id'],
                    'prize'=>iserializer($prize),
                    'code'=>random(12),
                    'createtime'=>time()
                ];
                
                if($data['type'] == 0 || $data['type'] == 1 || $data['type'] == 2 || $data['type'] == 3){
                    $data['status'] = 1;
                    $data['dhtime'] = time();
                }
                
                $id = Db::name("bbfx_luckywheel_lottery_record")->insert($data);
                $data['id'] = $id;
                if($lottery_method == 1){
                    $res = User::setUserMoney($data['user_id'],-1,11,46,"转盘抽奖",$data);
                    if(empty($res)){
                        throw new \Exception("抽奖次数不足");
                    }
                }
                else{
                    $res = User::setUserMoney($data['user_id'],-$lottery_score,2,46,"转盘抽奖",$data);
                    if(empty($res)){
                        throw new \Exception("抽奖积分不足");
                    }
                }
                

                if($data['type'] == 1 || $data['type'] == 2){
                    $reward = round($prize['reward'],2);
                    if($reward > 0){
                        User::setUserMoney($data['user_id'],$reward,$data['type'],46,"抽奖奖励",$data);
                    }
                }
                else if($data['type'] == 3){
                    $reward = iunserializer($prize['reward']);
                    if(!empty($reward) && is_array($reward)){
                        foreach($reward as $k => $v){
                            Coupon::receive(intval($v),[$user['id']],4,1,$id);
                        }
                    }
                }

                $record[] = $data;
            }
            
            
            

           
            
            if(!empty($user_zhidings)){
                foreach($user_zhidings as $k => $v){
                    Db::name("bbfx_luckywheel_zhiding")->where(['id'=>$v['id']])->update(['status'=>1,'cjtime'=>time()]);
                }
            }
            
            $result = __json(1,"抽奖成功",['prize_id'=>$prize['id'],'prizes'=>$prizes]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result = __json(0,$e->getMessage());
        }
          
        return $result;
    }

    // 获取抽奖次数
    public static function setLotteryNum($order_id){
        $config = self::getSet();
        if($config['status'] != 1){
            return __json(0,"未开启抽奖");
        }

        $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'is_pay'=>1,'id'=>$order_id])->find();
        if(empty($order)){
            return __json(0,"订单不存在");
        }

        $user_id = $order['user_id'];

        $lottery_obtain = $config['lottery_obtain'];
        
        // 购买商品
        if(in_array(1,$lottery_obtain)){
            $order_goods = Db::name("bbfx_order_goods")->where(['uniacid'=>UNIACID,'order_id'=>$order_id])->select();
            foreach($order_goods as $key => $val){
                $goods_info = iunserializer($val['goods_info']);
                $plugin = iunserializer($goods_info['plugin']);
                $lottery_num = max(0,intval($plugin['luckywheel']['lottery_num'])) * max(1,$val['total']);
                if($plugin['luckywheel']['status'] == 1 && $lottery_num > 0){
                    $log = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>11,'item_type'=>1,'item_id'=>$val['id']])->find();
                    if(empty($log)){
                        User::setUserMoney($user_id,$lottery_num,11,1,"购买商品",$val);
                    }
                    
                }
            }
        }
        
        // 消费金额
        if(in_array(2,$lottery_obtain)){
            $order_price = Db::name("bbfx_order_goods")->alias("og")->join("bbfx_order o","og.order_id=o.id","LEFT")->where(['o.uniacid'=>UNIACID,'o.id'=>$order_id,'o.user_id'=>$user_id,'o.status'=>['in',[1,2,3]],'o.refund_status'=>['in',[-1,2]]])->sum("og.price");
            $order_price = round($order_price,2);
            $lottery_obtain_rule = $config['lottery_obtain_rule']['consume'];
            
            if(!empty($lottery_obtain_rule)){
                $lottery_num = 0;
                foreach($lottery_obtain_rule as $key => $val){
                    $money = round($val['money'],2);
                    $num = intval($val['num']);
                    if($num > 0 && $money > 0 && $order_price >= $money){
                        $lottery_num = $num;
                    }
                }

                if($lottery_num > 0){
                    $log = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'type'=>11,'item_type'=>47,'item_id'=>$order['id']])->find();
                    if(empty($log)){
                        User::setUserMoney($user_id,$lottery_num,11,47,"消费金额",$order);
                    }
                }
                
            }
            
        }

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