<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2019/4/11
 * Time: 15:05
 */

namespace App\Modules\User\Services;

use App\Modules\User\Models\UserBindHkWelfare;

class UserBindHkWelfareService
{
    public static function isHasGet($uid){
        $result = UserBindHkWelfare::join('users','users.openid','=','user_bind_hk_welfare.openid')
            ->where('users.id',$uid)
            ->select('user_bind_hk_welfare.id','user_bind_hk_welfare.fee','users.distribution_channel_id','users.id as uid')
            ->first();
        return   $result;
    }

    public static function isHasGetCrm(int $uid){
        $result = UserBindHkWelfare::join('users','users.openid','=','user_bind_hk_welfare.openid')
            ->where('users.id',$uid)
            ->where('user_bind_hk_welfare.type','CRM')
            ->select('user_bind_hk_welfare.id','user_bind_hk_welfare.created_at','user_bind_hk_welfare.fee','users.distribution_channel_id','users.id as uid')
            ->first();
        return   $result;
    }

    public static function getByOpenidToken($openid,$token){
        $result = UserBindHkWelfare::where('openid',$openid)->where('token',$token)->select('uid','openid','fee','type','source','token')->first();
        return $result;
    }


    public static function getfreeCurrency($uid,$fee=200,$type='BIND_HK',$source=''){
        if(self::isHasGet($uid)){
            return false;
        }
        $user = UserService::getById($uid);
        try{
            UserBindHkWelfare::create([
                'uid'=>$uid,
                'openid'=>$user->openid,
                'fee'=>$fee,
                'type'=>$type,
                'source'=>$source
            ]);
            return true;
        }catch (\Exception $e){}

        return false;
    }

    //'uid','openid','fee','type','source','token'
    public static function getfreeCurrencyV2($uid,$openid,$fee,$type,$source,$token){
        return UserBindHkWelfare::create(compact('uid','openid','fee','type','source','token'));
    }
}