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

namespace app\common\model\bbfxshop;

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

class Cashlottery extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        
        return $base['cashlottery'];
    }

    public static function luckdraw($user_id,$num=1){

        try{
            Db::startTrans();
            
            $config = self::getSet();
            if($config['status'] != 1){
                throw new \Exception("未开启抽奖");
            }

            if(empty($config['lottery_method'])){
                throw new \Exception("未开启抽奖方式");
            }
            $user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$user_id])->find();
            if(empty($user)){
                throw new \Exception("用户不存在");
            }

            if(in_array(0,$config['lottery_method']) && in_array(1,$config['lottery_method'])){
                $time = strtotime(date('Y-m-d 00:00:00'));
                $log = Db::name("bbfx_cashlottery_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'lottery_method'=>0,'createtime'=>['>',$time]])->find();
                if(!empty($log) && $user['cashlottery_lottery_num'] <= 0){
                    throw new \Exception("您今日已抽完次数");
                }
            }
            else if(in_array(1,$config['lottery_method'])){
                if($user['cashlottery_lottery_num'] <= 0){
                    throw new \Exception("抽奖次数不足");
                }
            }
            else if(in_array(0,$config['lottery_method'])){
                $time = strtotime(date('Y-m-d 00:00:00'));
                $log = Db::name("bbfx_cashlottery_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'lottery_method'=>0,'createtime'=>['>',$time]])->find();
                if(!empty($log)){
                    throw new \Exception("您今日已抽完次数");
                }
            }

            $reward_list = Db::name("bbfx_cashlottery_reward")->where(['uniacid'=>UNIACID])->order("sort desc,id desc")->limit(0,9)->select();
            if(empty($reward_list)){
                throw new \Exception("未配置抽奖奖励");
            }
            // 抽奖逻辑开始
            if(empty($reward_list)) $reward_list = [];
            $reward = [];
            // 计算总概率
            $total_probability = 0;
            $max_probability = [];
            foreach ($reward_list as $item) {
                $total_probability += $item['probability'];
                if(empty($max_probability) && $item['probability'] > 0){
                    $max_probability = $item;
                }
                else{
                    if($item['probability'] > $max_probability['probability'] && $item['probability'] > 0){
                        $max_probability = $item;
                    }
                }
            }

            if($total_probability <= 0){
                throw new \Exception("未配置抽奖数据");
            }

            
            // 随机抽奖
            $rand = mt_rand(1, $total_probability);
            $current_probability = 0;
            foreach ($reward_list as $item) {
                if($item['probability'] <= 0){
                    continue;
                }
                $current_probability += $item['probability'];
                if ($rand <= $current_probability) {
                    $reward = $item;
                    break;
                }
            }
            
            // 未抽中时取概率最大的奖项
            if (empty($reward)) {
                $reward = $max_probability;
            }

            // 抽奖逻辑结束

            if(empty($log)){
                $lottery_method = 0;
            }
            else{
                $lottery_method = 1;
            }

            $money = 0;
            if($reward['type'] == 1){
                $money = mt_rand($reward['min'] * 100, $reward['max'] * 100) / 100;
                $money = round($money,2);
            }
            else{
                $money = $reward['money'];
            }

            $out_batch_no = date('YmdHis').random(8,true);

            $record = [
                "uniacid"=>UNIACID,
                'out_batch_no'=>$out_batch_no,
                "user_id"=>$user['id'],
                "lottery_method"=>$lottery_method,
                'pid'=>$reward['id'],
                'type'=>$reward['type'],
                'money'=>$money,
                'info'=>iserializer($reward),
                "createtime"=>time(),
            ];
            $id = Db::name("bbfx_cashlottery_reward_record")->insertGetId($record);

            if(empty($id)){
                throw new \Exception("现金抽奖记录添加失败");
            }
            $record['id'] = $id;

            if($lottery_method == 1){
                $res = User::setUserMoney($user['id'],-1,13,59,"现金抽奖扣除次数",$record);
                if(empty($res)){
                    throw new \Exception("现金抽奖失败");
                }
            }

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

        return __json(1,"操作成功",['reward'=>$reward,'money'=>$money,'out_batch_no'=>$out_batch_no]);
    }

    public static function addLotteryNum($order_id){
        try{
            Db::startTrans();
            
            $config = self::getSet();
            if($config['status'] != 1){
                throw new \Exception("未开启抽奖");
            }

            if(empty($config['lottery_method']) || !in_array(1,$config['lottery_method']) || $config['lottery_consume_money'] <= 0){
                throw new \Exception("未开启消费金额抽奖");
            }

            $order = Db::name("bbfx_order")->where(['uniacid'=>UNIACID,'id'=>$order_id,'is_pay'=>1])->field("id,user_id")->find();
            if(empty($order)){
                throw new \Exception("订单不存在");
            }
            
            $where = ['uniacid'=>UNIACID,'user_id'=>$order['user_id'],'is_pay'=>1,'pay_time'=>['>',$config['lottery_stime']]];
            $log = Db::name("bbfx_money_log")->where(['uniacid'=>UNIACID,'user_id'=>$order['user_id'],'type'=>13,'item_type'=>58])->order("id desc")->find();
            if(!empty($log)){
                $where['id'] = ['>',$log['item_id']];
            }

            $order_list = Db::name("bbfx_order")->where($where)->order("id asc")->field("id,user_id,price,paytype,pay_time,createtime,order_type")->select();
            if(!empty($order_list)){
                $lottery_consume_money = $config['lottery_consume_money'];
                $money_total = 0;
                $total = 0;
                $order = [];
                foreach($order_list as $item){
                    $money_total += $item['price'];
                    if($money_total >= $lottery_consume_money){
                        $num = intval($money_total / $lottery_consume_money);
                        $money_total = $money_total - $num * $lottery_consume_money;
                        $total += $num;
                        $order = $item;
                    }
                }
                if($total > 0){
                    $res = User::setUserMoney($order['user_id'],$total,13,58,"消费增加抽奖次数",$order);
                    if(empty($res)){
                        throw new \Exception("消费增加抽奖次数失败");
                    }
                }
            }

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

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

    public static function tixian($user_id,$out_batch_no,$tixian_method=0,$openid='',$platform=''){
        global $_W;
        try{
            Db::startTrans();

            $record = Db::name("bbfx_cashlottery_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'out_batch_no'=>$out_batch_no])->find();
            if(empty($record)){
                throw new \Exception("抽奖记录不存在");
            }

            $user = User::getInfo($user_id);
            if(empty($user)){
                throw new \Exception("用户不存在");
            }

            if($tixian_method == 1){
                if(empty($openid)){
                    throw new \Exception("用户微信openid错误，无法提现到微信零钱");
                }
                if($record['money'] < 0.1){
                    throw new \Exception("提现金额小于0.1元，请选择提现到余额");
                }
                if($_W['base']['is_merch_transfer_new'] == 1){
                    $res = \app\common\model\bbfxshop\Wxpay::newTransfer($openid,$record['money'],$out_batch_no,'',"现金抽奖提现",$platform);
                    if($res['code'] != 1){
                        throw new \Exception($res['message']);
                    }
                    $data = [
                        'batch_id'=>$res['data']['transfer_bill_no']
                    ];
                    if(!empty($res['data']['package_info'])){
                        $data['package_info'] = $res['data']['package_info'];
                    }
                    $data['is_confirm'] = 0;
                    $set = \app\common\model\bbfxshop\Wxpay::getSet($platform);
                    $tixian_data = [
                        'is_confirm'=>0,
                        "mchId"=>$set['mchid'],
                        "appId"=>$set['appid'],
                        "package"=>$data['package_info'],
                        'out_batch_no'=>$out_batch_no,
                    ];
                }
                else{
                    $res = \app\common\model\bbfxshop\Wxpay::transfer($openid,$record['money'],$out_batch_no,'',"现金抽奖提现",$platform);
                    if(empty($res) || $res['code'] != 1){
                        throw new \Exception($res['message']);
                    }
                    $data = [
                        'batch_id'=>$res['data']['batch_id']
                    ];

                    $tixian_data = ['is_confirm'=>1];
                }
                
            }
            else{
                $res = User::setUserMoney($user['id'],$record['money'],1,60,"现金抽奖提现",$record);
                if(empty($res)){
                    throw new \Exception("现金抽奖提现失败");
                }
                $tixian_data = [];
                $data = [];
            }
            $data['tixian_method'] = $tixian_method;
            $data['status'] = 1;
            $data['paytime'] = time();
            Db::name("bbfx_cashlottery_reward_record")->where(['id'=>$record['id']])->update($data);
            
            $result = __json(1,"操作成功",$tixian_data);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

        return $result;
    }

    public static function confirm($user_id,$out_batch_no,$platform=''){
        try{
            Db::startTrans();

            $record = Db::name("bbfx_cashlottery_reward_record")->where(['uniacid'=>UNIACID,'user_id'=>$user_id,'out_batch_no'=>$out_batch_no])->find();
            if(empty($record)){
                throw new \Exception("抽奖记录不存在");
            }

            $user = User::getInfo($user_id);
            if(empty($user)){
                throw new \Exception("用户不存在");
            }

            if($record['is_confirm'] == -1){
                throw new \Exception("不是新版商家转账到零钱");
            }
            if($record['is_confirm'] == 1){
                throw new \Exception("已确认收款");
            }
            
            $result = \app\common\model\bbfxshop\Wxpay::queryNewTransfer($record['out_batch_no'],$platform);
            if($result['code'] != 1){
                if($result['message'] == '记录不存在'){
                    $result['message'] = '记录已过期或不存在';
                }
                throw new \Exception($result['message']);
            }
            
            $state = $result['data']['state'];
            if($state != 'SUCCESS'){
                throw new \Exception("您还未确认收款成功");
            }

            Db::name("bbfx_cashlottery_reward_record")->where(['id'=>$record['id']])->update(['is_confirm'=>1,'confirmtime'=>time()]);
            
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return __json(0,$e->getMessage());
        }

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