<?php

namespace app\queue\single;

use Webman\RedisQueue\Consumer;
use app\model\WorkRecord;
use app\model\User as UserModel;
use think\facade\Db;
use app\model\BalanceLog;

class Questionnaire implements Consumer
{
    // 要消费的队列名
    public $queue = 'Questionnaire';
    public $connection = 'default';

    // 消费Notify
    public function consume($data)
    {
        try { 
            $this->log("云主机:".json_encode($data));
            if($data['action'] == 'assign'){
                $time = time();
                if( !isset($data['user_id']) || !$data['user_id']){
                    $this->log('user_id==null' );
                    return ;
                }
                if( !isset($data['order_id']) || !$data['order_id']){
                    $this->log('order_id==null' );
                    return ;
                }
                /**
                 * @var \app\model\ProductOrder $order
                 */
                $order = \app\model\ProductOrder::with(['product'])
                    ->where('id',$data['order_id'])
                    ->where('user_id',$data['user_id'])
                    ->whereColumn('assigned','<','total')
                    ->lock(true)
                    ->find();
                if(!$order){
                    $this->log('订单不存在:'.$data['order_id'] );
                    return ;
                }
                /**
                 * @var \app\model\Product $product
                 */
                $product = $order->product;
                // if($order->assigned >= $order->total){
                //     $this->log('订单已分配完:'.$order->id );
                //     return ;
                // }
                $amount = $product->assign_count;
                if($order->accelerate && $order->accelerate_times > $order->accelerate_used){
                    $amount = $product->accelerate_assign_count;
                }
                $amount *= $order->quantity;
                //每次分配不超过订单剩余量
                $_amount = min($amount,($order->total - $order->assigned));
                if($_amount <= 0 ){
                    return;
                }
                $user = UserModel::find($data['user_id']);
                if($_amount > $user->currency7 ){
                    return;
                }
                //分配问卷
                Db::startTrans();
                try {
                    $currency6_logData = [
                        'user_id'               => $data['user_id'].'',
                        'currency'              => 'currency6',
                        'amount'                => ''.$_amount,
                        'before'                => $user->currency6.'',
                        'after'                 => ($user->currency6+$_amount).'',
                        'type'                  => \app\enum\BalanceType::ASSIGN_QUOTA->value,
                        'created_at'            => $time.'',
                        'memo'                  => $order->id.''
                    ];
                    $currency7_logData = [
                        'user_id'               => $data['user_id'].'',
                        'currency'              => 'currency7',
                        'amount'                => '-'.$_amount,
                        'before'                => $user->currency7.'',
                        'after'                 => ($user->currency7-$_amount).'',
                        'type'                  => \app\enum\BalanceType::ASSIGN_QUOTA->value,
                        'created_at'            => $time.'',
                        'memo'                  => $order->id.''
                    ];
                    $currency8_logData = [
                        'user_id'               => $data['user_id'].'',
                        'currency'              => 'currency8',
                        'amount'                => ''.$_amount,
                        'before'                => $user->currency8.'',
                        'after'                 => ($user->currency8+$_amount).'',
                        'type'                  => \app\enum\BalanceType::ASSIGN_QUOTA->value,
                        'created_at'            => $time.'',
                        'memo'                  => $order->id.''
                    ];
                    BalanceLog::create($currency6_logData);
                    BalanceLog::create($currency7_logData);
                    BalanceLog::create($currency8_logData);
                    $user->currency6+=$_amount;    //可领取
                    $user->currency7-=$_amount;    //待分配
                    $user->currency8+=$_amount;    //已分配
                    $user->save();
                    $order->assigned += $_amount;
                    $order->accelerate_used +=1;
                    $order->save();
                    Db::commit();
                    if($order->total > $order->assigned){
                        //addJob($data,'Questionnaire',86400);
                        $nextday = strtotime('+1 days');
                        $nexttime = strtotime(datetime($nextday,'Y-m-d'))+$order->id-2000;
                        $nextdelay = $nexttime - time();
                        addJob($data,'Questionnaire',$nextdelay);
                    }
                }catch(\Exception $e){
                    Db::rollback();
                    $this->log($e->getMessage());
                    throw $e;
                }
            }elseif($data['action'] == 'workcomplete'){
                if( !isset($data['server_id']) || !$data['server_id']){
                    $this->log('server_id==null' );
                    return ;
                }
                $server = WorkRecord::find($data['server_id']);
                if($server->status != \app\enum\ServerStatus::WORKING->value){
                    return ;
                }
                $auditing_time = rand(3600,10800);  //1-3小时随机审核
                $server->status = \app\enum\ServerStatus::AUDITING->value;
                $server->save();
                addJob(['server_id'=>$server->id,'action'=>'settlement'],'Questionnaire',$auditing_time);
            }elseif($data['action'] == 'settlement'){
                if( !isset($data['server_id']) || !$data['server_id']){
                    $this->log('server_id==null' );
                    return ;
                }
                $server = WorkRecord::find($data['server_id']);
                if($server->status != \app\enum\ServerStatus::AUDITING->value){
                    return ;
                }
                Db::startTrans();
                try {
                    //几率失败,最低5%-最高10%的几率失败
                    $success = true;
                    $failRate = rand(5, 10); // 随机选择失败率
                    $rand = rand(0, 99);     // 0-99 共100个数
                    if ($rand < $failRate) {
                        $success = false;
                    }
                    $success = true;
                    if(!$success){
                        //失败的处理
                        $server->status = \app\enum\ServerStatus::FAILED->value;
                        $server->save();
                        $user = UserModel::find($server->user_id);
                        $time = time();
                        $currency6_logData = [
                            'user_id'               => $server->user_id.'',
                            'currency'              => 'currency6',
                            'amount'                => '1',
                            'before'                => $user->currency6.'',
                            'after'                 => ($user->currency6+1).'',
                            'type'                  => \app\enum\BalanceType::DIFFERENTIAL_COMMISSION,
                            'created_at'            => $time.'',
                            'memo'                  => ''
                        ];
                        $currency9_logData = [
                            'user_id'               => $server->user_id.'',
                            'currency'              => 'currency9',
                            'amount'                => '1',
                            'before'                => $user->currency9.'',
                            'after'                 => ($user->currency9+1).'',
                            'type'                  => \app\enum\BalanceType::DIFFERENTIAL_COMMISSION,
                            'created_at'            => $time.'',
                            'memo'                  => ''
                        ];
                        BalanceLog::create($currency6_logData);
                        BalanceLog::create($currency9_logData);
                        $user->currency6+=1;    //可领取
                        $user->currency9+=1;    //未通过
                        $user->save();
                        Db::commit();
                    }else{
                        //给用户付钱
                        UserModel::score($server->user_id,$server->income,\app\enum\BalanceType::PRODUCT_INCOME,$server->id);
                        $server->status = \app\enum\ServerStatus::COMPLETE->value;
                        $server->save();
                        cache_add('user_today_income_'.date('Ymd').'_'.$server->user_id,$server->income);
                        cache_add('user_month_income_'.date('Ym').'_'.$server->user_id,$server->income);
                        cache_add('user_income_total_'.$server->user_id,$server->income);
                        // $parent_info = parent_info($server->user_id);
                        // $parent_id = $parent_info['id'];
                        // // 产值奖励（直推）
                        // if(UserModel::where('id',$parent_id)->value('group') == 1){
                        //     //只有渠道用户才能活得
                        //     $reward = bcmul($data['amount'] ,0.05,4);
                        //     UserModel::score($parent_id ,$reward,\app\enum\BalanceType::OUTPUT_REWARD,$data['id']);
                        // }
                        // //产值奖励
                        // $distributed_users = jicha($server->user_id,$server->income,[0,0.01,0.02,0.03,0.05,0.05]);
                        // foreach($distributed_users as $k=>$v){
                        //     UserModel::money($v['user_id'],$v['amount'],\app\enum\BalanceType::OUTPUT_REWARD,$server->id);
                        //     cache_add('user_income_total_'.$v['user_id'],$v['amount']);
                        //     cache_add('user_output_reward_'.$v['user_id'],$v['amount']);
                        // }
                        Db::commit();
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->log($e->getMessage());
                    throw $e;
                }
            }else{
                $this->log('未知状态');
            }
        }
        catch(\Exception $e)
        {
            $this->log($e->getMessage());
        }
    }
    function log($msg = ''){
        \support\Log::channel('server')->alert($msg);
    }
    // 消费失败回调
    /* 
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
        $this->log('consume failure:'.$e->getMessage());
    }
}