<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/4/2
 * Time: 14:55
 */

namespace App\Modules\User\Services;

use App\Modules\Book\Models\BookGiftsSend;
use App\Modules\User\Models\UserGift;
use DB;

class UserGiftService
{

    /**
     * 给用户添加礼物  $gift=[['gift_id'=>1,'num'=>1]]
     * @param $uid
     * @param $gift
     */
    public static function addGift($uid,$gifts){
        if(empty($gifts)){
            return false;
        }
        $add_data = [];
        foreach ($gifts as $gift){
            if(!isset($gift['num']) || $gift['num']<=0) continue;
            $result = UserGift::where('uid',$uid)->where('gift_id',$gift['gift_id'])->increment('num',$gift['num']);
            if(!$result){
                $add_data[] = ['gift_id'=>$gift['gift_id'],
                    'uid'=>$uid,'num'=>$gift['num'],
                    'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')];
            }
        }
        if($add_data){
            UserGift::insert($add_data);
        }
    }


    public static function getByUidAndGiftId($uid,$gift_id){
        return UserGift::where('uid',$uid)->where('gift_id',$gift_id)->select('id','num','gift_id','uid')->first();
    }



    public static function getGifts($uid){
        $sql = 'SELECT a.id,a.name ,a.name_desc,a.icon,a.cost,IFNULL(b.num,0) as num,c.balance from book_gifts a 
LEFT JOIN user_gifts b on a.id = b.gift_id and b.uid = %s
LEFT JOIN users c on  c.id = %s
where a.status = 1 ORDER  by cost desc';
        return DB::select(sprintf($sql,$uid,$uid));
    }

    public static function sendGiftToBook($uid,$gift_id,$bid,$gift){
        $user_gift = self::getByUidAndGiftId($uid,$gift_id);
        $send_info =[
            'uid'=>$uid,
                'name_desc'=>$gift->name_desc,
                'icon'=>$gift->icon,
                'cost'=>$gift->cost,
                'bid'=>$bid,
                'gift_id'=>$gift_id,
                'cost_recharge'=>0,
                'cost_reward'=>0
            ];
        if($user_gift && $user_gift->num >0){
            //$send_info['cost'] = 0;
            $user_gift->num -=1;
            $user_gift->save();
            return  BookGiftsSend::addGift($send_info);
        }else{
            $result = self::payCoin($gift->cost,$uid);
            if(!$result) return false;
            $send_info['cost_recharge'] = $result['decrease_recharge'];
            $send_info['cost_reward'] = $result['decrease_reward'];
            return BookGiftsSend::addGift($send_info);
        }
    }

    protected static function payCoin($fee,$uid) {
        $user = UserService::getById($uid);
        if($user->balance < $fee){
            return false;
        }
        $decrease_recharge = 0;
        $decrease_reward =0;
        DB::beginTransaction();
        if ($user->charge_balance >= $fee) {
            $user->balance -= $fee;
            $user->charge_balance -= $fee;
            $decrease_recharge = $fee;
        } elseif ($user->charge_balance > 0) {
            $charge_fee = $user->charge_balance;
            $reword_fee  = $fee - $user->charge_balance;
            $user->balance -= $fee;
            $user->charge_balance -= $charge_fee;
            $user->reward_balance -= $reword_fee;
            $decrease_recharge = $charge_fee;
            $decrease_reward =$reword_fee;
        } else {
            $data['charge_balance'] = 0;
            $user->balance -= $fee;
            $user->reward_balance -= $fee;
            $decrease_reward =$fee;
        }
        try{
            $user->save();
            DB::commit();
            return compact('decrease_recharge','decrease_reward','fee');
        }catch (\Exception $e){
            DB::rollback();
        }
        return false;
    }
}