<?php

/**
 * 礼物信息
*/

class giftModule extends commonModule
{
    public function __construct()
    {
        parent::__construct("sl_gift");
    }

    //赠送礼物，参数验证
    public function verUserSentGift($user_info,$request){

        //主播编号
        if (empty($request["user_number"])){
            returnFail([],getcodestr(5001),5001);
        }
        $userModule = new userModule();
        $anchor = $userModule->getUserInfoByNumber($request["user_number"]);
        if (empty($anchor)){
            returnFail([],getcodestr(5001),5001);
        }

        //礼物
        if (empty($request["gift"])){
            returnFail([],getcodestr(5002),5002);
        }
        $giftModule = new giftModule();
        $gift = $giftModule->findOne($request["gift"]);
        if (empty($gift)){
            returnFail([],getcodestr(5002),5002);
        }

        //礼物数量
        if (empty($request["number"])){
            returnFail([],getcodestr(5003),5003);
        }

        //礼物所需钻石
        $diamond_need = $gift["diamond"] * $request["number"];
        //判断用户钻石是否足够支付
        if ($user_info["diamond"] < $diamond_need){
            returnFail([],getcodestr(5004),5004);
        }
        //扣除用户钻石
        $userModule->start_T();
        $user_diamond = (double)$user_info["diamond"] - $diamond_need;
        $res_user = $userModule->where(["id"=>$user_info["id"]])->update(["diamond"=>$user_diamond]);

        //生成收礼物日志
        $gift_log = [
            "user_number" => $user_info["number"],
            "usered_number" => $request["user_number"],
            "gift_id" => $request["gift"],
            "num" => $request["number"],
            "price" => $diamond_need,
            "create_time" => date("Y-m-d H:i:s"),
        ];
        $res_gift = (new userGiftLogModule())->insert($gift_log);

        //用户消费日志
        $buy_log = [
            "gift" => $request["gift"],
            "number" => $request["number"],
            "total" => $diamond_need,
            "dtime" => date("Y-m-d H:i:s"),
        ];

        $res_buy_log = (new userBuyLogModule())->insert($buy_log);
        //判断结果
        if ($res_user && $res_gift && $res_buy_log){
            $userModule->comit_T();
            return $gift;
        }else{
            $userModule->roll_T();
            returnFail([],getcodestr(10001),10001);
        }


    }

}