<?php

namespace app\common\service\promotion;

use think\facade\Db;
use app\common\model\promotion\Award as AwardModel;
use app\common\model\Users as UsersModel;
use app\common\model\users\UsersLog as UsersLogModel;
use app\common\model\users\UsersPointLog as UsersPointLogModel;

/**
 * @package app\common\service\promotion
 * @class Award
 * @author xzncit 2024/3/22
 */
class Award {

    /**
     * 发放奖励
     * @param $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function reward($user_id){
        $row = AwardModel::where("status",1)->find();
        if(empty($row)){
            return false;
        }

        $data = [];
        if($row["price"] > 0){
            $data["money"] = Db::raw("money+" . $row["price"]);
        }

        if($row["point"] > 0){
            $data["score"] = Db::raw("score+" . $row["point"]);
        }

        if(empty($data)){
            return false;
        }

        try{
            $user = UsersModel::where("id",$user_id)->find();
            if(empty($user)){
                return false;
            }

            UsersModel::startTrans();
            UsersModel::where("id",$user_id)->save($data);

            if($row["price"] > 0){
                UsersLogModel::create([
                    "user_id"       => $user["id"],
                    "type"          => 1,
                    "operation"     => 1,
                    "value"         => $row["price"],
                    "description"   => "新人奖励",
                    "create_time"   => time()
                ]);
            }

            if($row["point"] > 0){
                UsersPointLogModel::create([
                    "user_id"       => $user["id"],
                    "type"          => 1,
                    "value"         => $row["point"],
                    "content"       => "新人奖励",
                    "create_time"   => time()
                ]);
            }

            UsersModel::commit();
            return true;
        }catch (\Exception $ex){
            UsersModel::rollback();
            return false;
        }
    }

}