<?php


namespace App\Tasks;


use App\Models\Integral;
use App\Models\IntegralBill;
use App\Models\UserIntegral;
use Common\Model\RedisModel;
use Hhxsv5\LaravelS\Swoole\Task\Task;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class IntegralBillTask extends Task
{
    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        try {
            DB::transaction(function () {
                $userId = $this->data['user_id'];
                $integralId = $this->data['integral_id'];
                //还要去获取此时邀请能获得的金额,因为以后邀请这类操作的金额可能会变动
                $integral = new Integral();
                $res = $integral->getIntegral($integralId);
                if (!$res) {
                    throw new \Exception("获取红包信息失败,红包id是$integralId");
                }
                $amount = $res->amount;
                //数据库里面插入数据
                $data = [
                    'user_id'     => $userId,
                    'integral_id' => $integralId,
                    'amount'      => $amount,
                    'status'      => 1,
                    'add_time'    => $this->data['add_time'],
                ];
                $integralBill = new IntegralBill();
                $result = $integralBill->insert($data);
                if (!$result) {
                    throw new \Exception("插入用户红包账单失败,用户id是$userId,兑换类型id是$integralId");
                }

                //先判断user_integrals表里面存不存在这条记录,如果不存在的话,要初始化一条记录
                $userIntegral = new UserIntegral();
                $data = (array)$userIntegral->getUserIntegral($userId);
                if (!$data) {
                    $data = [
                        'user_id'  => $userId,
                        'status'   => 1,
                        'add_time' => $this->data['add_time'],
                    ];
                    $result = $userIntegral->addUserIntegral($data);
                    if (!$result) {
                        throw new \Exception("初始化用户红包详情失败,用户id是$userId");
                    }
                }
                //将用户的累计可兑换金额写进redis里面的ic_user里面去
                $redis = new RedisModel();
                $user = json_decode($redis->hget('ic_user', $userId), true);
                $data = (array)$userIntegral->getUserIntegral($userId);
                $user['integral'] = number_format($data['integral'] + $amount, 2);
                $result = $redis->hset('ic_user', $userId, json_encode($user));
                //还要写进user_integrals数据库
                if ($result !== false) {
                    $data = [
                        'integral'    => $data['integral'] + $amount,
                        'update_time' => time(),
                    ];

                    $result = $userIntegral->updateUserIntegralByUserId($userId, $data);
                    if (!$result) {
                        throw new \Exception("更新用户剩余积分失败,用户id是$userId,兑换类型id是$integralId");
                    }
                } else {
                    throw new \Exception("更新redis里ic_user的红包余额失败,用户id是$userId,兑换类型id是$integralId");
                }
                //还要对redis的限制数额那块进行更新
                //添加流水成功后,要把对应用户已经对该类型的流水当天操作次数放到redis
                $hashKey = 'ic_welfare_integral_limit_' . $integralId;
                $redis->hincrby($hashKey, $userId, 1);
            });
        } catch (\Exception $e) {
            //抛出致命错误日志
            Log::Error($e);
            ErrorLog(ErrorCode(1, 9), $e);
        }
    }

    public function finish()
    {

    }
}