<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\domain\user;

use app\model\User;
use Core\service\BaseCoreService;
use think\facade\Db;

/**
 * 用户积分服务
 * @package app\service\domain\user
 * Class CoreUserPointsService
 */
class CoreUserPointsService extends BaseCoreService
{
    /**
     * 调整用户积分（增加/扣除）
     * @param int $userId 用户ID
     * @param string $action 操作类型（recharge/deduct）
     * @param float $amount 积分数量
     * @param string $bizType 业务类型
     * @param string $remark 备注
     * @param string $operator 操作人
     * @return array
     */
    public function adjust(int $userId, string $action, float $amount, string $bizType = 'manual', string $remark = '', string $operator = ''): array
    {
        return Db::transaction(function () use ($userId, $action, $amount, $bizType, $remark, $operator) {
            $user = User::lock(true)->find($userId);
            if (!$user) {
                return ['code' => 1, 'msg' => ''];
            }

            $current = (float)$user->points;

            if ($action === 'deduct') {
                $amount = abs($amount);
                if ($amount > $current) {
                    return ['code' => 1, 'msg' => '' . $current];
                }
                $newPoints = $current - $amount;
                $type = 'deduct';
                $scene = 'admin_deduct';
            } else {
                $amount = abs($amount);
                $newPoints = $current + $amount;
                $type = 'recharge';
                $scene = 'admin_recharge';
            }

            $user->points = $newPoints;
            $user->save();

            Db::name('sys_user_points_logs')->insert([
                'user_id'    => $userId,
                'amount'     => $amount,
                'balance'    => $newPoints,
                'type'       => $type,
                'scene'      => $scene,
                'biz_type'   => $bizType,
                'biz_id'     => '',
                'remark'     => $remark,
                'operator'   => $operator,
                'create_time' => date('Y-m-d H:i:s'),
            ]);

            return ['code' => 0, 'msg' => '', 'points' => $newPoints];
        });
    }
}
