<?php

namespace addons\faqueue\library\jobs;

use addons\faqueue\library\QueueApi;
use addons\faqueue\model\FaqueueLog;
use app\admin\model\AdminMessage;
use app\admin\model\UserMessage;
use app\common\library\weChat\weChatMp;
use think\Db;
use think\Log;
use think\queue\job;

class CheckRelegation
{
    private $redis;

    function __construct()
    {
        $redis = new \Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"], 86400 * 31);
        $this->redis = $redis;
    }

    public function fire(Job $job, $data)
    {
        $user_id = $data['user_id'];
        $user = Db::name('user')->where('id',$user_id)->field('id,noble,noble_duetime')->find();

        //贵族等级高于30天前定时等级。视为无效任务
        if (!$user || $user['noble']>$data['noble'] || $user['noble_duetime']>$data['end_time']){
            $job->delete();
            echo 11111;
            return;
        }

        //玩家当前贵族等级
        $userNoble = $user['noble'];
        $nobleDuetime = $user['noble_duetime'];
        $userRenew2 = $this->redis->get('user_renew2_'.$user_id);
        $getNobleLevelData = $this->getNobleLevelData($userNoble);
        if (empty($getNobleLevelData)) {
            $job->delete();
            return;
        }

        $renew2 = $getNobleLevelData['renew2'];
//        $this->redis->set('user_renew_'.$user_id,0);
        $this->redis->set('user_renew2_'.$user_id,0);
        $duetime = strtotime("+1 month",$nobleDuetime);

        //如果不是最大等级保级说明是重新回到该爵位，需扣除之前回到回到该爵位的消保
        //增加月保级消费（处理保级），和月消费分开（处理升级）

        if ($userRenew2!=0 && $userRenew2>=$renew2){
            //保级成功,延长过期时间
            Db::name('user')->where('id',$user_id)->setField('noble_duetime',$duetime);

        }else{
            //降级,>骑士
            $userNoble = $userNoble - 1;
            if ($userNoble<1) {
                $job->delete();
                return;
            }
            Db::name('user')->where('id',$user_id)->update(['noble'=>$userNoble,'noble_duetime'=>$duetime]);
        }

        $job->delete();
        (new FaqueueLog())->log($job->getQueue(), $job->getName(), $data);

        //重新定时任务
        if ($userNoble>1) QueueApi::timeRelegation($user_id,$duetime,$userNoble);
    }

    public function failed($data)
    {
        Log::write("任务失败：" . print_r(['data' => $data,], true), 'error');
    }

    /**
     * 获取指定等级的贵族数据
     * @param $level_id
     */
    private function getNobleLevelData($level_id)
    {
        $getNobleLevelList = $this->redis->get('noble_level_list');
        if (empty($getNobleLevelList)) return [];
        $getNobleLevelList = unserialize($getNobleLevelList);
        foreach ($getNobleLevelList as $v){
            if ($level_id == $v['id']) return $v;
        }
        return [];
    }
}