<?php

namespace App\Services\Pay;

use App\Exceptions\AlertException;
use App\Models\FlowerLogModel;
use App\Models\User\UserModel;
use App\Models\User\UserSysTagModel;
use App\Services\Service;
use Illuminate\Support\Facades\DB;

class FlowerService extends Service
{
    /**
     * 用户小花明细
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function logs(int $uid, array $pages)
    {
        $flm = new FlowerLogModel();
        $total = $flm->where([['uid', $uid], ['id', '>', 1790400]])->count();
        $res = $flm->where([['uid', $uid], ['id', '>', 1790400]])->orderBy(
            'id',
            'desc'
        )->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        return [
            'page' => $pages['page'],
            'total' => $total,
            'limit' => $pages['limit'],
            'list' => $res
        ];
    }

    /**
     * 通过小花提升人气值时长
     * @param  int  $uid
     * @return bool
     * @throws \Exception
     */
    public function payPopularity(int $uid)
    {
        $red_flower = 1;
        $user = UserModel::findOrFail($uid);
        if ($user->red_flower < $red_flower) {
            throw new AlertException("余额不足", 403);
        }

        DB::beginTransaction();
        try {
            $systag = UserSysTagModel::firstOrCreate(['uid' => $user->uid], ['popularity_flower_end_at' => 0]);
            $addtime = $red_flower * 3600 * 2;
            $popularity_flower_end_at = $systag->popularity_flower_end_at;
            if ($systag->popularity_flower_end_at > time()) {
                $systag->popularity_flower_end_at += $addtime;
            } else {
                $systag->popularity_flower_end_at = time() + $addtime;
            }
            $systag->save();

            UserModel::where('uid', $uid)->decrement('red_flower', $red_flower);
            DB::table('kdgx_partner_charge_pay_logs')->insert([
                'uid' => $uid,
                'create_at' => time(),
                'type' => 14,
                'red_flower' => 0 - $red_flower,
                'gold_flower' => 0,
                'remark' => "增加人气值时长"
            ]);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            throw $exception;
        }
    }
}
