love_php/app/Http/Controllers/UserController.php
2026-04-02 09:20:51 +08:00

11119 lines
462 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Http\Controllers;
use App\Common\cache\redis\ApiRedisKey;
use App\Jobs\SendVisitNoticeTemplate;
use App\Jobs\StartMessageNotice;
use App\Jobs\SyncTencenFaceid;
use App\Model\Server\TencentFaceidLog;
use App\Models\App\MsgHistory;
use App\Models\Audit;
use App\Models\College;
use App\Models\CrmRole;
use App\Models\CrmUser;
use App\Models\CrmUserLog;
use App\Models\ExchangeGoods;
use App\Models\FaceMatch;
use App\Models\Followable;
use App\Models\LoveLink;
use App\Models\Server\TouristOrder;
use App\Models\SubscribeOfficialLog;
use App\Models\SystemBlacklist;
use App\Models\UserMessageSetting;
use App\Services\MarriageService;
use Carbon\Carbon;
use App\Models\Liveperson;
use App\Models\RecommendUser;
use App\Contracts\MomentContract;
use App\Models\AreaUser;
use App\Models\ClassArea;
use EasyWeChat\Factory;
use App\Models\CoinLog;
use App\Models\UserPreference;
use App\Services\UserService;
use App\Services\SmsService;
use App\Services\YDService;
use App\Services\CronService;
use Illuminate\Support\Facades\Log;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Facades\CommonUtilsService;
use App\Jobs\SendEasySms;
use App\Models\Coin;
use App\Models\Live\Article;
use App\Models\PlatformBehavior;
use App\Models\User;
use App\Models\Linking;
use App\Models\HandleLogs;
use App\Models\LinkingRequest;
use App\Models\UserSign;
use App\Models\Wechat;
use App\Models\ProfileCourtship;
use App\Models\ProfileMarriage;
use App\Models\Salary;
use App\Models\Order;
use App\Models\VerifyLog;
use App\Models\PayOrder;
use App\Models\Rank;
use App\Models\RankHistory;
use App\Models\FriendQuestionAnswer;
use App\Models\Notice;
use App\Models\ComplaintHistory;
use App\Models\UserGift;
use App\Models\Gift;
use App\Models\Goods;
use App\Models\BadWord;
use App\Models\VipQuestionAnswer;
use App\Models\VipAnswerResult;
use App\Models\VipQuestion;
use App\Models\VipQuestionOption;
use App\Models\GiftHistory;
use App\Models\ScoreHistory;
use App\Models\Dynamic;
use App\Models\Score;
use App\Models\Character;
use App\Models\LoveCharacter;
use App\Models\LoveLanguage;
use App\Models\InviteOrder;
use App\Models\ChatMessage;
use App\Models\MessageLinkman;
use App\Utils\Messenger;
use App\Utils\Http;
use EasyWechat;
use App\Events\NoticeServer;
use App\Events\ChatMessages;
use Illuminate\Http\Request;
use App\Models\TempMember;
use App\Models\FriendQuestion;
use App\Repositories\Eloquent\SmsRepository as Sms;
use App\Repositories\Eloquent\DynamicRepository as DynamicR;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\UsersImport;
use App\Models\AppointmentPlan;
use App\Models\AppointmentHistory;
use App\Models\UserPreviewHistory;
use App\Models\InviteHistory;
use App\Models\Matchmaker;
use App\Models\Message;
use App\Models\Industry;
use App\Models\SubIndustry;
use App\Models\ProfilePhoto;
use App\Models\SubRank;
use App\Models\Address;
use App\Models\UserPreview;
use App\Models\RefundOrder;
use App\Contracts\UserContract;
use App\Jobs\FaceDelect;
use App\Models\Paas;
use App\Contracts\OrderContract;
use App\Models\LinkingBlacklist;
use App\Models\PaasUser;
use App\Models\ApproveHistory;
use App\Models\AddedBonus;
use App\Exports\ReferreExport;
use App\Models\Admin;
use App\Models\Platform;
use App\Models\AssistantUser;
use App\Models\UserProfile;
use App\Models\RedPacketOrder;
use App\Jobs\CommunityShare;
use App\Models\Community;
use App\Utils\Str;
use Illuminate\Support\Facades\Cache;
use App\Models\RedPacketActivity;
use App\Models\CommunityMoment;
use App\Jobs\SendRedPacket;
use App\Models\MatchingRate;
use App\Models\ActivityMember;
use App\Models\AssistantLinkman;
use App\Models\BannedHistory;
use App\Models\ClientComment;
use App\Models\CommunityComplaintHistory;
use App\Models\CommunityMember;
use App\Models\CommunityMomentComplaint;
use App\Models\FeedbackHistory;
use App\Models\MatchmakerClient;
use App\Models\Moment;
use App\Models\PaasWorker;
use App\Models\PlatformUser;
use App\Models\PositionHistory;
use App\Models\ProfileChangeHistory;
use App\Models\RecommendSingleHistory;
use App\Models\Referre;
use App\Models\ReferreAwardHistory;
use App\Models\TransferOrder;
use App\Models\ErrorPhoto;
use Illuminate\Support\Facades\Storage;
use App\Models\FaceIdHistory;
use App\Jobs\ReferreAward;
use Intervention\Image\ImageManagerStatic as Image;
use App\Facades\QrcodeRectService;
use App\Models\SingleProfile;
use App\Models\SignLog;
use App\Models\Live\Viewer;
use App\Jobs\SendSignCoin;
use App\Jobs\SendSignCoinV2;
use App\Jobs\SendTemplateMsg;
use App\Models\Live\Messenger as LiveMessenger;
use App\Http\Response\ResponseJson;
use App\Jobs\SendProfileCoin;
use App\Jobs\SendSubTemplateMsg;
use App\Jobs\SendIMPushMsg;
use App\Models\ExposeLog;
use App\Models\RecommendLinkingNew;
use App\Jobs\FaceMatchJob;
use App\Jobs\SignActitityMember;
use App\Models\CoinWithdrawLog;
use App\Services\IMService;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Models\TestUser;
use App\Models\WorthShare;
use App\Jobs\StoreApproveWorthShare;
use App\Models\CommunityActivity;
use App\Models\ConsultationRecords;
use App\Models\Course\Course;
use App\Models\Course\UserCourses;
use App\Models\Label;
use App\Models\LabelHistory;
use App\Models\Live\Anchor;
use App\Models\UserInfo;
use App\Models\WrongInfoHistories;
use Illuminate\Support\Facades\Hash;
use App\Models\Server\MerchantUser;
use App\Models\Server\MerchantAccount;
class UserController extends Controller
{
use ResponseJson;
protected $sms;
protected $dynamic;
protected $userCon;
protected $mobile;
protected $orderCon;
protected $momentCon;
public function __construct(Sms $sms, DynamicR $dynamic, UserContract $userCon, OrderContract $orderCon, MomentContract $moment)
{
$this->sms = $sms;
$this->dynamic = $dynamic;
$this->userCon = $userCon;
$this->orderCon = $orderCon;
$this->momentCon = $moment;
$this->mobile = '15872844805';
}
public function deleteUserAllInfo(Request $request, $user_id)
{
$user = User::find($user_id);
if (empty($user)) {
return $this->failure('用户不存在');
}
//删除活动成员
ActivityMember::where('user_id', $user->id)->forceDelete();
AssistantUser::where('user_id', $user->id)->forceDelete();
AssistantLinkman::where('user_id', $user->id)->forceDelete();
BannedHistory::where('user_id', $user->id)->forceDelete();
// Bonuse::where('user_id', $user->id)->forceDelete();
ChatMessage::where('user_id', $user->id)->orWhere('other_user_id', $user->id)->forceDelete();
ClientComment::where('user_id', $user->id)->orWhere('maker_user_id', $user->id)->forceDelete();
Community::where('user_id', $user->id)->forceDelete();
CommunityComplaintHistory::where('user_id', $user->id)->forceDelete();
CommunityMember::where('user_id', $user->id)->forceDelete();
CommunityMoment::where('user_id', $user->id)->forceDelete();
CommunityMomentComplaint::where('user_id', $user->id)->delete();
ComplaintHistory::where('user_id', $user->id)->forceDelete();
Dynamic::where('user_id', $user->id)->forceDelete();
FeedbackHistory::where('user_id', $user->id)->forceDelete();
Linking::where('user_id', $user->id)->orWhere('user_linking_id', $user->id)->forceDelete();
LinkingBlacklist::where('user_id', $user->id)->orWhere('other_user_id', $user->id)->forceDelete();
LinkingRequest::where('user_id', $user->id)->orWhere('user_linking_id', $user->id)->forceDelete();
MatchingRate::where('user_id', $user->id)->orWhere('other_user_id', $user->id)->forceDelete();
Matchmaker::where('user_id', $user->id)->forceDelete();
MatchmakerClient::where('user_id', $user->id)->orWhere('client_user_id')->forceDelete();
MessageLinkman::where('user_id', $user->id)->orWhere('other_user_id', $user->id)->forceDelete();
Moment::where('user_id', $user->id)->forceDelete();
Notice::where('user_id', $user->id)->orWhere('send_user_id', $user->id)->forceDelete();
Order::where("user_id", $user->id)->forceDelete();
PaasUser::where('user_id', $user->id)->forceDelete();
PaasWorker::where('user_id', $user->id)->forceDelete();
PlatformUser::where('user_id', $user->id)->forceDelete();
PositionHistory::where('user_id', $user->id)->forceDelete();
ProfileChangeHistory::where('owner_user_id', $user->id)->delete();
ProfileCourtship::where('user_id', $user->id)->forceDelete();
ProfileMarriage::where('user_id', $user->id)->forceDelete();
ProfilePhoto::where('user_id', $user->id)->forceDelete();
RankHistory::where('user_id', $user->id)->forceDelete();
RecommendSingleHistory::where('user_id', $user->id)->orWhere('other_user_id', $user->id)->forceDelete();
RedPacketOrder::where('user_id', $user->id)->delete();
Referre::where('user_id', $user->id)->forceDelete();
ReferreAwardHistory::where('user_id', $user->id)->forceDelete();
RefundOrder::where('user_id', $user->id)->forceDelete();
Score::where('user_id', $user->id)->forceDelete();
ScoreHistory::where('user_id', $user->id)->forceDelete();
ScoreHistory::where('user_id', $user->id)->orWhere('other_user_id', $user->id)->delete();
TempMember::where('user_id', $user->id)->forceDelete();
TransferOrder::where('user_id', $user->id)->delete();
UserPreview::where('user_id', $user->id)->orWhere('preview_user_id', $user->id)->forceDelete();
UserPreviewHistory::where('user_id', $user->id)->orWHere('preview_user_id', $user->id)->forceDelete();
Wechat::where('user_id', $user->id)->update(['user_id'=>null]);
// $user->forceDelete();
return $this->success('ok');
}
/*
* @desc: 修改资料
*/
public function marriageUpdate(Request $request)
{
$id = auth()->id();
$profile_id = ProfileMarriage::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileMarriage::find($profile_id);
} else {
$profile = new ProfileMarriage;
$profile->user_id = $id;
}
$user = auth()->user();
//保存真实姓名
$name = $request->name ?: $user->name;
if (!$name) {
$data['focus'] = 'name';
return $this->failure('请填写真实姓名', $data);
}
//行业
$industry = $request->industry ?: $user->industry;
//子行业
$industry_sub = $request->industry_sub ?: $user->industry_sub;
$user->name = $name;
$user->industry = $industry;
$user->industry_sub = $industry_sub;
$user->save();
$profile->company = $request->company ?: $profile->company;
if (!$profile->company) {
$data['focus'] = 'company';
return $this->failure('请填写工作单位', $data);
}
$profile->degree = $request->degree ?: $profile->degree;
if (!$profile->degree) {
$data['focus'] = 'degree';
return $this->failure('请选择学历', $data);
}
$profile->wechat_id = $request->wechat_id ?: $profile->wechat_id;
if (!$profile->wechat_id) {
$data['focus'] = 'wechat_id';
return $this->failure('请填写微信号', $data);
}
$profile->slogan = $request->slogan ?: ($profile->slogan ?: '为单身的幸福生活服务!');
$profile->save();
$this->checkLinkingRequest($id);
return $this->success('update_marriage_ok', $profile);
}
//检查是否有申请需要重新审核
public function checkLinkingRequest($id)
{
$request = LinkingRequest::where(['user_linking_id' => $id, 'status' => 0])->first();
//没有原因的ignore, 不再发重新审核
if (!($request && (strpos($request->reply, 'no_reply') === false))) {
return;
}
LinkingRequest::where('id', $request->id)->update(['status' => 1]);
$this->synLinking($request->user_id);
$user = User::find($request->user_linking_id);
$invitor_user = User::find($request->user_id);
$sms = $invitor_user->name . '您好,' . $user->name . '已修改资料, 重新申请加入你的福恋人脉!请访问小程序查看.';
Messenger::sendSMS($invitor_user->mobile, $sms);
Messenger::sendSMS('18682191714', $sms);
}
//仅检查是否完成必填项
public function courtshipStatus(Request $request)
{
$id = auth()->id();
$profile = ProfileCourtship::where('user_id', $id)->first();
$is_photo = count(json_decode($profile->photos));
if (!$is_photo) {
$data['focus'] = 'photos';
return $this->failure('请点击上传生活照', $data);
}
$is_graduate = count(json_decode($profile->graduate_photos));
if (!$is_graduate) {
$data['focus'] = 'graduate_photos';
return $this->failure('请点击上传毕业照', $data);
}
$is_identification = count(json_decode($profile->identification_photos));
if (!$is_identification) {
$data['focus'] = 'identification_photos';
return $this->failure('请点击上传身份证', $data);
}
$this->checkLinkingRequest($id);
return $this->success('success');
}
/*
* @desc: 修改资料
*/
public function courtshipTextUpdate(Request $request)
{
$id = auth()->id();
$profile_id = ProfileCourtship::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileCourtship::find($profile_id);
} else {
$profile = new ProfileCourtship;
$profile->user_id = $id;
}
$wechat = auth()->user()->wechat;
$user = auth()->user();
//保存真实姓名
$name = $request->name ?: $user->name;
if (!$name) {
$data['focus'] = 'name';
return $this->failure('请填写真实姓名', $data);
}
//行业
$industry = $request->industry ?: $user->industry;
//子行业
$industry_sub = $request->industry_sub ?: $user->industry_sub;
$user->name = $name;
$user->industry = $industry;
$user->industry_sub = $industry_sub;
$user->save();
$profile->age = $request->age ?: $profile->age;
if (!$profile->age) {
$data['focus'] = 'age';
return $this->failure('请填写年齡', $data);
}
$profile->sex = $request->sex ?: $profile->sex;
$profile->state = $request->state ?: $profile->state;
if (!$profile->state) {
$data['focus'] = 'state';
return $this->failure('请选择婚恋状态', $data);
}
$profile->stature = $request->stature ?: $profile->stature;
if (!$profile->stature) {
$data['focus'] = 'stature';
return $this->failure('请填写身高(厘米)', $data);
}
$profile->weight = $request->weight ?: $profile->weight;
if (!$profile->weight) {
$data['focus'] = 'weight';
return $this->failure('请填写体重(公斤)', $data);
}
$profile->province = $request->province ?: $profile->province;
$profile->city = $request->city ?: $profile->city;
$profile->resident_type = $request->resident_type ?: $profile->resident_type;
$profile->habitat = $request->habitat ?: $profile->habitat;
$profile->resident_province = $request->resident_province ?: $profile->resident_province;
$profile->resident_city = $request->resident_city ?: $profile->resident_city;
$profile->degree = $request->degree ?: $profile->degree;
if (!$profile->degree) {
$data['focus'] = 'degree';
return $this->failure('请选择最高学历', $data);
}
$profile->graduate_school = $request->graduate_school ?: $profile->graduate_school;
if (!$profile->graduate_school) {
$data['focus'] = 'graduate_school';
return $this->failure('请填写毕业学校', $data);
}
$profile->work_sort = $request->work_sort ?: $profile->work_sort;
if (!$profile->work_sort) {
$data['focus'] = 'work_sort';
return $this->failure('请选择工作类型', $data);
}
$profile->salary_id = $request->salary_id ?: $profile->salary_id;
if (!$profile->salary_id) {
$data['focus'] = 'salary_id';
return $this->failure('请选择收入', $data);
}
if ($request->has('h_car')) {
$profile->h_car = $request->h_car;
}
if ($request->has('h_housing')) {
$profile->h_housing = $request->h_housing;
}
$profile->introduction = $request->introduction ?: $profile->introduction;
if (!$profile->introduction) {
$data['focus'] = 'introduction';
return $this->failure('请写一些个人介绍', $data);
}
$profile->ideal_mate = $request->ideal_mate ?: $profile->ideal_mate;
if (!$profile->ideal_mate) {
$data['focus'] = 'ideal_mate';
return $this->failure('请描绘一下你未来的理解对象', $data);
}
$profile->save();
return $this->success('update_courtship_text_ok', $profile);
}
/*
* @desc: 修改资料
*/
public function courtshipMediaUpdate(Request $request)
{
$id = auth()->id();
$profile_id = ProfileCourtship::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileCourtship::find($profile_id);
} else {
$profile = new ProfileCourtship;
$profile->user_id = $id;
}
$wechat = auth()->user()->wechat;
$profile->photos = $request->photos ? json_encode($request->photos) : $profile->photos;
$profile->graduate_photos = $request->graduate_photos ? json_encode($request->graduate_photos) : $profile->graduate_photos;
$profile->identification_photos = $request->identification_photos ? json_encode($request->identification_photos) : $profile->identification_photos;
$profile->other_photos = $request->other_photos ? json_encode($request->other_photos) : $profile->other_photos;
$profile->wechat_qrcode = $request->wechat_qrcode ? json_encode($request->wechat_qrcode) : $profile->wechat_qrcode;
$profile->save();
return $this->success('update_courtship_media_ok', $profile);
}
//* @desc: 我的人脉详情
public function linking()
{
$id = auth()->id();
$user = User::with('wechat', 'profileCourtship', 'profileMarriage')->find($id);
if ($user->from_openid) {
$invitor = Wechat::where('openid', $user->from_openid)->with('user')->first();
if ($invitor) {
$this->linkingRequestStore($id, $invitor->user_id, '我已加入你的熟人圈了!');
/*if($user->type=='single'){
$this->linkingRequestStore($id, $invitor->user_id, '我已加入你的熟人圈了!');
}else{
//成为我的人脉
$linking = new Linking;
$linking->user_id = $id;
$linking->user_linking_id = $invitor->user_id;
$linking->save();
$this->synLinking();
$sms = $invitor->user->name.'您好,'.$user->name.'已加入你的福恋人脉!请访问小程序查看.';
Messenger::sendSMS($invitor->user->mobile, $sms);
Messenger::sendSMS('18682191714', $sms);
}*/
//成为我的人脉
$linking = new Linking;
$linking->user_id = $invitor->user_id;
$linking->user_linking_id = $id;
$linking->save();
$this->synLinking($invitor->user_id);
// $user->is_linked = 1;
// $user->save();
$user = User::with('wechat', 'profileCourtship', 'profileMarriage')->find($id);
}
}
return $this->success('user', $user);
}
//* @desc 人脉列表
public function userLinkings(Request $request, $id)
{
$type = $request->type ?: 'marriage';
$sex = ($request->sex == '女') ? 2 : 1;
$linking_ids = Linking::where('user_id', $id)->pluck('user_linking_id');
if ($type == 'marriage') {
$profile = ProfileMarriage::with('user.wechat')->whereIn('user_id', $linking_ids);
} else {
$profile = ProfileCourtship::with('user.wechat')->whereIn('user_id', $linking_ids)->where('sex', $sex);
}
$linkings = $profile->paginate();
$user = User::with('wechat')->find($id);
return $this->success('user_linkings', compact('linkings', 'user'));
}
//* @desc: 用户详情
public function user($id = null)
{
$user_id = auth()->id();
$requestLinking = LinkingRequest::where(['user_id' => $user_id, 'user_linking_id' => $id])->first();
//第一介绍人暂时开放所以权限
if ($id && $user_id != 148) {
$ids_1st = Linking::where('user_id', $user_id)->pluck('user_linking_id');
$ids_1st->push($user_id);
$ids_2nd = Linking::whereIn('user_id', $ids_1st)->pluck('user_linking_id');
//
if (!in_array($id, $ids_2nd->toArray()) && !$requestLinking) {
return $this->failure('只能看二度以内的人脉详情');
}
}
$id = $id ?: $user_id;
$user = User::with('wechat', 'profileCourtship', 'profileMarriage')->find($id);
// 有申请需要处理
if (isset($requestLinking) && $requestLinking->status == '1') {
$user->is_request = $requestLinking->id;
}
$salaries = Salary::all();
if ($user->id != $user_id) {
$user->is_followed = auth()->user()->isFollowing($user);
// $user->is_linked = Linking::where(['user_id'=>$id, 'user_linking_id'=>$user_id])->count();
}
if ($user->wechat && $user->wechat->gender) {
$user->sex = $user->wechat->gender;
}
return $this->success('user', compact('user', 'salaries'));
}
//* @desc: 申请加入人脉
public function linkingRequest($target_id)
{
$this->linkingRequestStore(auth()->id(), $target_id, '申请加入你的人脉');
return $this->success('request_ok', $target_id);
}
public function linkingRequestStore($user_id, $target_id, $message)
{
$target_user = User::find($target_id);
$user = User::find($user_id);
$sms = $target_user->name . '您好,' . $user->name . '申请加入你的福恋人脉!请访问小程序查看.';
$this->sms->sentMessage($target_user->mobile, $sms);
$this->sms->sentMessage('18682191714', $sms);
$linking_id = LinkingRequest::where(['user_id' => $target_id, 'user_linking_id' => $user_id])->where('status', 0)->value('id');
if (!$linking_id) {
$linking_request = new LinkingRequest;
$linking_request->user_id = $target_id;
$linking_request->user_linking_id = $user_id;
$linking_request->status = 1;
$linking_request->message = $message;
$linking_request->save();
$linking_id = $linking_request->id;
$target_user->save();
$this->synLinking($user_id);
}
}
//* @desc: 我的人脉列表
public function myLinkings(Request $request)
{
if ($request->status == 1) {
$ids = Linking::where('user_id', auth()->id())->pluck('user_linking_id');
$users = User::whereIn('id', $ids)->with('wechat')->paginate();
} else {
$users = LinkingRequest::where('user_id', auth()->id())->where('status', 1)->with('linking_user.wechat')->paginate();
}
return $this->success('mylinkings', $users);
}
//* @desc: 同意申请人脉
//* status: 1: 待处理, 0:已处理
public function linkingConfirm($id)
{
$lr = LinkingRequest::find($id);
$id = auth()->id();
//check i
if ($lr->user_id != $id) {
return $this->failure('这不是你的人脉请求');
}
if ($lr->status == 1) {
$lr->status = 0;
$lr->reply = '同意';
$lr->save();
$linking = new Linking;
$linking->user_id = $lr->user_linking_id;
$linking->user_linking_id = $id;
$linking->save();
//同步人脉数
$this->synLinking($linking->user_id);
}
return $this->success('linking_confirm');
}
//* @desc: 勿略人脉请求
public function linkingCancel(Request $request, $id)
{
$lr = LinkingRequest::find($id);
$id = auth()->id();
$user = auth()->user();
//todo check i
if ($lr->user_id != $id) {
return $this->failure('这不是你的人脉请求');
}
if ($lr->status == 1) {
$lr->status = 0;
$lr->reply = $request->reply ?: 'no_reply';
//没有拒绝则返回
if (strpos($lr->reply, 'no_reply') === false) {
$linking_user = User::find($lr->user_linking_id);
$sms = $linking_user->name . '您好,您加入' . $user->name . '的人脉未通过,原因:' . $request->reply . '!请进入福恋小程序:我的->个人资料完善信息';
Messenger::sendSMS($linking_user->mobile, $sms);
Messenger::sendSMS('18682191714', $sms);
}
$lr->save();
$this->synLinking();
}
return $this->success('linking_refuse');
}
//* @desc: 取消人脉
public function linkingDestroy($id)
{
$user_id = auth()->id();
Linking::where(['user_id' => $user_id, 'user_linking_id' => $id])->delete();
$this->synLinking();
return $this->success('linking_destroy');
}
//* @desc: 我的有关注者
public function myFollows()
{
$follows = auth()->user()->followings()->with('wechat')->paginate();
return $this->success('follows', $follows);
}
//* @desc: 我的粉丝
public function myFans()
{
return $this->success('follows', auth()->user()->followings()->paginate());
}
public function synLinking($id = null)
{
// $id = $id?:auth()->id();
// $user = User::find($id);
// $ids = Linking::where('user_id', $id)->pluck('user_linking_id');
// //todo check user->type
// $user->marriage_linkings = ProfileMarriage::whereIn('user_id', $ids)->count();
// $user->single_female_linkings = ProfileCourtship::whereIn('user_id', $ids)->where('sex', '2')->count();
// $user->single_male_linkings = ProfileCourtship::whereIn('user_id', $ids)->where('sex', '1')->count();
// $user->save();
return true;
}
/**
* 会员等级列表
*/
public function ranks()
{
$user_id = auth()->id();
$ranks = Rank::orderBy('price', 'asc')->get();
$score_obj = $this->getAccountScore($user_id);
if (empty($score_obj)) {
return $this->failure('服务错误,请重试');
}
$score = $score_obj->remain_amount;
$rank_id = auth()->user()->rank_id;
$deadline = '';
if (empty($rank_id)) {
$my_rank_price = 0;
$my_rank_name = '';
} else {
$my_rank_price = Rank::where('id', $rank_id)->value('price');
$my_rank_name = Rank::where('id', $rank_id)->value('name');
$h = RankHistory::where('user_id', $user_id)->where('rank_id', $rank_id)->whereNotNull('deadline')->orderBy('deadline', 'desc')->first();
if (empty($h)) {
$deadline = '';
} else {
$deadline = date('Y-m-d', strtotime($h->deadline));
}
}
return $this->success('ok', compact('ranks', 'score', 'my_rank_price', 'my_rank_name', 'deadline'));
}
/**
* 会员列表
* @return [type] [description]
*/
public function ranksV2(Request $request)
{
//会员列表
$name = $request->input('name', '黄金');
$rank = Rank::where('id', 9)->first();
if (empty($rank)) {
return $this->failure('没有该会员类型');
}
$sub_ranks = SubRank::where('rank_id', $rank->id)->orderBy('price', 'desc')->orderBy('id', 'desc')->get();
$rank->sub_ranks = $sub_ranks;
$rank->feature = json_decode($rank->feature, true);
$rank->explain = json_decode($rank->explain, true);
$rank->official_feature = json_decode($rank->official_feature, true);
//个人信息
$user = auth()->user();
$wechat = Wechat::where('user_id', $user->id)->select('avatar', 'avatar2', 'official_openid')->first();
$avatar = $user->photo;
if ($wechat) {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
$official_openid = $wechat->official_openid;
$user->official_openid = $official_openid;
}
$user->avatar = $avatar;
$deadline = RankHistory::where('user_id', $user->id)->where('rank_id', $user->rank_id)->orderBy('deadline', 'desc')->value('deadline');
$user->rank_deadline = $deadline;
$rank_name = Rank::where('id', $user->rank_id)->value('name');
$user->rank_name = $rank_name;
$score = $this->getAccountScore($user->id);
return $this->success('ok', compact('user', 'rank', 'score'));
}
public function rankList(Request $request)
{
$list = Rank::where('is_show', 1)->orderBy('id', 'desc')->get();
foreach ($list as $rank) {
$rank->feature = json_decode($rank->feature);
$min_rank = SubRank::where('rank_id', $rank->id)->orderBy('price', 'asc')->first();
$max_rank = SubRank::where('rank_id', $rank->id)->orderBy('price', 'desc')->first();
$rank->min_price = $min_rank ? $min_rank->price : null;
$rank->max_price = $max_rank ? $max_rank->price : null;
$rank->min_discount_price = $min_rank ? $min_rank->discount_price : null;
$rank->max_discount_price = $max_rank ? $max_rank->discount_price : null;
}
$user = auth()->user();
$deadline = RankHistory::where('user_id', $user->id)->where('rank_id', $user->rank_id)->orderBy('deadline', 'desc')->value('deadline');
$user->rank_deadline = $deadline;
$rank_name = Rank::where('id', $user->rank_id)->value('name');
$user->rank_name = $rank_name;
return $this->success('ok', compact('list', 'user'));
}
/**
* 会员等级用户信息
*/
public function rankUser(Request $request)
{
$user = auth()->user();
$wechat = Wechat::where('user_id', $user->id)->select('avatar', 'avatar2')->first();
$user->avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
$user->rank_name = Rank::where('id', $user->rank_id)->value('name');
return $this->success('ok', $user);
}
/**
* 积分记录
*/
public function scoreHistories(Request $request)
{
$user_id = auth()->id();
$score_histories = ScoreHistory::where('user_id', $user_id)->orderBy('id', 'desc')->paginate();
foreach ($score_histories as $score_history) {
$other_user_name = '';
if ($score_history->other_user_id) {
$other_user_name = User::where('id', $score_history->other_user_id)->value('name');
}
$score_history->other_user_name = $other_user_name;
}
return $this->success('ok', $score_histories);
}
/**
* 好友设置问题
* 弃用
*/
public function setFriendQuestions(Request $request)
{
// $user = auth()->user();
// $questions = $request->input('questions', []);
// if($request->questions){
// $user->friend_question = json_encode($questions);
// }
// $user->save();
// return $this->success('ok');
}
/**
* 好友问题
* 弃用
*/
public function friendQuestions(Request $request, $id)
{
// $questions = User::where('id', $id)->value('friend_question');
// $question_arr = json_decode($questions, true);
// return $this->success('ok', compact('question_arr'));
}
/**
* 个人中心
*/
public function userV2(Request $request)
{
$user = auth()->user();
$user_id = $user->id;
$user->isSuperRank = $user->isSuperRank();
$wechat = Wechat::where('user_id', $user->id)->select('avatar', 'avatar2')->first();
$avatar = '';
if (!empty($wechat)) {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
}
$user->avatar = $avatar;
//等级
$rank_name = '';
$deadline = null;
if ($user->rank_id) {
$rank_name = Rank::where('id', $user->rank_id)->value('name');
$deadline = RankHistory::where('user_id', $user_id)->where('rank_id', $user->rank_id)->orderBy('deadline', 'desc')->value('deadline');
} elseif ($user->temp_member) {
$rank_name = '临时';
}
if (empty($deadline)) {
$deadline = '2119-10-01 01:00:00';
}
$user->rank_name = $rank_name;
//会员到期时间
$user->deadline = $deadline;
//粉丝数
$rd_user_key = User::cacheUserKey($user->id);
if (Cache::has($rd_user_key)) {
$rd_user = Cache::get($rd_user_key);
} else {
$user->cacheUser();
$rd_user = Cache::get($rd_user_key);
}
$user->fans_count = $rd_user->fans_count;
$user->follow_count = $rd_user->follow_count;
$user->friend_count = $rd_user->friend_count;
//推荐人
$marriage = Wechat::where('openid', $user->from_openid)->select('user_id')->first();
if ($marriage) {
$name = User::where('id', $marriage->user_id)->value('name');
$type = User::where('id', $marriage->user_id)->value('type');
$marriage->type = $type;
$marriage->name = $name;
}
$user->marriage = $marriage;
//是否有新信息
$new_notice_count = Notice::where('user_id', $user_id)->where('status', 0)->count();
$user->new_notice_count = $new_notice_count;
$user->identification_photos = json_decode($user->identification_photos, true) ? json_decode($user->identification_photos, true) : [];
//是否有个人资料
if ($user->type == 'single') {
$profile = ProfileCourtship::where('user_id', $user_id)->select('photos', 'graduate_photos', 'identification_photos', 'other_photos', 'wechat_qrcode', 'card_num')->first();
$is_profile = 1;
$vip_profile = 1;
if (empty($profile)) {
$is_profile = 0;
$vip_profile = 0;
} else {
if (!$profile->photos || count(json_decode($profile->photos, true)) == 0) {
$vip_profile = 0;
}
if (!$profile->graduate_photos || count(json_decode($profile->graduate_photos, true)) == 0) {
$vip_profile = 0;
}
if (!$profile->identification_photos || count(json_decode($profile->identification_photos, true)) == 0) {
$vip_profile = 0;
}
if (!$profile->other_photos || count(json_decode($profile->other_photos, true)) == 0) {
$vip_profile = 0;
}
if (!$profile->wechat_qrcode || count(json_decode($profile->wechat_qrcode, true)) == 0) {
$vip_profile = 0;
}
if ($profile->identification_photos) {
$identification_photos = json_decode($profile->identification_photos, true);
} else {
$identification_photos = [];
}
}
//是否有资料
$user->is_profile = $is_profile;
//是否完成vip资料
$user->vip_profile = $vip_profile;
//是否设置好友问题(弃用)
// $friend_question = $user->friend_question?json_decode($user->friend_question, true):[];
// $user->friend_question = $friend_question;
//爱情语言
$love_language = VipAnswerResult::where(['user_id' => $user_id, 'type' => '市级VIP'])->first();
if ($love_language) {
$is_love_language = 1;
} else {
$is_love_language = 0;
}
//交往基因
$love_character = VipAnswerResult::where(['user_id' => $user_id, 'type' => '省级VIP'])->first();
if ($love_character) {
$is_love_character = 1;
} else {
$is_love_character = 0;
}
//优势
$character = VipAnswerResult::where(['user_id' => $user_id, 'type' => '全国VIP'])->first();
if ($character) {
$is_character = 1;
} else {
$is_character = 0;
}
$user->is_love_language = $is_love_language;
$user->is_love_character = $is_love_character;
$user->is_character = $is_character;
//我的留言
$new_count = ChatMessage::where('other_user_id', $user_id)->where('status', 0)->count();
$user->new_count = $new_count;
//是否是临时会员
$user->is_temp_member = $user->temp_member;
}
//是否购买人认证
$order = Order::where('type', 'approve')->where('user_id', $user->id)->where('pay_status', "PAID")->first();
$approve_order = 0;
if ($order) {
$approve_order = 1;
}
// $now_time = time();
// $create_time = strtotime($user->created_at->toDateTimeString());
// if ($create_time + 24 * 3600 >= $now_time) {
// $approve_order = 1;
// }
$user->approve_order = $approve_order;
//是否退认证费
$refund_approve_status = $this->isRefundApprove($user->id);
$user->refund_approve_status = $refund_approve_status;
//是否是对所有人隐身访问
//生活照
$user->lifePhotos = $this->userCon->lifePhotos($user->id, 3);
//个人资料
if ($user->type == 'single') {
$user->profile = $this->userCon->singleProfile($user->id);
} else {
$user->profile = $this->userCon->marriageProfile($user->id);
}
$user->is_approved = (int)$user->is_approved;
//是否可以兑换会员
$user->can_get_super_rank = $user->canGetSuperRank();
$user->new_card_num = ($user->card_num) ? substr_replace($user->card_num, '********', -8, 8) : '';
$info = UserInfo::firstOrCreate(['user_id'=>$user->id],['message_notice'=>1,'label_notice'=>1]);
//是否开启新消息提醒
$user->message_notice = $info ? $info->message_notice : 1;
//是否开启夸夸我提醒
$user->label_notice = $info ? $info->label_notice : 1 ;
return $this->success('ok', $user);
}
/**
* 个人中心
*/
public function userV3(Request $request)
{
$user = auth()->user();
$rd_user_key = User::cacheUserKey($user->id);
$user->cacheUser();
$rd_user = Cache::get($rd_user_key);
if($rd_user){
$user->avatar = $rd_user->userAvatar();
}else{
$user->avatar = null;
}
$wechat = $user->wechat;
//会员到期时间
$user->deadline = $rd_user->rank_deadline;
$user->fans_count = $rd_user->fans_count;
$user->follow_count = $rd_user->follow_count;
$user->preview_count = $rd_user->preview_count;
$user->friend_count = $rd_user->friend_count;
//是否有新信息
$user->new_notice_count = Notice::where('user_id', $user->id)->where('status', 0)->count() ?: 0;
$user->is_approved = (int)$user->is_approved;
//今日打招呼次数
$time = date('Y-m-d 00:00:00');
$user->request_num = LinkingRequest::where('user_linking_id',$user->id)->whereBetween('created_at', [$time,now()])->count();
//今日购买打招呼次数
$user->pay_num = CoinLog::where('user_id',$user->id)->where('type','friend_request')->where('type_id',0)->whereBetween('created_at', [$time,now()])->count();
//剩余次数
$user->surplus_num = 3+$user->pay_num-$user->request_num;
//会员剩余福币
$user->coin;
//是否可以兑换会员
$user->can_get_super_rank = $user->canGetSuperRank();
//是否完善资料
$user->is_profile = ($this->userCon->isCompleteProfileV5($user)) ? 1 : 0;
//是否完善其他资料
$user->is_other_profile = $user->isCompletedProfile("mp_other_info");
$user->profile_courtship = ProfileCourtship::select('degree', 'graduate_school', 'educate_photo','introduction',
'ideal_mate', 'birthday', 'city','message_config')
->where('user_id', $user->id)->first();
// if ($user->profileCourtship || $user->profileMarriage) {
// unset($user->profileCourtship);
// unset($user->profileMarriage);
// }
if (!empty($user->identification_photos)) {
$user->identification_photos = json_decode($user->identification_photos);
} else {
$user->identification_photos = [];
}
//已分享的
//已分享注册的
//非saas端参与的活动数
//saas端参与的活动数
$invite_count = 0;
$invite_register_count = 0;
$no_saas_participate_count = 0;
$saas_participate_count = 0;
if (!empty($user->wechat)) {
$invite_count = InviteHistory::where('invite_openid', $user->wechat->openid)->whereHas('user')->whereNotNull('user_id')->where('type', 'FIRST')->count() ?: 0;
// $invite_register_count = User::where('from_openid', $user->wechat->openid)->count() ?: 0;
$invite_register_count = User::query()->where(function($sql) use($user) {
$sql = $sql->where('from_user_id',$user->id);
if ($user->wechat && $user->wechat->openid) {
$sql->orWhere("from_openid", $user->wechat->openid);
}
})->count();
}
// $invite_count = User::where('from_openid', $user->wechat->openid)->count()?:0;
$user->invite_count = $invite_count;
$user->invite_register_count = $invite_register_count;
$no_saas_participate_count = Order::where(['type'=>'activity','user_id'=>$user->id,'pay_status'=>'PAID'])->count();
$merchant_user_id = MerchantUser::where('user_id',$user->id)->value('id');
if($merchant_user_id){
$activity_ids = CommunityActivity::where('class','one')->pluck('id');
$saas_participate_count = TouristOrder::where(['account_id'=>$merchant_user_id,'type'=>'community','pay_status'=>1])->whereIn('type_id',$activity_ids)->count();
}
$user->participate_count = $no_saas_participate_count + $saas_participate_count;
if ($user->type == 'single') {
$introductionVerifyResultCode__key = $this->userCon->KYE_IVRC . $user->id;
$ideal_mateVerifyResultCode_key = $this->userCon->KYE_IMVRC . $user->id;
$interest_hobbyVerifyResultCode_key = $this->userCon->KYE_IMPHO . $user->id;
if($user->profile_courtship){
//个人介绍
$user->introduction_verifyResultCode = $this->userCon->geTextVerifyCode($introductionVerifyResultCode__key,$user->profile_courtship->introduction);
//择偶标准
$user->ideal_mate_verifyResultCode = $this->userCon->geTextVerifyCode($ideal_mateVerifyResultCode_key,$user->profile_courtship->ideal_mate);
//兴趣爱好
$user->interest_hobby_verifyResultCode = $this->userCon->geTextVerifyCode($interest_hobbyVerifyResultCode_key,$user->profile_courtship->interest_hobby);
//是否被标记
}else{
$user->introduction_verifyResultCode = null;
$user->ideal_mate_verifyResultCode = null;
$user->interest_hobby_verifyResultCode = null;
}
$user->tag_status = WrongInfoHistories::where('user_id',$user->id)->where('type','tag')->where('status',1)->count();
}
$user->approve_history_body_reason = ApproveHistory::where(['type'=>'body','user_id'=>$user->id])->where('ways',1)->value('reason');
//是否有兑换商品入口
$user->has_sale_goods = ExchangeGoods::hasSaleGoods();
//消息提醒
$user->message_notice = UserInfo::where('user_id',$user->id)->value('message_notice') ?: 0;
//是否关注公众号
if ($wechat) {
$user->is_subscribe = SubscribeOfficialLog::query()->where('openid', $wechat->official_openid)->value('is_subscribed');
}
$user->friend_max_year_after = (new MarriageService())->getFriendMaxYearAfter($user->id);
if ($user->is_marriage_approved == 0){
$audit = Audit::query()->where('user_id', $user->id)
->where('type', Audit::TYPE_MARRIAGE_APPROVE)
->orderByDesc('id')
->first();
if ($audit){
$user->is_marriage_approved = $audit->status == 0 ? 2 : $audit->status;
}
}
//分享个人详情
$user->user_share_qrcode = $user->userDetailQrcode?$user->userDetailQrcode->qrcode_path:'';
return $this->success('ok', $user);
}
/**
* 用户消息配置
*/
public function updateMessageConfig(Request $request){
$message_config = $request->message_config;
$user = auth()->user();
ProfileCourtship::where('user_id',$user->id)->update(['message_config' => $message_config]);
return $this->success('ok');
}
/**
* 我要上推荐
*/
public function userRecommendState(Request $request)
{
$type = $request->input('type', 1);
$area_id = $request->input('area_id', 1);
$user = auth()->user();
if (empty($user)) {
return $this->failure('请登录');
}
if ($user->type == 'single') {
$profile = $user->profileCourtship;
} else {
return $this->failure('介绍人不能上推荐');
}
$is_audited = AreaUser::where('user_id', $user->id)->where('area_id', $area_id)->orderBy('id', 'desc')->value('is_audited');
if ($is_audited === NULL) {
$is_audited = 2;
}
$has_apply_area = $is_audited;
$profile->nickname = $user->nickname;
$profile->is_approved = $user->is_approved;
$profile->is_real_approved = $user->is_real_approved;
$profile->is_educate_approved = $user->is_educate_approved;
$profile->industry = $user->industry;
$profile->industry_sub = $user->industry_sub;
//头像是否合格
$profile->is_photo_audited = $user->is_photo_audited;
$profile->photo = $user->photo;
//生活照
$photos = ProfilePhoto::where('user_id', $user->id)->get();
$profile->photos = $photos;
//年龄
$age = \CommonUtilsService::getAge($profile->birthday);
$profile->age = $age;
//完整度
$result = $this->userCon->profileIntegrity($profile, $user);
$profile->profile_count = $result['count'];
$profile->profile_total_count = $result['total_count'];
$percentage = $profile->profile_count / $profile->profile_total_count * 100;
$state['info'] = 0;
$state['is_real_approved'] = 0;
$state['is_educate_approved'] = 0;
if ($percentage >= 100 && count($profile->photos) >= 6 && strlen($profile->interest_hobby) >= 50 && strlen($profile->introduction) >= 300 && strlen($profile->ideal_mate) >= 200) {
$state['info'] = 1;
}
$state['is_real_approved'] = $profile->is_real_approved;
$state['is_educate_approved'] = $profile->is_educate_approved;
$apply_state['has_apply_area'] = $has_apply_area;
return $this->success('ok', ['state' => $state, 'apply_state' => $apply_state]);
}
/**
* 是否退认证费
* 0正常 1邀请好友 2退费
* @param [type] $user_id [description]
* @return boolean [description]
*/
public function isRefundApprove($user_id)
{
$status = 0;
$order = Order::where('user_id', $user_id)->where('type', 'approve')->where('pay_status', 'PAID')->first();
if ($order) {
//是否邀请好友
$from_openid = Wechat::where('user_id', $user_id)->value('openid');
$count = User::where('from_openid', $from_openid)->count();
if ($count) {
$status = 1;
}
$refund_order = RefundOrder::where('user_id', $user_id)->where('type', 'approve')->where('is_hook', 1)->first();
if ($refund_order) {
$status = 2;
}
}
return $status;
}
/**
* 新消息
* @param Request $request [description]
* @return [type] [description]
*/
public function newMessageCount(Request $request)
{
$user_id = auth()->id();
// $users = MessageLinkman::where('user_id',$user_id)->pluck('other_user_id')->toarray();
// $friend_count = ChatMessage::where('status', 0)->where('other_user_id', $user_id)->wherein('user_id',$users)->count();
$linkmen = DB::table("message_linkmen")->where('user_id', $user_id)->orWhere('other_user_id', $user_id);
$friend_count = DB::table('chat_messages')->rightJoinSub($linkmen, 'ufutx_message_linkmen', function($join) {
$join->on('chat_messages.other_user_id', 'message_linkmen.other_user_id');
})->where('chat_messages.other_user_id', $user_id)->where('chat_messages.status', 0)->whereNull('chat_messages.deleted_at')->count();
$order_count = 0;
$merchant_user_id = $this->matchMerchantUser($user_id);
if ($merchant_user_id) {
$order_count = DB::table('tourist_orders')
->join('community_activities', 'tourist_orders.type_id', 'community_activities.id')
// ->where('community_activities.class', 'one')
->where('channel', 3)
->where('tourist_orders.type', 'community')
->where('account_id', $merchant_user_id)
->where('pay_status', 0)
->count();
// if($user_id == 130163 || $user_id == 119488 || $user_id == 134494){
$date_time = date('Y-m-d H:i:s');
$order_count = DB::table('tourist_orders')
->join('community_activities', 'tourist_orders.type_id', 'community_activities.id')
// ->where('community_activities.class', 'one')
->where('channel', 3)
->where('tourist_orders.type', 'community')
->where('account_id', $merchant_user_id)
->where('pay_status', 0)
->whereRaw("DATE_ADD(ufutx_tourist_orders.created_at, INTERVAL 1 DAY) > '{$date_time}'")
->count();
// $new_count = $this->userCon->newsCount(auth()->id());
// return $this->success('ok', compact('new_count','friend_count','order_count'));
// }
}
$new_count = $this->userCon->newsCount(auth()->id());
return $this->success('ok', compact('new_count','friend_count','order_count'));
}
/**
* 测试结果
*/
public function testResult(Request $request, $id)
{
//测试结果
$city_answer_result = VipAnswerResult::where('user_id', $id)->where('type', '市级VIP')->orderBy('id', 'desc')->first();
$province_answer_result = VipAnswerResult::where('user_id', $id)->where('type', '省级VIP')->orderBy('id', 'desc')->first();
$country_answer_result = VipAnswerResult::where('user_id', $id)->where('type', '全国VIP')->orderBy('id', 'desc')->first();
$city_test_arr = [];
if ($city_answer_result) {
$city_test_arr = json_decode($city_answer_result->result, true);
}
$love_languages = $this->character($city_test_arr, '市级VIP');
$province_test_arr = [];
if ($province_answer_result) {
$province_test_arr = json_decode($province_answer_result->result, true);
}
$love_characters = $this->character($province_test_arr, '省级VIP');
$country_test = '';
if ($country_answer_result) {
$country_test_arr = json_decode($country_answer_result->result, true);
$country_test = $this->countryVipResult($country_test_arr);
}
$character = Character::where('sub_type', $country_test)->first();
if ($character) {
$character->profession = json_decode($character->profession, true);
}
return $this->success('ok', compact('love_languages', 'love_characters', 'character'));
}
public function getSelfInfo($user)
{
try {
$my_user = auth()->user();
if (empty($my_user)) {
$my_user = $this->authCheck();
}
if ($my_user) {
//添加访问记录
if($my_user->hidden_profile == 'NONE'){
$my_user->addUserPreview($user->id);
}
//是否已关注
$arr['self'] = 1;
if ($my_user->id != $user->id) {
$arr['is_followed'] = $my_user->isFollowing($user);
$arr['self'] = 0;
}
//是否是好友
$arr['is_friend'] = $this->userCon->isFriend($user->id, $my_user->id) ? 1 : 0;
//判断自己是否是福恋使者
$arr['is_messenger'] = $my_user->isMessenger();
//是否单独设置隐身访问
$arr['is_hidden'] = $this->userCon->isHidden($my_user->id, $user->id, 'alone');
//是否认证
$arr['self_is_approved'] = $my_user->is_approved;
//是否真人认证
$arr['self_is_real_approved'] = $my_user->is_real_approved;
//是否完善基本资料
$arr['self_base_info'] = $this->userCon->infoTaskProgress() == 1 ? 1 : 0;
//是否完成其他三步资料
$arr['self_other_info'] = $my_user->isCompletedProfile('mp_other_info');
//是否关闭了资料
$arr['self_hidden_profile'] = 1;
if($my_user->hidden_profile == 'NONE'){
$arr['self_hidden_profile'] = 0;
}
} else {
$arr['is_followed'] = 0;
$arr['is_friend'] = 0;
$arr['self'] = 0;
$arr['is_messenger'] = 0;
$arr['is_hidden'] = 0;
$arr['self_is_approved'] = 0;
$arr['self_base_info'] = 0;
$arr['self_other_info'] = 0;
$arr['self_is_real_approved'] = 0;
$arr['self_hidden_profile'] = 0;
}
return $arr;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public function otherUser(Request $request, $user_id)
{
//是否在黑名单
$is_black = LinkingBlacklist::where('user_id', $user_id)->where('other_user_id', auth()->id())->count();
if ($is_black) return $this->failure('您已被对方拉入黑名单');
//是否将对方拉入黑名单
$is_black = LinkingBlacklist::where('user_id', auth()->id())->where('other_user_id', $user_id)->count();
if ($is_black) return $this->failure('您已将对方拉入黑名单,请先移除黑名单');
$frozen_state = $this->userCon->getUserFrozenState($user_id);
if($frozen_state != 0){
return $this->failure('该用户资料异常,暂时无法查看');
}
$rd_user_key = User::cacheUserKey($user_id);
if (Cache::has($rd_user_key)) {
$user = $rd_user = Cache::get($rd_user_key);
} else {
$user = User::withCount('moments')->find($user_id);
if (empty($user)) return $this->failure('真不巧,用户最近关闭了资料~');
$user->cacheUser();
$rd_user = Cache::get($rd_user_key);
}
if (empty($user)) return $this->failure('真不巧,用户最近关闭了资料~');
if ($user->hidden_profile != 'NONE' && $request->input('versions') == 'v5.3') return $this->failure('真不巧,用户最近关闭了资料~');
$arr = $this->getSelfInfo($user);
foreach ($arr as $key => $value) {
$user->$key = $value;
}
$user->isSuperRank = $rd_user->is_super_rank;
$profile = $user->type == 'single' ? $rd_user->profileCourtship : $rd_user->profileMarriage;
if(!$profile){
return $this->failure('用户信息已关闭');
}
$user->profile_courtship = $profile;
//Ta是否完成资料
$isCompleteProfile = $this->userCon->isCompleteProfileV2($profile, $user->type);
if (!empty($user)) {
$isCompleteProfile = $user->id != $user_id ? $isCompleteProfile : true;
}
$user->isCompleteProfile = $isCompleteProfile;
//获取头像
$user->avatar = $user->userAvatar();
//没有购买会员且有临时会员
// $rank = $user->rank;
//年龄
$user->age = $rd_user->age ? ($rd_user->age) . '岁' : "未知";
//生活照
$profile_photos = $user->profilePhoto()->get()->toArray();
if (count($profile_photos) == 0 ) {
if ($user->photo && $user->is_photo_audited == 1) {
$photo['photo'] = $user->photo;
}else {
$photo['photo'] = User::DefaultAvatar;
}
$profile_photos[] = $photo;
}
$user->profile_photos = $profile_photos;
$user->year = null;
if($user->profile_courtship->birthday){
$user->year = substr($user->profile_courtship->birthday,2,2);
}
//粉丝数
$user->fans_count = $rd_user->fans_count;
if(isset($user->profileCourtship->mate_conditon))
$user->profileCourtship->mate_conditon = json_decode($user->profileCourtship->mate_conditon,true);
//点击数
$user->preview_count = (int)$user->previewCacheCount();
$user = $user->toArray();
$info = UserInfo::where('user_id',$user_id)->first();
$user['label_notice'] = $info ? $info->label_notice : 1;
if (isset($user['profile_courtship'])) {
if (!$user['profile_courtship']) {
$user['profile_courtship'] = $user['profile_marriage'];
}
} else {
$user['profile_courtship'] = $user['profile_marriage'];
}
//是否禁止登录
$now = date('Y-m-d H:i:s');
$sbl = SystemBlacklist::where('user_id', $user_id)->where('start_time', "<", $now)->where('end_time', '>', $now)->first();
$user['is_banned'] = $sbl?1:0;
//牵线服务id
$user['service_id'] = 1279;/*1353*/
//推荐服务id
unset($user['mobile'], $user['email']);
//过滤location
unset($user['profile_courtship']['mate_conditon']['location']);
//关闭资料 选择找到对象的状态
$user['hidden_profile_status'] = LoveLink::where('user_id', $user_id)->first() ? 1 : 0;
//邀请用户分布
$openid = Wechat::where('user_id', $user['id'])->value('openid');
$user['invite_count'] = User::query()->where(function($sql) use($user, $openid) {
$sql = $sql->where('from_user_id',$user['id']);
if ($openid) {
$sql->orWhere("from_openid", $openid);
}
})->count();
$user['invite_user_group_by_age'] = $user['invite_count'] ? (new MarriageService())->getAgeDistributeData($user['id']) : [];
//访客通知
SendVisitNoticeTemplate::dispatch(auth()->id(), $user_id)->onQueue("template_message");
return $this->success('ok', $user);
}
public function character($test_arr, $type)
{
if ($type == '市级VIP') {
$loves = LoveLanguage::select('id', 'type', 'title', 'content')->get();
foreach ($loves as $love) {
$love->num = 0;
foreach ($test_arr as $test) {
if ($test['key'] == $love->type) {
$love->num = $test['value'];
}
}
}
} elseif ($type == '省级VIP') {
$loves = LoveCharacter::select('type', 'title', 'content', 'character')->get();
foreach ($loves as $love) {
$love->num = 0;
foreach ($test_arr as $test) {
if ($test['key'] == $love->type) {
$love->num = $test['value'];
}
}
}
}
return $loves;
}
/**
* 全国VIP结果
*/
public function countryVipResult($country_test_arr)
{
$result = '';
if (!isset($country_test_arr['I'])) {
$country_test_arr['I'] = 0;
}
if (!isset($country_test_arr['E'])) {
$country_test_arr['E'] = 0;
}
if (!isset($country_test_arr['S'])) {
$country_test_arr['S'] = 0;
}
if (!isset($country_test_arr['N'])) {
$country_test_arr['N'] = 0;
}
if (!isset($country_test_arr['T'])) {
$country_test_arr['T'] = 0;
}
if (!isset($country_test_arr['F'])) {
$country_test_arr['F'] = 0;
}
if (!isset($country_test_arr['P'])) {
$country_test_arr['P'] = 0;
}
if (!isset($country_test_arr['J'])) {
$country_test_arr['J'] = 0;
}
if ($country_test_arr['P'] > $country_test_arr['J']) {
$result = 'P' . $result;
} else {
$result = 'J' . $result;
}
if ($country_test_arr['T'] > $country_test_arr['F']) {
$result = 'T' . $result;
} else {
$result = 'F' . $result;
}
if ($country_test_arr['S'] > $country_test_arr['N']) {
$result = 'S' . $result;
} else {
$result = 'N' . $result;
}
if ($country_test_arr['I'] > $country_test_arr['E']) {
$result = 'I' . $result;
} else {
$result = 'E' . $result;
}
return $result . '型';
}
/**
* 回答好友问题
* 弃用
*/
public function answerFriendQuestions(Request $request, $id)
{
// $questions = User::where('id', $id)->value('friend_question');
// if (empty($questions)) {
// $question_arr = [];
// }else{
// $question_arr = json_decode($questions, true);
// }
// if (count($question_arr)) {
// $answer = $request->input('answer',[]);
// if (!count($answer)) {
// return $this->failure('请回答问题');
// }
// $answer = json_encode($answer);
// $user_id = auth()->id();
// $question_answer = FriendQuestionAnswer::where('user_id', $user_id)->where('question_user_id', $id)->first();
// if ($question_answer) {
// $question_answer->update(['question_answer'=>$answer]);
// }else{
// FriendQuestionAnswer::create([
// 'user_id'=>$user_id,
// 'question_user_id'=>$id,
// 'question_answer'=>$answer,
// ]);
// }
// }
// return $this->success('ok');
}
/**
* 添加好友
*/
public function addFriend(Request $request, $id)
{
$user = auth()->user();
//是否禁言
// $banned = $user->isBanned('friend');
// if ($banned) {
// return $this->failure('您已被禁止申请好友,至'.$banned->end_time);
// }
$date = date('Y-m-d H:i:s');
$history = BannedHistory::where('user_id',$user->id)->where('type','friend')->first();
if (!empty($history)) {
if($history->end_time >= $date && $history->start_time <= $date) return $this->failure('你被禁止添加好友至'.$history->end_time);
}
$user_id = $user->id;
$targe_user = User::find($id);
if ($targe_user->hidden_profile == 'ALLSEX') {
return $this->success('ok');
}
//是否认证
if (empty(auth()->user()->is_approved)) return $this->failure('好友请求失败,实名认证未完善');
//判断是否是介绍人加单身或者单身加介绍人
if ($user->type != $targe_user->type) {
return $this->failure('好友请求失败,身份类型不符');
}
//判断加好友权限
$result = $this->addFriendPermission($user);
if (empty($result)) {
return $this->failure('今日申请好友次数已用完');
}
//是否是拉黑好友
$result = $this->userCon->isBlacklist($user->id, $id);
if ($result === 1) {
return $this->failure('对方设置了好友权限 暂不能加为好友');
} elseif ($result === 2) {
return $this->failure('对方已被您列入黑名单,请先移出黑名单');
}
$linking_id = LinkingRequest::where(['user_id' => $id, 'user_linking_id' => $user_id])->where('status', 0)->value('id');
if (!$linking_id) {
$linking_request = new LinkingRequest;
$linking_request->user_id = $id;
$linking_request->user_linking_id = $user_id;
$linking_request->status = 0;
$linking_request->message = $request->message ?: '申请加入你的福恋好友';
$linking_request->save();
//发送系统消息
$content = $targe_user->nickname . '您好,' . $user->nickname . '申请加你为好友!';
$message = $request->message ?: $content;
$notice = $this->sendNotice($id, $user_id, 'friend', $content, $message);
//订阅消息通知
SendSubTemplateMsg::dispatch($type = 'friend_request', $user, $targe_user)->onQueue('template_message');
//App推送消息
SendIMPushMsg::dispatch($notice->id, 'friend', $content, $user->id, $targe_user->id, $user->userAvatar())->onQueue('love');
} else {
$notice = Notice::where('user_id', $id)->where('send_user_id', $user_id)->where('type', 'friend')->update(['created_at' => date('Y-m-d H:i:s')]);
}
return $this->success('ok');
}
public function addFriendByLove($request, $user, $other_user_id)
{
$send_user = User::find($other_user_id);
//添加好友
$linking = $this->userCon->setLinking($other_user_id, $user->id);
//添加网易好友
$result = $user->addIMFriend($send_user);
if ($result) {
$linking->is_im = 1;
$linking->save();
}
//发送IM消息
if (config('app.env') == 'production') {
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$name = $send_user->is_real_approved?$send_user->name:$send_user->nickname;
$content = $name."你好,我是福恋脱单小助手小恋, 陪伴你一起找对象,有什么情感困惑可以随时找我!";
$body = ['msg'=>$content];
$result = $im_service->sendMsg($user->id, 0,$other_user_id,$type=0,$body);
}
}
/**
* 添加好友
*/
public function addFriendv2(Request $request, $id)
{
$user = auth()->user();
if ($user->id == User::LOVEID) {
//小恋添加好友
$this->addFriendByLove($request, $user, $id);
return $this->success("发送成功");
}
//是否禁言
// $banned = $user->isBanned('friend');
// if ($banned) {
// return $this->failure('您已被禁止申请好友,至'.$banned->end_time);
// }
$date = date('Y-m-d H:i:s');
$history = BannedHistory::where('user_id',$user->id)->where('type','friend')->first();
if (!empty($history)) {
if($history->end_time >= $date && $history->start_time <= $date) return $this->failure('你被禁止添加好友至'.$history->end_time);
}
$user_id = $user->id;
$targe_user = User::find($id);
if ($targe_user->hidden_profile == 'ALLSEX') {
return $this->success('ok');
}
//今日打招呼次数
$time = date('Y-m-d 00:00:00');
$num = LinkingRequest::where('user_linking_id',$user_id)->whereBetween('created_at', [$time,now()])->count();
//查看会员身份
$isSuperRank = $user->isSuperRank();
//查看今日购买次数
$pay_num = CoinLog::where('user_id',$user->id)->where('type','friend_request')->where('type_id',0)->whereBetween('created_at', [$time,now()])->count();
$num = $pay_num + 3 -$num;
if($num<=0&&$isSuperRank==0&&$user->type=='signle') return $this->failure('今日打招呼次数达到上限');
//是否是拉黑好友
$result = $this->userCon->isBlacklist($user->id, $id);
if ($result === 1) {
return $this->failure('对方设置了好友权限 暂不能加为好友');
} elseif ($result === 2) {
return $this->failure('对方已被您列入黑名单,请先移出黑名单');
}
// $linking_id = LinkingRequest::where(['user_id' => $id, 'user_linking_id' => $user_id])->where('status', 0)->value('id');
$linking = LinkingRequest::where(['user_id' => $id, 'user_linking_id' => $user_id])->where('status', 0)->orderBy('id', 'desc')->first();
$linking_id = $linking->id ?? 0;
if ($linking) {
$expire_time = strtotime("+7 day", strtotime($linking->created_at));
if ($expire_time > time()) {
$linking_id = 0;
}
}
if (!$linking_id) {
$linking_request = new LinkingRequest;
$linking_request->user_id = $id;
$linking_request->user_linking_id = $user_id;
$linking_request->status = 0;
$linking_request->message = $request->message ?: '申请加入你的福恋好友';
$linking_request->save();
//发送系统消息
$content = $targe_user->nickname . '您好,' . $user->nickname . '申请加你为好友!';
$message = $request->message ?: $content;
$notice = $this->sendNotice($id, $user_id, 'friend', $content, $message);
//订阅消息通知
SendSubTemplateMsg::dispatch($type = 'friend_request', $user, $targe_user)->onQueue('template_message');
//App推送消息
SendIMPushMsg::dispatch($notice->id, 'friend', $content, $user->id, $targe_user->id, $user->userAvatar())->onQueue('love');
//发送公众号通知
if ($targe_user->wechat && $targe_user->wechat->official_openid) {
$data['touser'] = $targe_user->wechat->official_openid;
$data['template_id'] = config('wechat.tpls.start_message_notice');
$data['url'] = '';
$data['miniprogram'] = [
'appid'=> config('wechat.mini_program.app_id'),
'pagepath'=>'/pages/users/friendRequest'
];
$data['data'] = [
"first" => "添加好友通知",
'keyword1' => date('Y-m-d H:i:s'),
'keyword2' => $user->nickname,
"remark" => "点击查看申请",
];
SendTemplateMsg::dispatch($data)->onQueue('start_message');
}
} else {
return $this->success('对方已收到打招呼消息,正在处理好友请求~');
}
return $this->success('发送成功,等待对方处理好友请求');
}
public function addFriendPermission($user)
{
$start_time = date('Y-m-d');
$end_time = date('Y-m-d H:i:s');
//当天申请加好友次数
$user_id = $user->id;
$friend_request_count = LinkingRequest::where('user_linking_id', $user_id)->whereBetween('created_at', [$start_time, $end_time])->count();
// dd($friend_request_count);
if ($friend_request_count > 7) {
return false;
}
return true;
}
/**
* 消息列表处理
*/
public function notices(Request $request)
{
//版本判断
$version = request()->input('versions');
$version = str_replace('v', '', $version);
$higher= $this->contrastVersion($version, '5.2.81');
$user_id = auth()->id();
$notices = Notice::with('otherUser:id,nickname,type,photo,is_real_approved,hidden_profile,sex')
->whereHas('otherUser', function ($sql) use($higher) {
$query = $sql->where('hidden_profile', '<>', 'ALLSEX');
if ($higher) {//高于5.2.81
$query->orWhere('id', 1);
}
})
->where('user_id', $user_id);
// ->where('receive_status',1);
$prefix = (request()->route()->getAction())['prefix'];
//请求连接
$route_name = request()->route()->getName();
if ($route_name == 'friend_requests') { //好友请求列表
$notices = $notices->where('type', 'friend');
} else {
$notices = $notices->where('type', '!=', 'friend');
}
$time = time();
$expired_id = [];
$notices = $notices->orderBy('created_at', 'desc')->paginate();
$wechat = auth()->user()->wechat;
$has_unionid = 1;
foreach ($notices as $notice) {
if ($notice->type == 'friend') {
$status = LinkingRequest::where("user_id", $notice->user_id)
->where('user_linking_id', $notice->send_user_id)
->orderBy('id', 'desc')->value('status');
$notice->deal_status = $status;
if ($notice->otherUser) {
if ($notice->otherUser->type == 'single') {
$profile = ProfileCourtship::where('user_id', $notice->send_user_id)->first();
if ($profile) {
$age = $this->getAge($profile->birthday);
$province = $profile->province;
} else {
$age = 0;
$province = '未知';
}
} else {
$profile = ProfileMarriage::where('user_id', $notice->send_user_id)->first();
if ($profile) {
$age = $this->getAge($profile->birthday);
$province = $profile->province;
} else {
$age = 0;
$province = '未知';
}
}
$notice->otherUser->age = $age;
$notice->otherUser->province = $province;
$notice->otherUser->is_super_rank = $notice->otherUser->isSuperRank($notice->otherUser->id);
if(empty($notice->otherUser->photo)) $notice->otherUser->photo = $notice->otherUser->avatar;
}
if ($notice->type == 'friend' && $notice->status == 0 && $notice->type_id != 2) {
$day = date('d', $time - strtotime($notice->created_at));
if ($day > 7) {
$expired_id[] = $notice->id;
$notice->deal_status = 2;
}
}
}
elseif ($notice->type == 'system') {
if ($notice->path_type==2 && $notice->path = "https://love.ufutx.com/h5/#/guidePage" && empty($wechat->unionid)) {
$has_unionid = 0;
}
}
$notice->has_unionid = $has_unionid;
}
Notice::where('user_id', $user_id)->where('status', 0)->update(['status' => 1]);
return $this->success('ok', $notices);
}
public function operateNotice(Request $request, Notice $notice)
{
try {
DB::beginTransaction();
$operate_status = $request->input('operate_status');
if ($notice->type == 'change_moment_topic' && $operate_status) {
$notice->operate_status = $operate_status;
if($operate_status == -1) {//拒绝
$moment = Moment::where('id', $notice->type_id)->where('user_id', auth()->id())->first();
if ($moment) {
$moment->topic_id = $moment->old_topic_id;
$moment->old_topic_id = null;
$moment->save();
}
}
$notice->save();
}
DB::commit();
return $this->success('ok');
} catch (\Exception $e) {
DB::rollBack();;
$this->getError($e);
return $this->failure();
}
}
/**
* 好友请求页面
*/
public function friendRequest(Request $request, $id)
{
$notice = Notice::findOrFail($id);
$user = User::with('wechat')->where('id', $notice->send_user_id)->first();
if (empty($user)) {
return $this->failure('该用户不存在');
}
if ($user->type == 'single') {
$profile = ProfileCourtship::where('user_id', $notice->send_user_id)->first();
if ($profile) {
$sex = $profile->sex;
$age = $this->getAge($profile->birthday);
$province = $profile->province;
} else {
$sex = 0;
$age = '无';
$province = '';
if ($notice->otherUser->wechat) {
$province = $notice->otherUser->wechat->province;
}
}
} elseif ($notice->otherUser->type == 'marriage') {
$profile = ProfileMarriage::where('user_id', $notice->send_user_id)->first();
if ($profile) {
$sex = $profile->sex;
$age = $this->getAge($profile->birthday);
$province = $profile->province;
} else {
$sex = 0;
$age = '无';
$province = '';
if ($notice->otherUser->wechat) {
$province = $notice->otherUser->wechat->province;
}
}
} else {
$sex = 0;
$age = '无';
$province = '';
if ($notice->otherUser->wechat) {
$province = $notice->otherUser->wechat->province;
}
}
$user->sex = $sex;
$user->age = $age;
$user->province = $province;
$answer = FriendQuestionAnswer::where('user_id', $user->id)->where('question_user_id', $notice->user_id)->first();
if (!empty($answer)) {
$answer->question_answer = json_decode($answer->question_answer, true);
}
if ($user->wechat) {
$user->avatar = $user->wechat->avatar2 ? $user->wechat->avatar2 : $user->wechat->avatar;
}
return $this->success('ok', compact('user', 'answer'));
}
/**
* 处理好友请求
*/
public function dealFriendRequest(Request $request, $id)
{
$user = auth()->user();
$user_id = $user->id;
$send_user_id = Notice::where('id', $id)->value('send_user_id');
$send_user = User::find($send_user_id);
$link_request = LinkingRequest::where('user_id', $user_id)->where('user_linking_id', $send_user_id)->where('status', 0)->orderBy('id','desc')->first();
if (empty($link_request)) return $this->success('ok');
if (empty($user_id)) return $this->failure('好友请求已经处理');
$status = $request->input('status');
if (empty($status)) return $this->failure('no status');
$result = [];
if ($status == 1) {
//添加好友
$linking = $this->userCon->setLinking($send_user_id, $user_id);
//添加网易好友
$result = $user->addIMFriend($send_user);
if ($result) {
$linking->is_im = 1;
$linking->save();
}
//发送IM消息
if (config('app.env') == 'production') {
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$body = ['msg'=>$link_request->message];
$result = $im_service->sendMsg($send_user_id, 0,auth()->id(),$type=0,$body);
}
//发送好友处理消息
SendSubTemplateMsg::dispatch("deal_friend_request", $user, $send_user)->onQueue("template_message");
}elseif($status == -1){
//拒绝添加好友
// $reply = $request->reply;
// if(empty($reply)) return $this->failure('请输入拒绝理由');
// $link_request->reply = $reply;
}
$link_request->status = $status;
$link_request->save();
return $this->success('ok',$result);
}
/**
* 举报
*/
public function complaint(Request $request, $id)
{
$label = $request->input('label');
$photos = $request->input('photos', []);
if(!$label){
// return $this->failure('请选择举报类型');
}else if($photos == [] || empty($photos)){
return $this->failure('请提供举报截图');
}
$this->userCon->complaint($request, auth()->id(), $id);
//短信通知
$user_name = User::where('id', auth()->id())->value('name');
$name = User::where('id', $id)->value('name');
$mobiles = Redis::smembers('repot_notice_mobile');
$param['message'] = '用户【' . $user_name . '】举报用户【' . $name . '】';
foreach ($mobiles as $mobile) {
$param['mobile'] = $mobile;
SendEasySms::dispatch($param)->onQueue('love');
}
return $this->success('ok');
}
/**
* vip题目
*/
public function vipQuestions(Request $request)
{
$type = $request->input('type', '市级VIP');
$questions = VipQuestion::with('options')->where('type', $type)->get();
foreach ($questions as $question) {
foreach ($question->options as $option) {
$option_arr = json_decode($option->question_options, true);
$question->option_arr = $option_arr;
}
}
return $this->success('ok', $questions);
}
/**
* 测试
*/
public function vipTest(Request $request)
{
$user_id = auth()->id();
$type = $request->input('type');
if (empty($type)) {
return $this->failure('no type');
}
$answers = $request->input('answer', []);
if (!count($answers)) {
return $this->failure('请选择答案');
}
VipQuestionAnswer::where(['user_id' => $user_id, 'type' => $type])->delete();
foreach ($answers as $answer) {
VipQuestionAnswer::create([
'user_id' => $user_id,
'type' => $type,
'question_id' => $answer['question_id'],
'option_value' => $answer['value'],
]);
}
$option_values = VipQuestionAnswer::where('user_id', $user_id)->where('type', $type)->distinct('option_value')->pluck('option_value');
$result_arr = [];
foreach ($option_values as &$option_value) {
$re = [];
$value = VipQuestionAnswer::where('user_id', $user_id)->where('type', $type)->where('option_value', $option_value)->count();
$re['key'] = $option_value;
$re['value'] = $value;
array_push($result_arr, $re);
}
$result = VipAnswerResult::where(['user_id' => $user_id, 'type' => $type])->first();
if (empty($result)) {
$result = VipAnswerResult::create([
'user_id' => $user_id,
'type' => $type,
'result' => json_encode($result_arr),
]);
} else {
$result->result = json_encode($result_arr);
$result->save();
}
return $this->success('ok', compact('user_id'));
}
/**
* 礼物广场
*/
public function gifts(Request $request, $id)
{
$user = null;
if (!empty($id)) {
$user = User::with('wechat')->where('id', $id)->first();
}
$score = $this->getAccountScore(auth()->id());
$gifts = Gift::all();
return $this->success('ok', compact('user', 'gifts', 'score'));
}
public function giftsV2(Request $request)
{
$gifts = Gift::all();
return $this->success('ok', compact('gifts'));
}
/**
* 用户礼物列表
*/
public function userGifts(Request $request, $id)
{
$user_id = auth()->id();
$user_gift = UserGift::with('gift')->where(['user_id' => $user_id, 'gift_id' => $id])->first();
if (empty($user_gift)) {
$user_gift = UserGift::create([
'user_id' => $user_id,
'gift_id' => $id,
'num' => 0,
]);
$user_gift->gift = Gift::find($id);
}
$gift_histories = GiftHistory::where(['user_id' => $user_id, 'type' => 'RECEVIED', 'status' => 1, 'gift_id' => $id])->get();
foreach ($gift_histories as $gift_history) {
$send_user = User::where('id', $gift_history->other_user_id)->select('name', 'id', 'type')->first();
if (empty($send_user)) {
continue;
}
$wechat = Wechat::where('user_id', $gift_history->other_user_id)->select('avatar', 'avatar2')->first();
if (empty($wechat)) {
if ($send_user->sex == 1) {
$avatar = 'http://images.ufutx.com/201811/12/0e8b72aae6fa640d9e73ed312edeebf3.png';
} else {
$avatar = 'http://images.ufutx.com/201811/12/dddd79aa2c2fc6a6f35e641f6b8fb8f5.png';
}
} else {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
}
$send_user->avatar = $avatar;
$gift_history->send_user = $send_user;
}
return $this->success('ok', compact('user_gift', 'gift_histories'));
}
/**
* 加微信请求
*/
public function addWechat(Request $request, $id)
{
$user = auth()->user();
if ($user->type == 'single') {
$wechat_qrcode = ProfileCourtship::where('user_id', $user->id)->value('wechat_qrcode');
$wechat_qrcode_arr = json_decode($wechat_qrcode, true);
if (empty($wechat_qrcode) || !count($wechat_qrcode_arr)) {
return $this->failure('您还没有上传微信');
}
} else {
$wechat_qrcode = ProfileMarriage::where('user_id', $user->id)->value('wechat_qrcode');
$wechat_qrcode_arr = json_decode($wechat_qrcode, true);
if (empty($wechat_qrcode) || !count($wechat_qrcode_arr)) {
return $this->failure('您还没有上传微信');
}
}
$content = "发了Ta的微信二维码给你喔";
$this->sendNotice($id, $user->id, 'wechat', $content);
$target_user = User::where('id', $id)->first();
$sms = $target_user->name . '您好,' . $user->name . '申请加微信好友!请访问小程序查看.';
$this->sms->sentMessage($target_user->mobile, $sms);
return $this->success('ok');
}
/**
* 加微信页面
*/
public function showWechat(Request $request, $id)
{
$user = auth()->user();
if ($user->type == 'single') {
$profile = ProfileCourtship::where('user_id', $user->id)->first();
} else {
$profile = ProfileMarriage::where('user_id', $user->id)->first();
}
$wechat = Wechat::where('user_id', $user->id)->first();
$wechat_qrcode_arr = [];
if (!empty($profile)) {
$wechat_qrcode = $profile->wechat_qrcode;
$user->wechat_id = $profile->wechat_id;
$wechat_qrcode_arr = json_decode($wechat_qrcode, true);
}
$qrcode = '';
if (is_array($wechat_qrcode_arr) && count($wechat_qrcode_arr)) {
$qrcode = $wechat_qrcode_arr[0];
} else {
$qrcode = '';
}
$user->wechat = $wechat;
$user->wechat_qrcode = $qrcode;
$other_user = User::with('wechat')->where('id', $id)->first();
return $this->success('ok', compact('user', 'other_user'));
}
/**
* 微信页面
*/
public function showWechatV2(Request $request, $id)
{
$notice = Notice::find($id);
$user = User::with('wechat')->where('id', $notice->send_user_id)->first();
$age = 0;
if ($user->type == 'single') {
$profile = ProfileCourtship::where('user_id', $notice->send_user_id)->first();
if ($profile) {
if ($profile->birthday) {
$age = $this->getAge($profile->birthday);
}
$province = $profile->province;
} else {
$province = $notice->otherUser->wechat->province;
}
} else {
$profile = ProfileMarriage::where('user_id', $notice->send_user_id)->first();
if ($profile) {
if ($profile->birthday) {
$age = $this->getAge($profile->birthday);
}
$province = '未知';
} else {
$province = $notice->otherUser->wechat->province;
}
}
$user->wechat->avatar = $user->wechat->avatar2;
$user->age = $age;
$user->province = $province;
$wechat_qrcode = ProfileCourtship::where('user_id', $notice->send_user_id)->value('wechat_qrcode');
$user->wechat_qrcode = $wechat_qrcode;
$profile = ProfileCourtship::where('user_id', $notice->send_user_id)->first();
if (!empty($profile)) {
$wechat_qrcode = $profile->wechat_qrcode;
$wechat_qrcode_arr = json_decode($wechat_qrcode, true);
$qrcode = '';
if (is_array($wechat_qrcode_arr) && count($wechat_qrcode_arr)) {
$qrcode = $wechat_qrcode_arr[0];
} else {
$qrcode = '';
}
$user->wechat_id = $profile->wechat_id;
$user->qrcode = $qrcode;
}
return $this->success('ok', $user);
}
//* @desc: 关注用户
public function follow(Request $request, $id)
{
try {
$user = auth()->user();
if ($id == $user->id) {
return $this->failure('不能关注自己!');
}
$other_user = User::find($id);
if(!$other_user){
return $this->failure('用户信息错误!');
}
$is_followed = $user->isFollowing($other_user);
if ($is_followed) {
$user->unfollow($other_user);
} else {
$user->toggleFollow($other_user);
$notice = Notice::where('user_id', $id)->where('send_user_id', $user->id)->where('type', 'follow')->first();
$content = '用户' . $user->nickname . '关注了你喔!';
if ($notice) {
$data = [
'content' => $content,
'updated_at' => date('Y-m-d H:i:s'),
];
$this->userCon->updateNotice($notice, $data);
} else {
//计算年龄差
$user_age = 0;
if ($user->type == 'single' && !empty($user->profileCourtship)) {
$user_birthday = $user->profileCourtship->birthday;
}
if ($user->type == 'marriage' && !empty($user->profileMarriage)) {
$user_birthday = $user->profileMarriage->birthday;
}
if (!empty($user_birthday)) {
$user_age = CommonUtilsService::getAge($user_birthday);
}
$other_user_age = 0;
if ($other_user->type == 'single' && !empty($other_user->profileCourtship)) {
$other_user_birthday = $other_user->profileCourtship->birthday;
}
if ($other_user->type == 'marriage' && !empty($other_user->profileMarriage)) {
$other_user_birthday = $other_user->profileMarriage->birthday;
}
if (!empty($other_user_birthday)) {
$other_user_age = CommonUtilsService::getAge($other_user_birthday);
}
$age_diff = abs($other_user_age - $user_age);
if ($other_user->sex != $user->sex && $age_diff > 10) {
} else {
SendSubTemplateMsg::dispatch($type = 'follow', $user, $other_user)->onQueue('template_message');
SendIMPushMsg::dispatch($user->id, 'follow', $content, $user->id, $other_user->id, $user->userAvatar())->onQueue('love');
}
$this->sendNotice($id, $user->id, 'follow', $content);
}
}
//缓存用户
$other_user->updateCacheUser('fans_count');
$user->updateCacheUser('follow_count');
$is_followed = $user->isFollowing($other_user);
return $this->success('关注用户成功', compact('is_followed'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('关注用户失败,请稍后再试');
}
}
/**
* 取消好友
*/
public function deleteFirend(Request $request, $id)
{
$user = auth()->user();
$other_user = User::find($id);
//删除网易好友
$user->deleteIMFriend($other_user);
Linking::where('user_id', $user->id)->where('user_linking_id', $id)->delete();
Linking::where('user_id', $id)->where('user_linking_id', $user->id)->delete();
//删除聊天联系人
$user_id = auth()->id();
MessageLinkman::where(function ($sql) use ($user_id, $id) {
$sql->where(['user_id' => $user_id, 'other_user_id' => $id])
->orWhere(function ($query) use ($user_id, $id) {
$query->where(['user_id' => $id, 'other_user_id' => $user_id]);
});
})->delete();
$user->updateCacheUser('friend_count');
User::find($id)->updateCacheUser('friend_count');
//聊天记录标记
ChatMessage::where('other_user_id', $other_user->id)->where('user_id', $user->id)->update(['status'=>1]);
ChatMessage::where('other_user_id', $user->id)->where('user_id', $other_user->id)->update(['status'=>1]);
return $this->success('ok');
}
/**
* 拉入黑名单
* @param Request $request [description]
* @param [type] $id [description]
* @return [type] [description]
*/
public function blacklistFriend(Request $request, $id)
{
$this->userCon->blacklistFriend(auth()->id(), $id);
return $this->success('ok');
}
/**
* 黑名单列表
* @param Request $request [description]
* @return [type] [description]
*/
public function blacklist(Request $request)
{
$blacklist = $this->userCon->blacklist(auth()->id());
return $this->success('ok', $blacklist);
}
/**
* 移除黑名单
* @param Request $request [description]
* @param [type] $id [description]
* @return [type] [description]
*/
public function deleteBlacklist(Request $request, $id)
{
$blacklist = $this->userCon->deleteBlacklist($id);
return $this->success('ok');
}
/**
* 移除黑名单通过用户id
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function deleteBlacklistByUser(Request $request, $user_id)
{
$this->userCon->deleteBlacklistByUser($user_id);
return $this->success('ok');
}
/*
* @desc: 修改资料
*/
public function courtshipTextUpdateV2(Request $request)
{
$wechat = auth()->user()->wechat;
$user = auth()->user();
$id = $user->id;
$profile_id = ProfileCourtship::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileCourtship::find($profile_id);
} else {
$profile = new ProfileCourtship;
$profile->user_id = $id;
$user->type = 'single';
}
//行业
$industry = $request->industry ? $request->industry : '';
$user->industry = $industry;
$profile->sex = $request->sex ?: $profile->sex;
if (!$profile->sex) {
$data['focus'] = 'sex';
return $this->failure('请填写性别', $data);
}
$user->sex = $profile->sex;
$profile->birthday = $request->birthday ?: $profile->birthday;
if (!$profile->birthday) {
$data['focus'] = 'birthday';
return $this->failure('请填写生日', $data);
}
$profile->state = $request->state ?: $profile->state;
if (!$profile->state) {
$data['focus'] = 'state';
return $this->failure('请选择婚恋状态', $data);
}
$profile->stature = $request->stature ?: $profile->stature;
if (!$profile->stature) {
$data['focus'] = 'stature';
return $this->failure('请填写身高(厘米)', $data);
}
$profile->weight = $request->weight ?: $profile->weight;
if (!$profile->weight) {
$data['focus'] = 'weight';
return $this->failure('请填写体重(公斤)', $data);
}
$profile->province = $request->province ?: $profile->province;
$profile->city = $request->city ?: $profile->city;
$profile->dist = $request->dist ?: $profile->dist;
if ($request->province == '省' && $request->city == '市') {
$data['focus'] = 'province';
return $this->failure('请选择常居地', $data);
}
$profile->resident_type = $request->resident_type ?: $profile->resident_type;
if (!$profile->resident_type) {
$data['focus'] = 'resident_type';
return $this->failure('请选择成长环境', $data);
}
$profile->resident_province = $request->resident_province ?: $profile->resident_province;
$profile->resident_city = $request->resident_city ?: $profile->resident_city;
if ($request->resident_province == '省' && $request->resident_city == '市') {
$data['focus'] = 'resident_province';
return $this->failure('请选择成长地', $data);
}
$profile->resident_dist = $request->resident_dist ?: $profile->resident_dist;
$profile->belief = $request->belief ?: $profile->belief;
$user->belief = $request->belief ?: $user->belief;
$profile->degree = $request->degree ?: $profile->degree;
if (!$profile->degree) {
$data['focus'] = 'degree';
return $this->failure('请选择最高学历', $data);
}
$profile->graduate_school = $request->graduate_school ?: $profile->graduate_school;
if (!$profile->graduate_school) {
$data['focus'] = 'graduate_school';
return $this->failure('请填写毕业学校', $data);
}
$profile->company = $request->company ?: $profile->company;
if (!$profile->company) {
$data['focus'] = 'company';
return $this->failure('请选择工作单位', $data);
}
$profile->work_sort = $request->work_sort ?: $profile->work_sort;
if (!$profile->work_sort) {
$data['focus'] = 'work_sort';
return $this->failure('请选择单位性质', $data);
}
$user->industry = $request->industry ?: $user->industry;
if (!$user->industry) {
$data['focus'] = 'industry';
return $this->failure('请选择行业', $data);
}
$user->industry_sub = $request->industry_sub ?: $user->industry_sub;
if (!$user->industry_sub) {
$data['focus'] = 'industry_sub';
return $this->failure('请选择子行业', $data);
}
$profile->introduction = $request->introduction ?: $profile->introduction;
if (!$profile->introduction) {
$data['focus'] = 'introduction';
return $this->failure('请写一些个人介绍', $data);
}
$profile->ideal_mate = $request->ideal_mate ?: $profile->ideal_mate;
if (!$profile->ideal_mate) {
$data['focus'] = 'ideal_mate';
return $this->failure('请描绘一下你未来的理解对象', $data);
}
$profile->country = $request->input('country');
$profile->save();
$user->save();
$is_rank = $user->rank_id;
//成为24小时会员
$temp_member = TempMember::where('user_id', $id)->count();
if (empty($temp_member) && $user->rank_id == 0) {
$can_get_temp_member = 1;
} else {
$can_get_temp_member = 0;
}
return $this->success('update_courtship_text_ok', compact('is_rank', 'can_get_temp_member'));
}
public function courtshipTextUpdateV3(Request $request)
{
try {
$user = auth()->user();
$id = $user->id;
if ($user->type == 'single') {
$profile_id = ProfileCourtship::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileCourtship::find($profile_id);
} else {
$profile = new ProfileCourtship;
$profile->user_id = $id;
$user->type = 'single';
}
if ($request->has('type') && $request->type != $user->type) {
if ($user->type == 'single' || $user->type == 'loving') {
$user->type = $request->type;
}
}
if (($request->sex != $user->sex) && ($request->has('sex') && !empty($request->sex))) {
return $this->failure('不支持修改性别');
}
if ($request->has('sex') && !empty($request->sex) && $request->sex != $profile->sex) {
$profile->sex = $request->sex;
$user->sex = $request->sex;
}
if ($request->has('birthday') && !empty($request->birthday) && $request->birthday != $profile->birthday) {
$profile->birthday = $request->birthday;
}
if ($request->has('belief') && !empty($request->belief) && $request->belief != $profile->belief) {
$profile->belief = $request->belief;
$user->belief = $request->belief;
}
if ($request->has('state') && !empty($request->state) && $request->state != $profile->state) {
$profile->state = $request->state;
}
if ($request->input('stature') && !empty($request->stature) && $request->stature != $profile->stature) {
switch ($request->stature) {
case "140cm以下":
$profile->stature = 139;
break;
case "201cm以上":
$profile->stature = 202;
break;
default:
$profile->stature = $request->stature;
}
}
if ($request->input('weight') && !empty($request->weight) && $request->weight != $profile->weight) {
switch ($request->weight) {
case "40kg以下":
$profile->stature = 39;
break;
case "210kg以上":
$profile->stature = 211;
break;
default:
$profile->weight = $request->weight;
}
}
// if ($request->province == '省' && $request->city == '市') {
// return $this->failure('请选择常居地');
// }
// if ($request->has('province') && !empty($request->province) && $request->province != $profile->province) {
$profile->province = $request->province;
// }
// if ($request->has('city') && !empty($request->city) && $request->city != $profile->city) {
$profile->city = $request->city;
// }
// if ($request->has('dist') && !empty($request->dist) && $request->dist != $profile->dist) {
// $profile->dist = $request->dist;
// }
$resident_type = $request->input('resident_type', '城市');
if ($profile->resident_type != $resident_type) {
$profile->resident_type = $resident_type;
}
// if ($request->has('resident_province') && !empty($request->resident_province) && $request->resident_province != $profile->resident_province) {
// $profile->resident_province = $request->resident_province;
// }
// if ($request->resident_province == '省' && $request->resident_city == '市') {
// return $this->failure('请选择成长地');
// }
$profile->resident_province = $request->resident_city;
$profile->resident_city = $request->resident_dist;
// $profile->
// if ($request->has('resident_city') && !empty($request->resident_city) && $request->resident_city != $profile->resident_city) {
// $profile->resident_city = $request->resident_city;
// }
// if ($request->has('resident_dist') && !empty($request->resident_dist) && $request->resident_dist != $profile->resident_dist) {
// $profile->resident_dist = $request->resident_dist;
// }
if ($request->has('degree') && !empty($request->degree) && $request->degree != $profile->degree) {
$profile->degree = $request->degree;
}
if ($request->has('graduate_school') && !empty($request->graduate_school) && $request->graduate_school != $profile->graduate_school) {
$profile->graduate_school = $request->graduate_school;
}
if ($request->has('company') && !empty($request->company) && $request->company != $profile->company) {
$profile->company = $request->company;
}
if ($request->has('wechat_id') && !empty($request->wechat_id) && $request->wechat_id != $profile->wechat_id) {
$profile->wechat_id = $request->wechat_id;
}
if ($request->has('post') && !empty($request->post) && $request->post != $profile->post) {
$profile->post = $request->post;
}
if ($request->has('work_sort') && !empty($request->work_sort) && $request->work_sort != $profile->work_sort) {
$profile->work_sort = $request->work_sort;
}
if ($request->has('industry') && !empty($request->industry) && $request->industry != $user->industry) {
$user->industry = $request->industry;
}
if ($request->has('industry_sub') && !empty($request->industry_sub) && $request->industry_sub != $user->industry_sub) {
$user->industry_sub = $request->industry_sub;
}
if ($request->has('introduction') && !empty($request->introduction) && $request->introduction != $profile->introduction) {
$profile->introduction = $request->introduction;
}
if ($request->has('ideal_mate') && !empty($request->ideal_mate) && $request->ideal_mate != $profile->ideal_mate) {
$profile->ideal_mate = $request->ideal_mate;
}
if ($request->input('interest_hobby') && $request->interest_hobby != $profile->interest_hobby) {
$profile->interest_hobby = $request->interest_hobby;
}
if ($request->has('country') && !empty($request->country) && $request->country != $profile->country) {
$profile->country = $request->country;
}
if ($request->input('max_age') && $request->max_age != $profile->max_age) {
$profile->max_age = $request->max_age;
}
if ($request->input('min_age') && $request->min_age != $profile->min_age) {
$profile->min_age = $request->min_age;
}
if ($request->input('name') && $request->name != $user->name) {
$user->name = $request->input('name');
}
if ($request->input('photo') && $request->photo != $user->wechat->avatar) {
$user->wechat->avatar = $request->photo;
$user->wechat->save();
}
$temp_member = TempMember::where('user_id', $id)->count();
if (empty($temp_member) && $user->rank_id == 0) {
$can_get_temp_member = 1;
} else {
$can_get_temp_member = 0;
}
if ($request->has('work_province') && $request->work_province != $profile->work_province) {
$profile->work_province = $request->work_province;
}
if ($request->has('work_city') && $request->work_city != $profile->work_city) {
$profile->work_city = $request->work_city;
}
if ($request->has('work_dist') && $request->work_dist != $profile->work_dist) {
$profile->work_dist = $request->work_dist;
}
if ($request->has('is_smoke') && $request->is_smoke != $profile->is_smoke && is_numeric($request->is_smoke)) {
$profile->is_smoke = $request->is_smoke;
}
if ($request->has('is_drink') && $request->is_drink != $profile->is_drink && is_numeric($request->is_drink)) {
$profile->is_drink = $request->is_drink;
}
if ($request->has('marry_time') && $request->marry_time != $profile->marry_time && is_numeric($request->marry_time)) {
$profile->marry_time = $request->marry_time;
}
if ($request->has('have_child') && $request->have_child != $profile->have_child && is_numeric($request->have_child)) {
$profile->have_child = $request->have_child;
}
if ($request->has('want_child') && $request->want_child != $profile->want_child && is_numeric($request->want_child)) {
$profile->want_child = $request->want_child;
}
if ($request->has('live_status') && $request->live_status != $profile->live_status && is_numeric($request->live_status)) {
$profile->live_status = $request->live_status;
}
if ($request->has('car_status') && $request->car_status != $profile->car_status && is_numeric($request->car_status)) {
$profile->car_status = $request->car_status;
}
//文本内容检测;
$result = \CommonUtilsService::textContentCecurity([$request->input('nickname'), $request->input('name'), $request->input('graduate_school'), $request->input('company'), $request->input('introduction'), $request->input('ideal_mate'), $request->input('interest_hobby')]);
if ($result && $result['result']) {
return $this->failure('您填写的内容【' . $result['context'] . "】:" . $result['result'] . ",请重新输入");
}
$profile->save();
$user->save();
//上传图片
$photos = $request->input('photos', []);
if (count($photos)) {
foreach ($photos as $photo) {
if (empty($photo)) {
continue;
}
$photo_obj = new ProfilePhoto();
$photo_obj->photo = $photo;
$photo_obj->user_id = auth()->id();
$photo_obj->dateline = date('Y-m-d');
$photo_obj->save();
}
}
return $this->success('update_courtship_text_ok', compact('can_get_temp_member'));
} else {
$profile_id = ProfileMarriage::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileMarriage::find($profile_id);
} else {
$profile = new ProfileMarriage;
$profile->user_id = $id;
}
if ($request->has('wechat_id') && !empty($request->wechat_id) && $request->wechat_id != $profile->wechat_id) {
$profile->wechat_id = $request->wechat_id;
}
$profile->save();
return $this->success('update_courtship_text_ok');
}
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('修改资料失败,请稍后再试');
}
}
/**
* 修改六步推荐
*/
public function updateRecommendProfile(Request $request)
{
$user = auth()->user();
if ($user->type == 'single') {
$profile = $user->profileCourtship;
$is_change = 0;
if ($request->input('belief') && $request->belief != $profile->belief) {
$profile->belief = $request->belief;
$user->belief = $request->belief;
$is_change = 1;
}
if ($request->input('max_age')) {
$max_age = $request->input('max_age');
$max_birthday = date('Y-m-d', strtotime('-' . $max_age . ' year'));
$profile->max_age = $max_birthday;
$is_change = 1;
}
if ($request->input('min_age')) {
$min_age = $request->input('min_age');
$min_birthday = date('Y-m-d', strtotime('-' . $min_age . ' year'));
$profile->min_age = $min_birthday;
$is_change = 1;
}
if ($request->input('birthday') && $request->birthday != $profile->birthday) {
$profile->birthday = $request->birthday;
$is_change = 1;
}
if ($request->input('city') && $request->city != $profile->city) {
$profile->city = $request->city;
$is_change = 1;
}
if ($request->input('province') && $request->province != $profile->province) {
$profile->province = $request->province;
$is_change = 1;
}
if ($request->input('country') && $request->country != $profile->country) {
$profile->country = $request->country;
$is_change = 1;
}
if ($request->input('sex') && $request->sex != $user->sex) {
$user->sex = $request->sex;
$profile->sex = $request->sex;
$is_change = 1;
}
if ($request->input('state') && $request->state != $profile->state) {
$profile->state = $request->state;
$is_change = 1;
}
$user->save();
$profile->save();
//修改推荐
if ($is_change) {
$this->changeMatchingRate($user, $profile);
}
}
return $this->success('ok');
}
public function changeMatchingRate($user, $profile)
{
//删除所有的记录
MatchingRate::where('user_id', $user->id)->delete();
$other_users = User::where('type', 'single')->where('hidden_profile', '<>', 'ALLSEX');
//1.信仰
$other_users = $other_users->where('belief', $user->belief);
//性别
$other_users = $other_users->where('sex', '<>', 0)->where('sex', '<>', $user->sex);
//年龄限制内的
$other_users = $other_users->with('profileCourtship')->whereHas('profileCourtship', function ($sql) use ($profile) {
$sql->where('birthday', '>', $profile->max_age)->where('birthday', '<', $profile->min_age);
});
//年龄
$other_users = $other_users->get();
$data = [];
foreach ($other_users as $other_user) {
$residence_province = 0;
if ($other_user->profileCourtship->province == $profile->province) {
$residence_province = 1;
}
$residence_city = 0;
if ($other_user->profileCourtship->province == $profile->province && $other_user->profileCourtship->city == $profile->city) {
$residence_city = 1;
}
$user_data = [];
$user_data['user_id'] = $user->id;
$user_data['other_user_id'] = $other_user->id;
$user_data['belief'] = 10;
$user_data['age'] = 3;
$user_data['residence_province'] = 1;
$user_data['weight'] = 20;
$user_data['created_at'] = date('Y-m-d H:i:s');
$user_data['updated_at'] = date('Y-m-d H:i:s');
$data[] = $user_data;
}
MatchingRate::insert($data);
}
/*
* @desc: 修改资料
*/
public function marriageUpdateV2(Request $request)
{
$user = auth()->user();
$id = $user->id;
$profile_id = ProfileMarriage::where('user_id', $id)->value('id');
if ($profile_id) {
$profile = ProfileMarriage::find($profile_id);
} else {
$profile = new ProfileMarriage;
$profile->user_id = $id;
$user->type = 'marriage';
}
//保存真实姓名
// $name = $request->name?:$user->name;
// if(!$name){
// $data['focus'] = 'name';
// return $this->failure('请填写真实姓名', $data);
// }
//行业
$industry = $request->industry ?: $user->industry;
$belief = $request->input('belief', '基督教');
$profile->belief = $belief;
$user->belief = $belief;
// $user->name = $name;
$user->industry = $industry;
$profile->sex = $request->sex ?: $profile->sex;
if (!$profile->sex) {
$data['focus'] = 'sex';
return $this->failure('请填写性别', $data);
}
$user->sex = $profile->sex;
$profile->birthday = $request->birthday ?: $profile->birthday;
if (!$profile->birthday) {
$data['focus'] = 'birthday';
return $this->failure('请填写出生年月日', $data);
}
// $profile->province=$request->province?:$profile->province;
// if(!$profile->province){
// $data['focus'] = 'province';
// return $this->failure('请选择居住省份', $data);
// }
// $profile->city=$request->city?:$profile->city;
// if(!$profile->city){
// $data['focus'] = 'city';
// return $this->failure('请选择居住城市', $data);
// }
$profile->company = $request->company ?: $profile->company;
if (!$profile->company) {
$data['focus'] = 'company';
return $this->failure('请填写工作单位', $data);
}
$user->industry = $request->industry ?: $user->industry;
if (!$user->industry) {
$data['focus'] = 'industry';
return $this->failure('请选择行业', $data);
}
$user->industry_sub = $request->industry_sub ?: $user->industry_sub;
if (!$user->industry_sub) {
$data['focus'] = 'industry_sub';
return $this->failure('请选择子行业', $data);
}
$profile->slogan = $request->slogan ?: ($profile->slogan ?: '为单身的幸福生活服务!');
$profile->save();
$user->save();
// $this->checkLinkingRequest($id);
return $this->success('update_marriage_ok', $profile);
}
/**
* 标签信息
*/
public function labels(Request $request)
{
$page = $request->page??1;
$sex = $request->sex??2;
// Log::info($request->header());
// Log::info($request->all());
$result = Label::select('id','label')->where('sex',$sex)->paginate(9);
return $this->success('ok',$result);
}
/**
* 给用户写上标签
*/
public function post_user_label(Request $request)
{
$user = auth()->user();
$other_user_id = $request->other_user_id;
//当前用户是否打开夸夸我功能
$info = UserInfo::where('user_id',$request->user_id)->first();
if($info && $info->label_notice == 0) return $this->failure('对方已关闭夸夸功能');
$labels = $request['labels'];
$labels = json_encode($labels);
$start = Carbon::today();
$end = Carbon::tomorrow();
$exist = LabelHistory::where('user_id',$user->id)->where('labeled_user_id',$other_user_id)->wherebetween('created_at',[$start,$end])->count();
if($exist) return $this->success('今天你已经夸过Ta了明天再夸吧~');
if($labels){
$LabelHistory = new LabelHistory;
$LabelHistory->user_id = $user->id;
$LabelHistory->labeled_user_id = $other_user_id;
$LabelHistory->content = $labels;
$LabelHistory->save();
}
$url = $this->getMiniUrl($request->other_user_id);
$url = \CommonUtilsService::shortUrl($url);
$message = '刚刚有人夸夸了你,点击链接(' . $url['url'] . ')快来看看吧';
$send_user = User::where('id', $other_user_id)->first();
//关闭资料 介绍人不发
if($send_user->hidden_profile != 'ALLSEX' || $send_user->type != 'single'){
$log = UserMessageSetting::where(['user_id'=>$send_user->id, 'type'=>'label'])->first();
if (empty($log)) $this->sentMessage($send_user->mobile,$message);
}
$key = 'get_user_label'.$other_user_id;
cache::forget($key);
$LabelHistory->content = $request['labels'];
$LabelHistory->avatar = $LabelHistory->user->avatar;
unset($LabelHistory->user);
return $this->success('评价成功',$LabelHistory);
}
public function get_user_label(Request $request)
{
$key = 'get_user_label'.$request->user_id;
//当前用户是否打开夸夸我功能
$info = UserInfo::where('user_id',$request->user_id)->first();
if($info && $info->label_notice == 0) return $this->success('ok',[]);
$result = cache::remember($key,5,function () use($request){
$user_id = $request->user_id;
$result = LabelHistory::select('user_id','labeled_user_id','content')->where('labeled_user_id', $user_id)->orderBy('id','desc')->get();
foreach ($result as $key => $value) {
$value->avatar = $value->user->avatar??null;
$value->content = json_decode($value->content,true);
unset($value->user);
}
return $result;
});
return $this->success('ok',$result);
}
/**
* 信息
*/
public function profile(Request $request)
{
$user = auth()->user();
$wechat = Wechat::where('user_id', $user->id)->first();
if ($user->type == 'single') {
$profile = ProfileCourtship::with('salary')->where('user_id', $user->id)->first();
if (empty($profile)) {
$profile = new ProfileCourtship;
$profile->user_id = $user->id;
$profile->resident_type = '农村';
if ($wechat && $wechat->gender) {
$user->sex = $wechat->gender;
$profile->sex = $wechat->gender;
}
$profile->save();
$user->save();
switch ($profile->stature) {
case 139:
$profile->stature = '140cm以下';
break;
case 202:
$profile->stature = '201cm以上';
break;
default:
$profile->stature .= 'cm';
}
switch ($profile->weight) {
case 39:
$profile->weight = '40kg以下';
break;
case 211:
$profile->weight = '210kg以上';
break;
default:
$profile->weight .= 'kg';
}
return $this->success('ok', $profile);
}
if (empty($profile->photos)) {
$profile->photos = [];
} else {
$profile->photos = json_decode($profile->photos, true);
}
if (empty($profile->graduate_photos)) {
$profile->graduate_photos = [];
} else {
$profile->graduate_photos = json_decode($profile->graduate_photos, true);
}
if (empty($profile->identification_photos)) {
$profile->identification_photos = [];
} else {
$profile->identification_photos = json_decode($profile->identification_photos, true);
}
if (empty($profile->other_photos)) {
$profile->other_photos = [];
} else {
$profile->other_photos = json_decode($profile->other_photos, true);
}
if (empty($profile->wechat_qrcode)) {
$profile->wechat_qrcode = [];
} else {
$profile->wechat_qrcode = json_decode($profile->wechat_qrcode, true);
}
$profile->industry = $user->industry;
$profile->industry_sub = $user->industry_sub;
//生活照
$photos = $this->userCon->lifePhotos($user->id, 0, 'desc');
$profile->photos = $photos;
} else {
$profile = ProfileMarriage::where('user_id', $user->id)->first();
if (empty($profile)) {
$profile = new ProfileMarriage();
$profile->user_id = $user->id;
$single_profile = ProfileCourtship::where('user_id', $user->id)->first();
if (!empty($single_profile)) {
$profile->sex = $single_profile->sex;
$profile->birthday = $single_profile->birthday;
$profile->belief = $single_profile->belief;
$user->belief = $profile->belief;
$profile->company = $single_profile->company;
}
$profile->save();
$user->save();
}
$profile->industry = $user->industry;
$profile->industry_sub = $user->industry_sub;
}
if (empty($wechat)) {
if ($user->sex == 1) {
$avatar = 'http://images.ufutx.com/201811/12/0e8b72aae6fa640d9e73ed312edeebf3.png';
} else {
$avatar = 'http://images.ufutx.com/201811/12/dddd79aa2c2fc6a6f35e641f6b8fb8f5.png';
}
} else {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
}
$profile->avatar = $avatar;
$profile->nickname = $user->nickname;
$profile->name = $user->name;
$profile->is_approved = $user->is_approved;
switch ($profile->stature) {
case 139:
$profile->stature = '140cm以下';
break;
case 202:
$profile->stature = '201以上';
break;
default:
$profile->stature .= 'cm';
}
switch ($profile->weight) {
case 39:
$profile->weight = '40kg以下';
break;
case 211:
$profile->weight = '210kg以上';
break;
default:
$profile->weight .= 'kg';
}
return $this->success('ok', $profile);
}
/**
* 个人资料
*/
public function profileV2(Request $request)
{
$user = auth()->user();
$wechat = $user->wechat;
if ($user->type == 'single') {
$profile = $user->profileCourtship;
if (empty($profile)) {
$profile = new ProfileCourtship;
$profile->user_id = $user->id;
$profile->sex = $user->sex ?: $wechat->gender;
$profile->save();
}
} else {
$profile = $user->profileMarriage;
if (empty($profile)) {
$profile = new ProfileMarriage;
$profile->user_id = $user->id;
$profile->sex = $user->sex ?: $wechat->gender;
$profile->save();
}
}
$profile->name = $user->name;
$profile->nickname = $user->nickname;
$profile->is_approved = $user->is_approved;
$profile->is_real_approved = $user->is_real_approved;
$profile->is_educate_approved = $user->is_educate_approved;
$profile->industry = $user->industry;
$profile->industry_sub = $user->industry_sub;
//头像是否合格
$profile->is_photo_audited = $user->is_photo_audited;
$profile->photo = $user->photo;
//生活照
$photos = ProfilePhoto::where('user_id', $user->id)->get();
// foreach ($photos as $key => $value) {
// $value->photo = explode('?', $value->photo);
// }
$profile->photos = $photos;
//年龄
$age = \CommonUtilsService::getAge($profile->birthday);
$profile->age = $age;
//完整度
$result = $this->userCon->profileIntegrity($profile, $user);
$profile->profile_count = $result['count'];
$profile->profile_total_count = $result['total_count'];
//是否可以领取
$can_get_daily_rank = ($user->canGetDailySuperRank()) ? 0 : 1;
$profile->can_get_daily_rank = $can_get_daily_rank;
//是否已经领取
$has_get_daily_rank = TempMember::where('user_id', $user->id)->count() ? 1 : 0;
$profile->has_get_daily_rank = $has_get_daily_rank;
$profile->introduction_verifyResultCode = 1;
$profile->ideal_mate_verifyResultCode = 1;
if ($user->type == 'single') {
$mate_conditon = json_decode($profile->mate_conditon,true);
unset($mate_conditon['location']);
$profile->mate_conditon = $mate_conditon;
$introductionVerifyResultCode__key = $this->userCon->KYE_IVRC . $user->id;
$ideal_mateVerifyResultCode_key = $this->userCon->KYE_IMVRC . $user->id;
$interest_hobbyVerifyResultCode_key = $this->userCon->KYE_IMPHO . $user->id;
$profile->introduction_verifyResultCode = $this->userCon->geTextVerifyCode($introductionVerifyResultCode__key,$profile->introduction);
$profile->ideal_mate_verifyResultCode = $this->userCon->geTextVerifyCode($ideal_mateVerifyResultCode_key,$profile->ideal_mate);
//兴趣爱好
$profile->interest_hobby_verifyResultCode = $this->userCon->geTextVerifyCode($interest_hobbyVerifyResultCode_key,$profile->interest_hobby);
//是否被标记
$profile->tag_status = WrongInfoHistories::where('user_id',$user->id)->where('type','tag')->where('status',1)->count();
}
return $this->success('ok', $profile);
}
/**
* 修改资料
*/
public function updateProfileV2(Request $request)
{
$ex = [];
$old_data = [];
$user = auth()->user();
//是否更新H5的昵称
$is_replenishUserOtherInfo = false;
$await_checkoutTextArray = [];
if ($request->input('nickname') && $request->nickname != $user->nickname) {
$old_data['nickname'] = $user->nickname;
$ex['nickname'] = $request->nickname;
$user->nickname = $request->nickname;
$await_checkoutTextArray[] = $request->nickname;
$is_replenishUserOtherInfo = true;
if (strpos($request->nickname , 'frank' ) !== false || strpos($request->nickname , 'Frank' ) !== false) {
$data['touser'] = 'oPC_2vneOWpQbicNZQAUCxuwZ4mw';
$data['template_id'] = config('wechat.tpls.error_notice');
$data['url'] = '';
$data['data'] = [
'first' => '可疑用户提示',
'keyword1' => '用户['.$user->nickname.']id--'.$user->id,
'keyword2' => '福恋',
'keyword3' => date('Y-m-d H:i:s'),
'remark' => '',
];
SendTemplateMsg::dispatch($data)->onQueue('error_email');
}
}
if ($request->input('industry') && $request->industry != $user->industry) {
$user->industry = $request->industry;
$old_data['industry'] = $user->industry;
$ex['industry'] = $request->industry;
}
if ($request->input('industry_sub') && $request->industry_sub != $user->industry_sub) {
if ($request->industry == '其他行业' && $request->industry_sub != '其他行业') {
$industry_sub = $request->industry;
//自定义职位 审核记录
(new Audit())->createAuditData(
$user->id,
Audit::TYPE_INDUSTRY_SUB,
['industry_sub' => $request->industry_sub]
);
} else {
$industry_sub = $request->industry_sub;
}
$user->industry_sub = $industry_sub;
$old_data['industry_sub'] = $user->industry_sub;
$ex['industry_sub'] = $industry_sub;
}
if ($request->input('type') && $request->input('type') != $user->type) {
$user->type = $request->type;
}
if ($user->type == 'single') {
$profile = $user->profileCourtship;
if (empty($profile)) {
$profile = new ProfileCourtship;
$profile->user_id = $user->id;
}
if ($request->input('stature') && $request->stature != $profile->stature) {
$profile->stature = $request->stature;
$old_data['stature'] = $user->stature;
$ex['stature'] = $request->stature;
}
if ($request->input('weight') && $request->weight != $profile->weight) {
$profile->weight = $request->weight;
$old_data['weight'] = $user->weight;
$ex['weight'] = $request->weight;
}
if ($request->input('province') && $request->province != $profile->province) {
$profile->province = $request->province;
$old_data['province'] = $user->province;
$ex['province'] = $request->province;
}
if ($request->input('city') && $request->city != $profile->city) {
$profile->city = $request->city;
$old_data['city'] = $user->city;
$ex['city'] = $request->city;
}
if ($request->input('state') && $request->state != $profile->state) {
$profile->state = $request->state;
$user->type = $request->state == '已婚' ? "marriage" : "single";
$old_data['state'] = $profile->state;
$ex['state'] = $request->state;
}
if ($request->input('degree') && $request->degree != $profile->degree) {
// $profile->degree = $request->degree;
$old_data['degree'] = $user->degree;
$ex['degree'] = $request->degree;
}
if ($request->input('graduate_school') && $request->graduate_school != $profile->graduate_school) {
// $profile->graduate_school = $request->graduate_school;
$old_data['graduate_school'] = $user->graduate_school;
$ex['graduate_school'] = $request->graduate_school;
$await_checkoutTextArray[] = $request->graduate_school;
}
$is_educate_approved = DB::table('users')->where('id', $user->id)->value('is_educate_approved');
if ($request->input('educate_photo') && $is_educate_approved != 2) {
// if ($user->is_real_approved != 1) return $this->failure("认证失败,请先完成真人认证!");
//毕业证书
// $profile->educate_photo = $request->educate_photo;
$profile->edc_type = 0;
$extend = [
'degree' => $request->degree,
'graduate_school' => $request->graduate_school,
'educate_photo' => $request->educate_photo,
'chsi_code' => $request->chsi_code
];
if($is_educate_approved == 1){
//升级学历
$user->upgradeEducation($extend);
}else{
//创建认证记录
$user->updateApproveInfo('educate', 0,null,$extend);
}
} else if ($request->input('chsi_code') && $is_educate_approved != 2) {
if ($user->is_real_approved != 1) return $this->failure("认证失败,请先完成真人认证!");
//添加学信网CODE
// $profile->chsi_code = $request->chsi_code;
$extend = [
'degree' => $request->degree,
'graduate_school' => $request->graduate_school,
'educate_photo' => $request->educate_photo,
'chsi_code' => $request->chsi_code
];
$profile->edc_type = 1;
if($is_educate_approved == 1){
//升级学历
$user->upgradeEducation($extend);
}else{
//创建认证记录
$user->updateApproveInfo('educate', 0,null,$extend);
}
}
if ($request->input('resident_province') && $request->resident_province != $profile->resident_province) {
$profile->resident_province = $request->resident_province;
$old_data['resident_province'] = $user->resident_province;
$ex['resident_province'] = $request->resident_province;
}
if ($request->input('resident_city') && $request->resident_city != $profile->resident_city) {
$profile->resident_city = $request->resident_city;
$old_data['resident_city'] = $user->resident_city;
$ex['resident_city'] = $request->resident_cityresident_cityresident_city;
}
if ($request->input('introduction') && $request->introduction != $profile->introduction) {
$profile->introduction = $request->introduction;
$old_data['introduction'] = $user->introduction;
$ex['introduction'] = $request->introduction;
$await_checkoutTextArray[] = $request->introduction;
}
if ($request->input('ideal_mate') && $request->ideal_mate != $profile->ideal_mate) {
$profile->ideal_mate = $request->ideal_mate;
$old_data['ideal_mate'] = $user->ideal_mate;
$ex['ideal_mate'] = $request->ideal_mate;
$await_checkoutTextArray[] = $request->ideal_mate;
}
if ($request->input('mate_conditon') && $request->mate_conditon != json_decode($profile->mate_conditon,true)) {
$profile->mate_conditon = json_encode($request->mate_conditon);
$old_data['mate_conditon'] = $user->mate_conditon;
$ex['mate_conditon'] = $request->mate_conditon;
$await_checkoutTextArray[] = $request->mate_conditon;
$mate_conditon = $request->mate_conditon;
if (strpos($mate_conditon['age'], 'undefined') !== false) {
return $this->failure('请重新选择年龄范围');
}
if (strpos($mate_conditon['stature'], 'undefined') !== false) {
return $this->failure('请重新选择身高范围');
}
if ($mate_conditon['age'] != '年龄不限') {
$age_arr = explode('-', $mate_conditon['age']);
$profile->min_age = CommonUtilsService::ageToDate($age_arr[0]);
$profile->max_age = CommonUtilsService::ageToDate(explode('岁', $age_arr[1])[0]);
}
if ($mate_conditon['stature'] != '身高不限') {
$stature_arr = explode('-', $mate_conditon['stature']);
$profile->min_height = $stature_arr[0];
$profile->max_height = explode('cm', $stature_arr[1])[0];;
}
}
// 我希望Ta所在的城市:城市字符串
$city_list_claim = $request->input('city_list_claim');
$city_claim = $request->input('city_claim');
if($city_claim == 3){
if ($city_list_claim && $city_list_claim != $profile->city_list_claim){
$profile->city_list_claim = $city_list_claim;
}
}else if($request->city_claim == 1){
$profile->city_list_claim = '';
}
if ($request->input('interest_hobby') && $request->interest_hobby != $profile->interest_hobby) {
$profile->interest_hobby = $request->interest_hobby;
$old_data['interest_hobby'] = $user->interest_hobby;
$ex['interest_hobby'] = $request->interest_hobby;
$await_checkoutTextArray[] = $request->interest_hobby;
}
if ($request->input('income') && $request->income != $profile->income) {
$profile->income = $request->income;
$old_data['income'] = $user->income;
$ex['income'] = $request->income;
}
} else {
$profile = $user->profileMarriage;
if (empty($profile)) {
$profile = new ProfileMarriage;
$profile->user_id = $user->id;
}
if ($request->input('slogan') && $request->slogan != $profile->slogan) {
$profile->slogan = $request->slogan;
}
}
if ($request->has('wechat_id') && !empty($request->wechat_id) && $request->wechat_id != $profile->wechat_id) {
$profile->wechat_id = $request->wechat_id;
$old_data['wechat_id'] = $user->wechat_id;
$ex['wechat_id'] = $request->wechat_id;
}
if ($request->input('birthday') && $request->birthday != $profile->birthday) {
//检查是否已经认证并且出生日期是否对应
if ($this->checkProfileBirthday($user, $request->birthday)) {
return $this->failure('修改出生日期失败,和身份证信息不符');
}
$profile->birthday = $request->birthday;
$old_data['birthday'] = $user->birthday;
$ex['birthday'] = $request->birthday;
}
if ($request->input('belief') && $request->belief != $user->belief) {
$user->belief = $request->belief;
$profile->belief = $request->belief;
//删除每日推荐七位信息
$this->userCon->deleteRecommendUsers();
$old_data['belief'] = $user->belief;
$ex['belief'] = $request->belief;
}
if ($request->input('sex') && $request->sex != $user->sex) {
$user->sex = $request->sex;
$profile->sex = $request->sex;
}
//职位
if ($request->input('post') && $request->post != $profile->post) {
$profile->post = $request->post;
}
//期望多久结婚
if ($request->input('marry_by_time') && $request->marry_by_time != $profile->marry_by_time) {
$profile->marry_by_time = $request->marry_by_time;
}
//修改完善分数
$result = $this->userCon->profileIntegrity($profile, $user);
$user->info_complete_score = $result['count'];
try {
//敏感词汇过滤
$result = \CommonUtilsService::checkoutTextArray($await_checkoutTextArray);
if($result['code'] == 1){
return $this->failure($result['cause']);
}
$introductionVerifyResultCode__key = $this->userCon->KYE_IVRC . $user->id;
$ideal_mateVerifyResultCode_key = $this->userCon->KYE_IMVRC . $user->id;
$interest_hobbyVerifyResultCode_key = $this->userCon->KYE_IMPHO . $user->id;
Cache::forget($introductionVerifyResultCode__key);
Cache::forget($ideal_mateVerifyResultCode_key);
Cache::forget($interest_hobbyVerifyResultCode_key);
\DB::beginTransaction();
$profile->save();
$user->save();
$user->addProfileChangeLog($old_data, $ex);
if($is_replenishUserOtherInfo){
$this->userCon->replenishUserOtherInfo($user->id,$user->nickname);
}
SendProfileCoin::dispatch($user, $type = 'profile')->onQueue('love');
\DB::commit();
$user->cacheUser();
//完善基本资料赠送福币
return $this->success('ok');
} catch (Exception $e) {
\DB::rollBack();
$this->getError($e);
return $this->failure('修改资料失败,请重试');
}
}
//完善资料
public function updateUserProfileV2(Request $request){
$userinfo = $this->getMyUserinfo();
$belief = $request->input('belief');
$sex= $request->input('sex');
$nickname= $request->input('nickname');
$state= $request->input('state');
$type = $this->getFeelingStateType($state);
$birthday = $request->input('birthday');
$city = $request->input('city');
$province = $request->input('province');
$photo = $request->input('photo');
if(!$userinfo->mobile){
return $this->failure('出了一点问题,请联系管理员');
}
if(!$belief||!$sex||!$nickname||!$state||!$birthday||!$city||!$province||!$photo){
return $this->failure('出了些问题。缺参');
}
try{
\DB::beginTransaction();
$photoinfo = $this->getPhotoInfo($photo,$sex);
$is_photo_audited = -1;
if(!$photoinfo){
return $this->failure('头像异常');
}
if ($photoinfo['code'] == -1) {
return $this->failure('头像异常');
}else if ($photoinfo['code'] == 1){
$is_photo_audited = 1;
}else{
$is_photo_audited = -1;
}
$r = $this->userCon->replenishPhotoInfo($userinfo, $photo, $birthday, $photoinfo['face_list']);
if($r){
$userinfo->circle_avatar = null;
$userinfo->my_share = null;
$userinfo->home_share = null;
if ($photoinfo['code'] == 0) {
$userinfo->face_score = 0;
}
}
$userinfo->belief = $belief;
$userinfo->sex = $sex;
$userinfo->type = $type;
$userinfo->nickname = $nickname;
$userinfo->photo = $photo;
$userinfo->app_avatar = $photo;
$userinfo->save();
if ($type === 'marriage') {
$profile = ProfileMarriage::firstOrCreate(['user_id' => $userinfo->id]);
} else {
$profile = ProfileCourtship::firstOrCreate(['user_id' => $userinfo->id]);
}
$profile->belief = $belief;
$profile->sex = $sex;
$profile->birthday = $birthday;
$profile->state = $state;
$profile->city = $city;
$profile->province = $province;
$profile->save();
\DB::commit();
//获取token
$token = $userinfo->createToken($userinfo->mobile)->accessToken;
return $this->success('完善资料成功',['user'=>$userinfo,'token'=>$token]);
} catch (\Exception $e) {
\DB::rollBack();
return $this->failure('完善资料失败');
}
}
//获取头像信息
private function getPhotoInfo($photo, $user_sex)
{
$fun_result = ['code' => -1, 'face_list' => []];
try {
if (empty($photo)) {
return $fun_result;
}
//内容安全-图片
$result = \CommonUtilsService::imageContentCecurity([$photo]);
if ($result && isset($result['result']) && $result['result']) {
return $fun_result;
}
//人脸识别
$result = $this->userCon->faceDelectBaiDu($photo);
$res = $this->userCon->checkPhotoResultV2($result,$user_sex);
if (empty($res)) {
return ['code' => -1, 'face_list' => []];
} else if ($res['code'] == 1) {
return ['code' => 1, 'face_list' => $result->result->face_list];
} else if ($res['code'] == 0) {
return ['code' => 0, 'face_list' => []];
} else {
return ['code' => -1, 'face_list' => []];
}
return $fun_result;
} catch (\Exception $e) {
$this->getError($e);
return $fun_result;
}
}
//判断情感状态 返回计算机识别得情感状态
private function getFeelingStateType($state)
{
if ($state == '未婚' || $state == '离异' || $state == '丧偶') {
return 'single';
} else if ($state == '已婚' || $state == '恋爱中') {
return 'marriage';
}else{
return 'single';
}
}
public function checkProfileBirthday($user, $req_birthday)
{
//拿到身份证的出生日期
$result = \CommonUtilsService::checkCardBirhday($user->card_num);
if ($result['error'] != 2) {
return false;
}
$birthday = $result['tdate'];
if ($user->is_approved && $birthday != $req_birthday) {
return true;
}
}
public function updateProfileV3(Request $request)
{
$user = auth()->user();
if (empty($request->input('nickname'))) {
return $this->failure('请输入昵称');
}
if (empty($request->input('industry')) || empty($request->input('industry_sub'))) {
return $this->failure('请选择行业');
}
$user->industry = $request->industry;
$user->industry_sub = $request->industry_sub;
if ($user->type == 'single') {
$profile = $user->profileCourtship;
if (empty($profile)) {
$profile = new ProfileCourtship;
$profile->user_id = $user->id;
$profile->sex = $user->sex;
}
if (empty($request->input('stature'))) {
return $this->failure('请现在身高');
}
$profile->stature = $request->stature;
if (empty($request->input('weight'))) {
return $this->failure('请输入体重');
}
$profile->weight = $request->weight;
if (empty($request->input('province')) || empty($request->input('city'))) {
return $this->failure('请输入常居地');
}
$profile->province = $request->province;
$profile->city = $request->city;
if (empty($request->input('state'))) {
return $this->failure('请选择单身状态');
}
$profile->state = $request->state;
if (empty($request->input('degree'))) {
return $this->failure('请输入最高学历');
}
$profile->degree = $request->degree;
if (empty($request->input('graduate_school'))) {
return $this->failure('请输入毕业学校');
}
$profile->graduate_school = $request->graduate_school;
if (empty($request->input('resident_province')) || empty($request->input('resident_city'))) {
return $this->failure('请选择成长地');
}
$profile->resident_province = $request->resident_province;
$profile->resident_city = $request->resident_city;
if ($request->input('introduction') && $request->introduction != $profile->introduction) {
$profile->introduction = $request->introduction;
}
if ($request->input('ideal_mate') && $request->ideal_mate != $profile->ideal_mate) {
$profile->ideal_mate = $request->ideal_mate;
}
if ($request->input('interest_hobby') && $request->interest_hobby != $profile->interest_hobby) {
$profile->interest_hobby = $request->interest_hobby;
}
if ($request->input('income') && $request->income != $profile->income) {
$profile->income = $request->income;
}
} else {
$profile = $user->profileMarriage;
if (empty($profile)) {
$profile = new ProfileMarriage;
$profile->user_id = $user->id;
$profile->sex = $user->sex;
}
if ($request->input('slogan') && $request->slogan != $profile->slogan) {
$profile->slogan = $request->slogan;
}
}
if ($request->has('wechat_id') && !empty($request->wechat_id) && $request->wechat_id != $profile->wechat_id) {
$profile->wechat_id = $request->wechat_id;
}
if (empty($request->input('birthday'))) {
return $this->failure('请选择出生日期');
}
$profile->birthday = $request->birthday;
if (empty($request->input('belief'))) {
return $this->failure('请选择信仰');
}
$user->belief = $request->belief;
$profile->belief = $request->belief;
try {
\DB::beginTransaction();
$profile->save();
$user->save();
\DB::commit();
return $this->success('ok');
} catch (Exception $e) {
\DB::rollBack();
return $this->failure('修改资料失败,请重试');
}
}
/**
* vip信息
*/
public function updateVipProfile(Request $request)
{
$user = auth()->user();
$user_id = $user->id;
if ($request->has('identification_photos')) {
$user->identification_photos = json_encode($request->identification_photos);
//提醒客服
$user_ids = [7776, 527, 625];
$content = '有新用户提交实名认证信息!';
$this->userCon->sendAssistantMessage($user_ids, $content);
//添加申请认证记录
$history = ApproveHistory::where('user_id', $user_id)->whereIn('status', [0, 1])->first();
if (empty($history)) {
ApproveHistory::create([
'user_id' => $user_id,
'type' => 'name',
'status' => 0,
'from_platform' => $request->from_platform,
]);
}
}
$user->save();
if ($user->type == 'single') {
$profile = ProfileCourtship::where('user_id', $user_id)->first();
if (empty($profile)) {
$profile = new ProfileCourtship();
$profile->user_id = $user_id;
$profile->save();
// return $this->failure('no profile');
}
if ($request->has('salary_id') && $request->salary_id != $profile->salary_id) {
$profile->salary_id = $request->salary_id;
}
if ($request->has('h_car') && $request->h_car != $profile->h_car) {
$profile->h_car = $request->h_car;
}
if ($request->has('h_housing') && $request->h_housing != $profile->h_housing) {
$profile->h_housing = $request->h_housing;
}
if ($request->has('photos') && json_encode($request->photos) != $profile->photos) {
$profile->photos = json_encode($request->photos);
}
if ($request->has('identification_photos') && json_encode($request->identification_photos) != $profile->identification_photos) {
$profile->identification_photos = json_encode($request->identification_photos);
}
if ($request->has('graduate_photos') && json_encode($request->graduate_photos) != $profile->graduate_photos) {
$profile->graduate_photos = json_encode($request->graduate_photos);
}
if ($request->has('other_photos') && json_encode($request->other_photos) != $profile->other_photos) {
$profile->other_photos = json_encode($request->other_photos);
}
if ($request->has('wechat_qrcode') && json_encode($request->wechat_qrcode) != $profile->wechat_qrcode) {
$profile->wechat_qrcode = json_encode($request->wechat_qrcode);
}
$profile->save();
} else {
$profile = ProfileMarriage::where('user_id', $user_id)->first();
if (empty($profile)) {
$profile = new ProfileMarriage();
$profile->user_id = $user_id;
$profile->save();
// return $this->failure('no profile');
}
if ($request->has('wechat_qrcode') && json_encode($request->wechat_qrcode) != $profile->wechat_qrcode) {
$profile->wechat_qrcode = json_encode($request->wechat_qrcode);
}
$profile->save();
return $this->success('ok');
}
return $this->success('ok');
}
/**
* 公共账号
* @param Request $request
* @return integer 公共账号id
*/
public function getAccountUid(Request $request)
{
$openid = $this->getOpenid();
$wechat = Wechat::with('user')->where('openid', $openid)->first();
if ($wechat && $wechat->user) {
if ($wechat->user->uid) {
$uid = $wechat->user->uid;
} else {
$mobile = $wechat->user->mobile;
$name = $wechat->user->name;
$nickname = $wechat->nickname;
$gender = $wechat->gender;
$city = $wechat->city;
$province = $wechat->province;
$country = $wechat->country;
$unionid = $wechat->unionid;
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
$url = config('app.account_url') . "/api/user";
$data = [
'mobile' => $mobile,
'name' => $name,
'nickname' => $nickname,
'gender' => $gender,
'city' => $city,
'province' => $province,
'country' => $country,
'unionid' => $unionid,
'avatar' => $avatar,
];
try {
$account_user = json_decode(Http::http($url, $data, 'POST'), true);
} catch (Exception $e) {
$message = $e->getMessage();
Messenger::sendSMS('15872844805', $message);
}
if (isset($account_user['id'])) {
$uid = $account_user['id'];
$wechat->user->uid = $uid;
$wechat->user->save();
} else {
$uid = 0;
Messenger::sendSMS('15872844805', '福恋用户, 手机号:' . $mobile . '生成公共账号错误');
}
}
} else {
return $this->failure('该账号还未注册');
}
return $this->success('ok', compact('uid'));
}
/**
* 小程序跳转查询user
*/
public function skipUser(Request $request)
{
$uid = $request->uid;
$session = $this->getWechatSession($request->wechat_code);
$session_key = '';
$openid = '';
if ($session) {
$openid = $session['openid'];
$session_key = $session['session_key'];
}
if ($request->has('iv') && $request->has('encryptedData')) {
$mp = \WechatService::app();
$user_info = $mp->encryptor->decryptData($session_key, $request->iv, $request->encryptedData);
$unionid = $user_info['unionId'];
$url = config('app.account_url') . "/api/user/$uid";
$account_user = json_decode(Http::http($url, $data = [], 'GET'));
if ($unionid != $account_user->wechat->unionid) {
return $this->failure('账号错误');
}
} else {
return $this->failure('缺少参数');
}
//获取公众账号的unionid
$wechat = Wechat::with('user')->where('openid', $openid)->first();
$user = null;
if ($wechat) {
if (!empty($wecha->user)) {
$wechat->user->uid = $uid;
$wechat->user->save();
$user = $wechat->user;
$user->access_token = $user->createToken($user->mobile)->accessToken;
return $this->success('ok', $user);
} else {
$user = new User;
}
} else {
$user = new User;
$wechat = new Wechat;
}
$user->name = $account_user->name;
$user->uid = $uid;
// $mobile = $access_user->mobile;
// $email = $access_user->email;
$password = '';
$user->save();
$wechat->user_id = $user->id;
$wechat->openid = $openid;
$wechat->nickname = $user_info['nickName'];
$wechat->gender = $user_info['gender'];
$wechat->city = $user_info['city'];
$wechat->province = $user_info['province'];
$wechat->country = isset($user_info['country']) ? $user_info['country'] : '中国';
$wechat->avatar = $user_info['avatarUrl'];
$wechat->unionid = $user_info['unionId'];
$wechat->save();
$user->access_token = $user->createToken($user->mobile)->accessToken;
return $this->success('ok', $user);
}
public function getWechatSession($code)
{
$session = null;
try {
if (config('app.debug') && $code == 'the code is a mock one') {
//simulate
$session = [
'openid' => 'oyBj70MRExrrzYH7K8F_VE75XeoE',
'session_key' => 'oyBj70MRExrrzYH7K8F_VE75XeoE',
'unionid' => 'oVMWoswKQA2ToVHyLzcc6t19N4zE',
];
} else {
// $session = $this->app->auth->session($code);
$session = \WechatService::app()->auth->session($code);
}
} catch (\Exeception $e) {
$failure = $e->getMessage;
}
return $session;
}
/**
* 薪资
*/
public function salaries(Request $request)
{
$salaries = Salary::orderBy('min', 'asc')->get();
return $this->success('ok', $salaries);
}
/**
* 好友列表
*/
public function friends(Request $request, $id = null)
{
if (empty($id)) {
$id = auth()->id();
}
$type = $request->input('type');
$types = $type ? [$type] : ['marriage', 'single', 'loveing'];
$ids = Linking::where('user_id', $id)->pluck('user_linking_id');
$other_ids = Linking::where('user_linking_id', $id)->pluck('user_id');
$users = User::where(function ($sql) use ($ids, $other_ids) {
$sql->whereIn('id', $ids)->orWhereIn('id', $other_ids);
})->whereIn('type', $types);
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%');
});
}
$users = $users->orderBy('id', 'desc')->paginate();
foreach ($users as $following) {
$wechat = Wechat::where('user_id', $following->id)->first();
if (!empty($wechat)) {
$following->photo = $following->photo ?: ($wechat->avatar2 ?: $wechat->avatar);
} else {
$following->photo = $following->photo ?: null;
}
$following->wechat = $wechat;
$sex = null;
$age = null;
$stature = null;
$province = null;
if ($following->type == 'single') {
$court = ProfileCourtship::where('user_id', $following->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
}
} else {
$court = ProfileMarriage::where('user_id', $following->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
}
}
$following->sex = $sex;
$following->age = $age;
$following->stature = $stature;
$following->province = $province;
if ($following->type == 'single') {
$following->profile = $following->profileCourtship;
} else {
$following->profile = $following->profileMarriage;
}
$linking = Linking::where('user_id', $id)->where('user_linking_id', $following->id)->first();
if (empty($linking)) {
$linking = Linking::where('user_linking_id', $id)->where('user_id', $following->id)->first();
}
$following->pivot = $linking;
}
return $this->success('mylinkings', $users);
}
/**获取好友的列表 */
public function myFriendsChat(Request $request){
$userinfo = $this->getMyUserinfo();
if(!$userinfo){
return $this->fail('请登录后访问',2);
}
$keyword = $request->keyword;
$type = $request->input('type');
$friendChatList = $this->userCon->getMyFriends($userinfo,$keyword,$type);
return $this->success('ok', ['friendChatList'=>$friendChatList]);
}
public function friendsV2(Request $request, $id = null)
{
if (empty($id)) {
$id = auth()->id();
}
$user = auth()->user();
// $user->cacheUser();
$type = $request->input('type');
$types = $type ? [$type] : ['marriage', 'single', 'loveing'];
$ids = Linking::where('user_id', $id)->pluck('user_linking_id');
$other_ids = Linking::where('user_linking_id', $id)->pluck('user_id');
$users = User::where(function ($sql) use ($ids, $other_ids) {
$sql->whereIn('id', $ids)->orWhereIn('id', $other_ids);
})
// ->where('hidden_profile', '<>', 'ALLSEX')
->whereIn('type', $types);
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%')
->orWhere('nickname', 'like', '%' . $keyword . '%');
});
}
$users = $users->orderBy('id', 'desc')->paginate();
foreach ($users as $following) {
$wechat = Wechat::where('user_id', $following->id)->first();
if (!empty($wechat)) {
$following->photo = $following->photo ?: ($wechat->avatar2 ?: $wechat->avatar);
} else {
$following->photo = $following->photo ?: null;
}
$following->wechat = $wechat;
$sex = null;
$age = 0;
$stature = null;
$province = null;
if ($following->type == 'single') {
$court = ProfileCourtship::where('user_id', $following->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
}
} else {
$court = ProfileMarriage::where('user_id', $following->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
}
}
$following->sex = $sex;
$following->age = $age;
$following->stature = $stature;
$following->province = $province;
if ($following->type == 'single') {
$following->profile = $following->profileCourtship;
} else {
$following->profile = $following->profileMarriage;
}
$linking = Linking::where('user_id', $id)->where('user_linking_id', $following->id)->first();
if (empty($linking)) {
$linking = Linking::where('user_linking_id', $id)->where('user_id', $following->id)->first();
}
$following->pivot = $linking;
}
return $this->success('mylinkings', $users);
}
/**
* 好友列表
* @param Request $request [description]
* @return [type] [description]
*/
public function friendsV3(Request $request)
{
try {
$user = auth()->user();
$linkings = Linking::with('user:id,nickname,photo,app_avatar,rank_id,is_approved,sex,type,hidden_profile', 'userLink:id,nickname,type,photo,app_avatar,rank_id,is_approved,sex,hidden_profile')->where(function($sql){
$sql->where('user_id', auth()->id())->orWhere('user_linking_id', auth()->id());
})->whereHas('user', function($sql){
// $sql->where('hidden_profile', 'NONE')/*->where('type', 'single')*/;
})->whereHas('userLink', function($sql){
// $sql->where('hidden_profile', 'NONE')/*->where('type', 'single')*/;
});
$keyword = $request->keyword;
if($keyword || ($keyword == 0 && $keyword != null) ){
$linkings = $linkings->whereHas('user', function($query) use ($keyword,$user) {
$query->where('nickname', 'like', '%'.$keyword.'%');
$query->orWhere('id',$user->id);
});
$linkings = $linkings->whereHas('userLink', function($query) use ($keyword,$user) {
$query->where('nickname', 'like', '%'.$keyword.'%');
$query->orWhere('id',$user->id);
});
}
$linkings = $linkings->orderBy('created_at', 'desc')->paginate();
foreach ($linkings as $linking) {
if ($linking->user_id != auth()->id()) {
$linking->nickname = $linking->user->nickname;
$linking->id = $linking->user->id;
$linking->is_approved = $linking->user->is_approved;
$linking->isSuperRank = $linking->user->isSuperRank()?1:0;
$linking->sex = $linking->user->sex;
$linking->photo = $linking->user->userAvatar();
$linking->circle_avatar = $linking->user->circle_avatar;
$linking->type = $linking->user->type;
$linking->hidden_profile = $linking->user->hidden_profile;
}else{
$linking->nickname = $linking->userLink->nickname;
$linking->id = $linking->userLink->id;
$linking->is_approved = $linking->userLink->is_approved;
$linking->isSuperRank = $linking->userLink->isSuperRank()?1:0;
$linking->sex = $linking->userLink->sex;
$linking->photo = $linking->userLink->userAvatar();
$linking->circle_avatar = $linking->userLink->circle_avatar;
$linking->type = $linking->userLink->type;
$linking->hidden_profile = $linking->userLink->hidden_profile;
}
$linking->province = '';
$linking->age = '';
$age = '';
$court = '';
$sex = '';
$stature = '';
$province = '';
$birthday = '';
if ($linking->type == 'single') {
$court = ProfileCourtship::where('user_id', $linking->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$birthday = $court->birthday;
$stature = $court->stature;
$province = $court->province;
}
} else {
$court = ProfileMarriage::where('user_id', $linking->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
$birthday = $court->birthday;
}
}
$linking->profile = $court;
$linking->sex = $sex;
$linking->age = $age;
$linking->stature = $stature;
$linking->province = $province;
$linking->birthday = empty($birthday) ? : substr($birthday, 2,2);
$linking->pivot = ['created_at'=> date($linking->created_at)];
unset($linking->user, $linking->userLink, $linking->user_linking_id,$linking->user_id, $user->profile);
}
return $this->success('ok', $linkings);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取好友列表信息失败,请稍后再试');
}
}
/**
* 我的粉丝
*/
public function followers(Request $request, $id = null)
{
if (!$id) {
$id = auth()->id();
}
$size = $request->input('size',15);
$user = User::find($id);
$user->cacheUser();
$type = $request->input('type');
$followers = $user->followers();
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$followers = $followers->where('name', 'like', '%' . $keyword . '%');
}
$followers = $followers
->orderBY('followables.created_at', 'desc')
->paginate($size);
foreach ($followers as $following) {
$rd_user_key = User::cacheUserKey($following->id);
if (Cache::has($rd_user_key)) {
$rd_user = Cache::get($rd_user_key);
} else {
$following->cacheUser();
$rd_user = Cache::get($rd_user_key);
}
$following->photo = $rd_user->userAvatar();
$following->sex = $rd_user->sex;
$following->age = $rd_user->age;
$stature = null;
$province = null;
$birthday = null;
$city = null;
if ($following->type == 'single') {
$court = $rd_user->profileCourtship;
} else {
$court = $rd_user->profileMarriage;
}
if (!empty($court)) {
$stature = $court->stature;
$province = $court->province;
$birthday = $court->birthday;
$city = $court->city;
}
$following->stature = $stature;
$following->province = $province;
$following->birthday = $birthday;
$following->city = !empty($city) ? str_replace('市', '', $city) : '无';
$following->year = !empty($birthday) ? substr($birthday, 2, 2) . '年' : '未填写';
}
Notice::where('status', 0)->where('user_id', $id)->where('type', 'follow')->update(['status' => 1]);
return $this->success('ok', $followers);
}
public function followersV2(Request $request, $id = null)
{
if (!$id) {
$id = auth()->id();
}
$followables = DB::table('followables')->where('followable_id', $id)
->where('followable_type', 'App\\Models\\User')->where('relation', 'follow');
$users = DB::table("users")->rightJoinSub($followables, 'ufutx_followables', function($join) {
$join->on('users.id', '=', 'followables.user_id');
})
->where('users.hidden_profile','!=','ALLSEX')
->select('id', 'nickname', 'sex','photo', 'type', 'hidden_profile', 'followables.created_at')
->orderBy('followables.created_at', 'desc')->paginate(18);
foreach ($users as $user) {
$user->avatar = $user->photo;
$court = ProfileCourtship::where('user_id',$user->id)->first();
$user->stature = $court?$court->stature:null;
$user->province = $court?$court->province:null;
$user->city = !empty($court->city) ? str_replace('市', '', $court->city) : '无';
$user->year = !empty($court->birthday) ? substr($court->birthday, 2, 2) . '年' : '未填写';
}
return $this->success('ok', $users);
}
/**
* 我的关注者
*/
public function followings(Request $request, $id = null)
{
if (!$id) {
$id = auth()->id();
}
$user = User::find($id);
$user->cacheUser();
$type = $request->input('type');
$types = $type ? [$type] : ['marriage', 'single', 'loveing'];
$followings = $user->followings()->where('hidden_profile','!=','ALLSEX');
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$followings = $followings->where('name', 'like', '%' . $keyword . '%');
}
$followings = $followings->whereIn('type', $types)
->orderBy('followables.created_at', 'desc')
->paginate();
foreach ($followings as $following) {
$wechat = Wechat::where('user_id', $following->id)->first();
if (!empty($wechat)) {
$following->photo = $following->photo ?: ($wechat->avatar2 ?: $wechat->avatar);
}
$following->wechat = $wechat;
$sex = 1;
$age = 0;
$stature = null;
$province = null;
if ($following->type == 'single') {
$court = ProfileCourtship::where('user_id', $following->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
} else {
$sex = $following->wechat ? $following->wechat->sex : $sex;
$province = $following->province;
}
} else {
$court = ProfileMarriage::where('user_id', $following->id)->first();
if (!empty($court)) {
$sex = $court->sex;
if ($court->birthday) {
$age = $this->getAge($court->birthday);
}
$stature = $court->stature;
$province = $court->province;
} else {
$sex = $following->wechat->sex;
$province = $following->province;
}
}
$following->sex = $sex;
$following->age = $age;
$following->stature = $stature;
$following->province = $province;
$following->is_super_rank = $following->isSuperRank($following->id);
}
return $this->success('ok', $followings);
}
public function followingsV2(Request $request, $id = null)
{
try {
if (!$id) {
$id = auth()->id();
}
$followables = DB::table('followables')->where('user_id', $id)
->where('followable_type', 'App\\Models\\User')
->where('relation', 'follow');
$users = DB::table("users")->rightJoinSub($followables, 'ufutx_followables', function ($join) {
$join->on('users.id', '=', 'followables.followable_id');
})
// ->where('users.hidden_profile','!=','ALLSEX')
->select('id', 'nickname', 'sex', 'photo', 'type', 'hidden_profile', 'followables.created_at');
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where('nickname', 'like', '%' . $keyword . '%');
}
$users = $users->orderBy('followables.created_at', 'desc')->paginate(18);
foreach ($users as $user) {
$user->avatar = $user->photo;
$court = ProfileCourtship::where('user_id', $user->id)->first();
$user->age = $court? $this->getAge($court->birthday):'';
$user->pivot = ['created_at' => $user->created_at];
//是否互关
$user->is_mutual_follow = Followable::where('user_id', $user->id)->where('followable_id', $id)
->where('followable_type', 'App\\Models\\User')->count() ? 1 : 0;
$user->birthday = ($court && $court->birthday) ? substr($court->birthday, 2, 2) : '';
$user->city = $court? $court->city: '';
}
return $this->success('ok', $users);
}catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍候再试");
}
}
/**
* 我的订单
*/
public function userOrders(Request $request)
{
$user_id = auth()->id();
$orders = Order::where('user_id', $user_id)->where('pay_status', 'PAID')->orderBy('id', 'desc')->paginate();
foreach ($orders as $order) {
$message = '';
if ($order->type == 'rank') {
$rank_name = Rank::where('id', $order->type_id)->value('name');
$message = '升级' . $rank_name;
} elseif ($order->type == 'other_rank') {
$rank_name = Rank::where('id', $order->type_id)->value('name');
$message = '分享升级' . $rank_name;
$invite_order = InviteOrder::where('trade_no', $order->trade_no)->first();
if (!empty($invite_order)) {
$order->invite_pic = $invite_order->invite_pic;
$order->other_openid = $invite_order->other_openid;
$other_wechat = Wechat::where('openid', $invite_order->other_openid)->first();
$other_name = '';
if (!empty($other_wechat)) {
if ($other_wechat->user_id) {
$other_name = User::where('id', $other_wechat->user_id)->value('name');
} else {
$other_name = $other_wechat->nickname;
}
}
$order->other_name = $other_name;
}
} elseif ($order->type == 'gift') {
$gift_name = Gift::where('id', $order->type_id)->value('name');
$other_user_id = GiftHistory::where('trade_no', $order->trade_no)->where('type', 'GIVEN')->value('other_user_id');
$other_name = User::where('id', $other_user_id)->value('name');
$order->other_name = $other_name;
$message = '购买' . $gift_name;
} elseif ($order->type == 'score') {
$message = '账户充值';
} elseif ($order->type == 'goods') {
$goods_name = Goods::where('id', $order->type_id)->value('name');
$message = '兑换' . $goods_name;
}
$order->message = $message;
}
return $this->success('ok', $orders);
}
/**
* 用户订单V2
*/
public function userOrdersV2(Request $request)
{
$user = $this->authCheck();
$userId = 0;
$type = $request->input('type', 'rank');
if($user){
$userId = $user->id;
}
$orders = Order::with('subRank')->whereHas('subRank')->where('user_id', $userId)->where('goods', '<>', '购买0个月市级VIP')->where('type', $type)->where('pay_status', 'PAID')->orderBy('id', 'desc')->paginate();
foreach ($orders as $key => $order) {
$order->pic = $order->subRank->pic;
$order->rank_name = $order->subRank->name;
unset($order->subRank);
}
return $this->success('ok', $orders);
}
public function newNotice()
{
$user = auth()->user();
if (empty($user)) {
$user = $this->authCheck();
}
$new_notice_count = 0;
$type = null;
if ($user) {
$new_notice_count = Notice::where('user_id', $user->id)->where('status', 0)->count();
$type = $user->type;
$new_message_count = ChatMessage::where('other_user_id', $user->id)->where('status', 0)->count();
$new_notice_count = $new_notice_count + $new_message_count;
}
return $this->success('ok', compact('new_notice_count', 'type'));
}
public function myShare(Request $request)
{
try {
$type = $request->input('type', 'single_trip');
$user = $this->authCheck();
if(empty($user)){
return $this->fail('profile', 2, 'pages/tabBar/home', '未登录', '你的账号还没登录');
}
$pic = $this->createShareImg($user,$type);
return $this->success('ok', compact('pic'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('生成分享图片失败, 请稍后再试');
}
// try {
// $type = $request->input('type', 'single_trip');
// $log = $this->shareImg($type);
// if (empty($log)) throw new \Exception("生成分享图片失败", 1);
// $pic = $log->photo;
// return $this->success('ok', compact('pic'));
// } catch (\Exception $e) {
// $this->getError($e);
// return $this->failure('生成分享图片失败, 请稍后再试');
// }
}
public function shareImg($type)
{
try {
$user = auth()->user();
$log = $user->shareImgLogs()->where('type', $type)->first();
if (empty($log)) {
$qrcode = $user->my_qrcode;
if (empty($qrcode)) {
$qrcode = QrcodeRectService::getQrCode($user);
$user->my_qrcode = $qrcode;
$user->save();
}
$photo = QrcodeRectService::makeMyShareForType($user, $qrcode, $type);
if (empty($photo)) throw new \Exception("图片生成失败", 1);
$log = $user->shareImgLogs()->where('type', $type)->create([
'user_id' => $user->id,
'photo' => $photo,
'type' => $type
]);
}
return $log;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public function createShareImg($user, $type){
$imgSrc = 'https://local-pictures.oss-cn-shenzhen.aliyuncs.com/202105/19/fe0b4df62bbe4c5e8bbd094cf4024602.jpeg';
$qrcode = QrcodeRectService::getQrCodeV2($user,'pages/tabBar/welcome');
$user->my_qrcode = $qrcode ;
$user->save();
$photo = QrcodeRectService::makeMyShareForType($user, $qrcode, $type);
return $photo;
}
public function createAllUserShareImg(Request $request){
$type = $request->input('type', 'single_trip');
$imgSrc = 'https://local-pictures.oss-cn-shenzhen.aliyuncs.com/202105/19/fe0b4df62bbe4c5e8bbd094cf4024602.jpeg';
// $imgSrc = 'https://images.ufutx.com/202104/30/eff01d5faa7fae2286f9bf1a73db9996.png';
$user = User::where('id',94268)->first();
if(!$user){
return $this->failure('用户没找到');
}
$qrcode = QrcodeRectService::getQrCodeV2($user,'pages/tabBar/welcome');
$user->my_qrcode = $qrcode ;
$user->save();
$qrcode = $user->my_qrcode;
$photo = QrcodeRectService::makeMySharePoster($user, $qrcode, $imgSrc);
dd($photo);
}
public function otherUserShare(Request $request, User $user)
{
$wechat = $user->wechat;
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
$avatar = $user->circle_avatar ?: ($user->photo ?: $avatar);
if ($user->my_share_rect) {
$pic = $user->my_share_rect;
$qrcode = $user->my_qrcode_rect;
return $this->success('ok', compact('pic', 'qrcode','avatar'));
}
try {
if (empty($user->my_qrcode_rect)) {
$my_qrcode_rect = QrcodeRectService::getQrCodeRect($user);
} else {
$my_qrcode_rect = $user->my_qrcode_rect;
}
$pic = QrcodeRectService::makeMyShareRect($user, $my_qrcode_rect);
$name = $user->name;
User::where('id', $user->id)->update(['my_qrcode_rect' => $my_qrcode_rect, 'my_share_rect' => $pic]);
return $this->success('ok', compact('my_qrcode_rect', 'name', 'avatar', 'pic'));
} catch (\Exception $e) {
\Log::error($e->getMessage());
return $this->failure('图片生成失败,请稍后再试');
}
}
/**
* 消息联系人列表
*/
public function messageLinkmen(Request $request)
{
$user_id = auth()->id();
$linkmen = MessageLinkman::whereHas('otheruser', function ($sql) {
$sql->where('id', '>', 0)->where('hidden_profile', '<>', 'ALLSEX');
})->where('user_id', $user_id);
$type = $request->input('type');
if ($type) {
$linkmen = $linkmen->where('type', $type);
}
$linkmen = $linkmen->orderBy('updated_at', 'desc')->paginate();
foreach ($linkmen as $linkman) {
// if ($linkman->user_id == $user_id) {//自己
$new_count = ChatMessage::where('status', 0)->where('user_id', $linkman->other_user_id)->where('other_user_id', $linkman->user_id)->count();
$user = User::where('id', $linkman->other_user_id)->select('id', 'name')->first();
// }else{
// $new_count = ChatMessage::where('status', 0)->where('user_id', $linkman->user_id)->where('other_user_id', $linkman->other_user_id)->count();
// $user = User::where('id', $linkman->user_id)->select('id', 'name')->first();
// }
if (empty($user)) {
continue;
}
$linkman->new_count = $new_count;
$wechat = Wechat::where('user_id', $user->id)->select('avatar', 'avatar2')->first();
if (empty($wechat)) {
if ($user->sex == 1) {
$avatar = 'http://images.ufutx.com/201811/12/0e8b72aae6fa640d9e73ed312edeebf3.png';
} else {
$avatar = 'http://images.ufutx.com/201811/12/dddd79aa2c2fc6a6f35e641f6b8fb8f5.png';
}
} else {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
}
$user->avatar = $avatar;
$linkman->user = $user;
$other_user_id = $user->id;
$last_message = ChatMessage::where(function ($sql) use ($user_id, $other_user_id) {
$sql->where(['user_id' => $user_id, 'other_user_id' => $other_user_id]);
})->orWhere(function ($sql) use ($user_id, $other_user_id) {
$sql->where(['user_id' => $other_user_id, 'other_user_id' => $user_id]);
})->orderBy('id', 'desc')->first();
$linkman->last_message = $last_message;
}
return $this->success('ok', compact('linkmen'));
}
/**
* 新留言
* @param Request $request [description]
* @return [type] [description]
*/
public function messageLinkmanList(Request $request)
{
$user = auth()->user();
$user_id = $user->id;
//良人
$single_man_user_ids = MessageLinkman::where('user_id', $user_id)->where('type', 'single_man')->pluck('other_user_id');
//新消息数
$single_man_count = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $single_man_user_ids)->count();
//发新消息人数
$send_user_ids = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $single_man_user_ids)->pluck('user_id');
$single_men = MessageLinkman::where('user_id', $user_id)->whereIn('other_user_id', $send_user_ids)->where('type', 'single_man')->orderBy('updated_at', 'desc')->get();
foreach ($single_men as $single_man) {
$single_man->circle_avatar = User::where('id', $single_man->other_user_id)->value('circle_avatar');
}
//佳偶
$single_woman_user_ids = MessageLinkman::where('user_id', $user_id)->where('type', 'single_woman')->pluck('other_user_id');
//新消息数
$single_woman_count = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $single_woman_user_ids)->count();
//发新消息人数
$send_user_ids = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $single_woman_user_ids)->pluck('user_id');
$single_women = MessageLinkman::where('user_id', $user_id)->whereIn('other_user_id', $send_user_ids)->where('type', 'single_woman')->orderBy('updated_at', 'desc')->get();
foreach ($single_women as $single_woman) {
$single_woman->circle_avatar = User::where('id', $single_woman->other_user_id)->value('circle_avatar');
}
//红娘
$maker_user_ids = MessageLinkman::where('user_id', $user_id)->where('type', 'maker')->pluck('other_user_id');
//新消息数
$maker_count = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $maker_user_ids)->count();
//发新消息人数
$send_user_ids = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $maker_user_ids)->pluck('user_id');
$makers = MessageLinkman::where('user_id', $user_id)->whereIn('other_user_id', $send_user_ids)->where('type', 'maker')->orderBy('updated_at', 'desc')->get();
foreach ($makers as $maker) {
$maker->circle_avatar = User::where('id', $maker->other_user_id)->value('circle_avatar');
}
//介绍人
$marriage_user_ids = MessageLinkman::where('user_id', $user_id)->where(function ($sql) {
$sql->where('type', 'marriage')->orWhere('type', 'loveing');
})->pluck('other_user_id');
//新消息数
$marriage_count = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $marriage_user_ids)->count();
//发新消息人数
$send_user_ids = ChatMessage::where('status', 0)->where('other_user_id', $user->id)->whereIn('user_id', $marriage_user_ids)->pluck('user_id');
$marriages = MessageLinkman::where('user_id', $user_id)->whereIn('other_user_id', $send_user_ids)->where('type', 'marriage')->orderBy('updated_at', 'desc')->get();
foreach ($marriages as $marriage) {
$marriage->circle_avatar = User::where('id', $marriage->other_user_id)->value('circle_avatar');
}
//咨询
//活动
//
$result = [
'single_man_count' => $single_man_count,
'single_men' => $single_men,
'single_woman_count' => $single_woman_count,
'single_women' => $single_women,
'maker_count' => $maker_count,
'makers' => $makers,
'marriage_count' => $marriage_count,
'marriages' => $marriages,
];
return $this->success('ok', $result);
}
/**
* 消息列表
*/
public function chatMessages(Request $request, $other_user_id)
{
try {
if ($other_user_id == 1) { //小恋
$messages = $this->assistantMessages($request, $other_user_id);
return $this->success('ok', $messages);
} else {
$user_id = auth()->id();
$min_id = $request->input('min_id', 0);
$messages = ChatMessage::where(function ($sql) use ($user_id, $other_user_id, $min_id) {
$sql->where(['user_id' => $user_id, 'other_user_id' => $other_user_id]);
if ($min_id) {
$sql->where('id', '<', $min_id);
}
})->orWhere(function ($sql) use ($user_id, $other_user_id, $min_id) {
$sql->where(['user_id' => $other_user_id, 'other_user_id' => $user_id]);
if ($min_id) {
$sql->where('id', '<', $min_id);
}
})->orderBy('id', 'desc')->limit(7)->get();
$other_user = User::find($other_user_id);
//是否是黑名单
$is_blacklist = LinkingBlacklist::where('user_id', $user_id)->where('other_user_id', $other_user_id)->count() ? 1 : 0;
foreach ($messages as $message) {
if ($message->user_id == $user_id) {
$is_mine = 1;
} else {
$is_mine = 0;
}
$user = User::find($message->user_id);
$avatar = $user->avatar;
// $wechat = Wechat::where('user_id', $message->user_id)->select('avatar', 'avatar2')->first();
// $avatar = '';
// if ($user->photo) {
// $avatar = $user->photo;
// } else {
// if (!empty($wechat)) {
// $avatar = $wechat->avatar2 ?: $wechat->avatar;
// }
// }
$message->is_mine = $is_mine;
$message->avatar = $avatar;
$message->type = $other_user->type;
$message->is_blacklist = $is_blacklist;
//如果是卡片
if ($message->content_type === 'CARD') {
$message->card = json_decode($message->content, true);
}
}
ChatMessage::where(function ($sql) use ($user_id, $other_user_id, $min_id) {
$sql->where(['user_id' => $user_id, 'other_user_id' => $other_user_id]);
if ($min_id) {
$sql->where('id', '<', $min_id);
}
})->orWhere(function ($sql) use ($user_id, $other_user_id, $min_id) {
$sql->where(['user_id' => $other_user_id, 'other_user_id' => $user_id]);
if ($min_id) {
$sql->where('id', '<', $min_id);
}
})->orderBy('id', 'desc')->update(['status' => 1]);
return $this->success('ok', $messages);
}
} catch (\Exception $e) {
\Log::error($e->getMessage());
return $this->failure('信息获取失败,请稍后再试');
}
}
public function assistantMessages($request, $other_user_id)
{
$user_id = auth()->id();
$min_id = $request->input('min_id', 0);
$messages = AssistantUser::where('user_id', $user_id)->where('assistant_user_id', 1);
if ($request->input('min_id')) {
$messages = $messages->where('id', '<', $request->input('min_id'));
}
$messages = $messages->orderBy('id', 'desc')->limit(7)->get();
$other_user = User::find($other_user_id);
AssistantUser::where('status', 0)->update(['status' => 1]);
//是否是黑名单
foreach ($messages as $message) {
$wechat = Wechat::where('user_id', $message->assistant_user_id)->select('avatar', 'avatar2')->first();
// $avatar = '';
$avatar = User::where('id', 1)->value('photo');
if (empty($avatar) && !empty($wechat)) {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
}
$message->avatar = $avatar;
$message->type = $other_user->type;
$message->is_mine = 0;
if ($message->msg_type == 'card') { //如果是卡片
$content = json_decode($message->content, true);
//福恋使者的头像和昵称
$messenger = User::where('id', $content['sharer_user_id'])->select('id', 'nickname', 'photo')->first();
$message->messenger = $messenger;
//被推荐人
$recommend_user = User::where('id', $content['user_id'])->select('id', 'nickname', 'photo')->first();
$profile = SingleProfile::where('user_id', $recommend_user->id)->select('birthday', 'stature', 'province', 'city', 'belief')->first();
if ($profile) {
$profile->age = \CommonUtilsService::getAge($profile->birthday);
}
$message->recommend_profile = $profile;
$message->recommend_user = $recommend_user;
}
}
return $messages;
}
/**
* 发消息
*/
public function sendChatMessage(Request $request, $other_user_id)
{
$user = auth()->user();
$user_id = $user->id;
//查看是否被禁言
$date = date('Y-m-d H:i:s');
$history = BannedHistory::where('user_id',$user_id)->where('type','chat')->first();
if (!empty($history)) {
if($history->end_time >= $date && $history->end_time <= $date) return $this->failure('你被禁止聊天至'.$history->end_time);
}
$content = $request->input('content', '');
if (empty($content)&&$request->content_type=='text') {
return $this->failure('请输入信息。');
}
// //是否是好友
// $result = $this->userCon->isFriend($other_user_id, $user_id);
// if (!$result) {
// return $this->failure('该用户还不是你的好友!');
// }
$result = \CommonUtilsService::checkIsRiskyContent($content);
if($result){
return $this->failure('您填写的内容可能潜在风险,请重新输入');
}
$other_user = User::find($other_user_id);
if($other_user->hidden_profile != 'NONE'){
return $this->failure('该用户已经关闭了资料!');
}
//判断是否是介绍人加单身或者单身加介绍人
if ($user->type != $other_user->type) return $this->failure('介绍人在小程序不能参与聊天请下载APP交流。');
//我的聯係人
$is_super_rank = $user->isSuperRank();
$is_temp_rank = $user->isTempMember();
if (empty($is_temp_rank) && empty($is_super_rank)) { //如果不是会员 可以聊三句
$count = $user->chatMessageCountWithUser($other_user->id);
$coin = $user->totalCoin();
if ($count >= 3) return $this->success('ok', ['error_code' => '1', 'coin' => $coin]);
}
$my_linkman = MessageLinkman::where('user_id', $user_id)->where('other_user_id', $other_user_id)->first();
$other_linkman = MessageLinkman::where('user_id', $other_user_id)->where('other_user_id', $user_id)->first();
$maker = Matchmaker::where('user_id', $other_user_id)->where('status', 1)->first();
$other_type = null;
if ($maker) {
$other_type = 'maker';
} else {
if ($other_user->type == 'marriage') {
$other_type = 'marriage';
} else {
if ($other_user->type == 'single' && $other_user->sex == 1) {
$other_type = 'single_man';
} elseif ($other_user->type == 'single' && $other_user->sex == 2) {
$other_type = 'single_woman';
}
}
}
if (empty($my_linkman)) {
$my_linkman = MessageLinkman::create([
'user_id' => $user_id,
'other_user_id' => $other_user_id,
'type' => $other_type,
]);
} else {
$time = date('Y-m-d H:i:s', time());
$my_linkman->updated_at = $time;
$my_linkman->type = $other_type;
$my_linkman->save();
}
if (empty($other_linkman)) {
$my_linkman = MessageLinkman::create([
'user_id' => $other_user_id,
'other_user_id' => $user->id,
'type' => $user->type,
]);
} else {
$time = date('Y-m-d H:i:s', time());
$other_linkman->updated_at = $time;
$other_linkman->type = $user->type;
$other_linkman->save();
}
$other_linkman = MessageLinkman::where('user_id', $other_user_id)->where('other_user_id', $user_id)->first();
$maker = Matchmaker::where('user_id', $user_id)->where('status', 1)->first();
$my_type = null;
if ($maker) {
$my_type = 'maker';
} else {
if ($user->type == 'marriage') {
$my_type = 'marriage';
} else {
if ($user->type == 'single' && $user->sex == 1) {
$my_type = 'single_man';
} elseif ($user->type == 'single' && $user->sex == 2) {
$my_type = 'single_woman';
}
}
}
if (empty($other_linkman)) {
$other_linkman = MessageLinkman::create([
'user_id' => $other_user_id,
'other_user_id' => $user_id,
'type' => $my_type,
]);
} else {
$time = date('Y-m-d H:i:s', time());
$other_linkman->updated_at = $time;
$other_linkman->type = $my_type;
$other_linkman->save();
}
$message = ChatMessage::create([
'user_id' => $user_id,
'other_user_id' => $other_user_id,
'content' => $content,
]);
$messages = $this->newMessage($request, $user_id, $other_user_id);
$other_user = User::findOrFail($other_user_id);
broadcast(new NoticeServer($other_user));
broadcast(new ChatMessages($message, $other_user));
return $this->success('ok', $messages);
}
/**
* 发消息
*/
public function sendChatMessagev2(Request $request, $other_user_id)
{
$user = auth()->user();
$user_id = $user->id;
$other_user = User::find($other_user_id);
//双方是否建立联系
$system_type = ['remind','greet','notice'];
$my_num = ChatMessage::where('user_id',$user->id)->where('other_user_id',$other_user->id)->wherenotin('system_type',$system_type)->count();
$other_num = ChatMessage::where('user_id',$other_user->id)->where('other_user_id',$user->id)->wherenotin('system_type',$system_type)->count();
if($other_user->hidden_profile != 'NONE'){
return $this->failure('该用户已经关闭了资料!');
}
$my_linkman = MessageLinkman::where('user_id', $user_id)->where('other_user_id', $other_user_id)->first();
$other_linkman = MessageLinkman::where('user_id', $other_user_id)->where('other_user_id', $user_id)->first();
$maker = Matchmaker::where('user_id', $other_user_id)->where('status', 1)->first();
$other_type = null;
if ($maker) {
$other_type = 'maker';
} else {
if ($other_user->type == 'marriage') {
$other_type = 'marriage';
} else {
if ($other_user->type == 'single' && $other_user->sex == 1) {
$other_type = 'single_man';
} elseif ($other_user->type == 'single' && $other_user->sex == 2) {
$other_type = 'single_woman';
}
}
}
if (empty($my_linkman)) {
$my_linkman = MessageLinkman::create([
'user_id' => $user_id,
'other_user_id' => $other_user_id,
'type' => $other_type,
]);
} else {
$time = date('Y-m-d H:i:s', time());
$my_linkman->updated_at = $time;
$my_linkman->type = $other_type;
$my_linkman->save();
}
if (empty($other_linkman)) {
$other_linkman = MessageLinkman::create([
'user_id' => $other_user_id,
'other_user_id' => $user->id,
'type' => $user->type,
]);
} else {
$time = date('Y-m-d H:i:s', time());
$other_linkman->updated_at = $time;
$other_linkman->type = $user->type;
$other_linkman->save();
}
$my_type = null;
if ($maker) {
$my_type = 'maker';
} else {
if ($user->type == 'marriage') {
$my_type = 'marriage';
} else {
if ($user->type == 'single' && $user->sex == 1) {
$my_type = 'single_man';
} elseif ($user->type == 'single' && $user->sex == 2) {
$my_type = 'single_woman';
}
}
}
if (empty($other_linkman)) {
$other_linkman = MessageLinkman::create([
'user_id' => $other_user_id,
'other_user_id' => $user_id,
'type' => $my_type,
]);
} else {
$time = date('Y-m-d H:i:s', time());
$other_linkman->updated_at = $time;
$other_linkman->type = $my_type;
$other_linkman->save();
}
$content_type = $request->input('content_type', 'TEXT');
$message = ChatMessage::create([
'user_id' => $user_id,
'other_user_id' => $other_user_id,
'content' => $request->input('content'),
'content_type'=>$content_type,
]);
$messages = $this->newMessage($request, $user_id, $other_user_id);
$other_user = User::findOrFail($other_user_id);
broadcast(new NoticeServer($other_user));
broadcast(new ChatMessages($message, $other_user));
//如果双方已经通信.
$code = 0;
if($my_num<=1&&$other_num>=1){
//发送端已认证,接受端未认证
if($user->is_real_approved==1&&$other_user->is_real_approved!=1){
$key = 'u'.$user->id.'f'.$other_user->id.'chat';
$result = Cache::add($key, true, 60*24*3);
$code = 0;
if($result)//是否提示过
$code = 1;
}
}elseif ($my_num>=2) {
//如果发送方未认证
if($user->is_real_approved!=1){
//如果在审核中
$exists = ApproveHistory::where('user_id',$user->id)->where('type','body')->where('status',0)->exists();
if( $exists)
$code = 3;
$code = 2;
}
//如果已邀请对方认证
$remind = ChatMessage::where('user_id',$user->id)->where('other_user_id',$other_user->id)->where('system_type','remind')->exists();
if($remind&&$other_user->is_real_approved!=1)
$code = 5;
//如果接受方未认证
if($other_user->is_real_approved!=1)
$code = 4;
$code = 0;
//如果双方已经通信.第一次
}else{
$code = 0;
}
return $this->resp('ok', $messages,$code);
}
public function sendChatMessageV3(Request $request, $other_user_id)
{
try {
//发送聊天内容
$message = $this->userCon->sendChatMessage(auth()->user(), $request->other_user, $request->input('content'));
$messages = $this->newMessage($request, auth()->id(), $other_user_id);
//发送聊天模板消息
if ($request->versions != 'v5.4') {
// StartMessageNotice::dispatch($message)->onQueue('start_message')/*->delay(now()->addMinutes(1))*/;
}
return $this->success('ok', $messages);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
/**
* 最新数据
*/
public function newMessage($request, $user_id, $other_user_id)
{
$max_id = $request->input('max_id');
if ($other_user_id == 1) {
$messages = AssistantUser::where('user_id', $user_id)->where('assistant_user_id', 1)->where(function ($sql) use ($max_id) {
if ($max_id) {
$sql->where('id', '>', $max_id);
}
})->orderBy('id', 'desc')->get();
} else {
$messages = ChatMessage::where(function ($sql) use ($user_id, $other_user_id, $max_id) {
$sql->where(['user_id' => $user_id, 'other_user_id' => $other_user_id]);
if ($max_id) {
$sql->where('id', '>', $max_id);
}
})->orWhere(function ($sql) use ($user_id, $other_user_id, $max_id) {
$sql->where(['user_id' => $other_user_id, 'other_user_id' => $user_id]);
if ($max_id) {
$sql->where('id', '>', $max_id);
}
})->whereNotNull('content')->orderBy('id', 'desc')->get();
}
foreach ($messages as $message) {
// $is_mine = 1;
$avatar = '';
$wechat = Wechat::where('user_id', $message->user_id)->select('avatar', 'avatar2')->first();
if (!empty($wechat)) {
$avatar = $wechat->avatar2 ? $wechat->avatar2 : $wechat->avatar;
}
$message->is_mine = $user_id == $message->user_id ? 1 : 0;
$message->avatar = $avatar;
//如果是卡片
if ($message->content_type === 'CARD') {
$message->card = json_decode($message->content, true);
}
}
ChatMessage::where('user_id', $other_user_id)->where('other_user_id', $user_id)->update(['status' => 1]);
return $messages;
}
/**
* 刷新数据
*/
public function refreshChatMessage(Request $request, $other_user_id)
{
$user_id = auth()->id();
$messages = $this->newMessage($request, $user_id, $other_user_id);
return $this->success('ok', $messages);
}
//是否注册过
public function registerInfor(Request $request)
{
$session = $this->getWechatSession($request->wechat_code);
$session_key = '';
$openid = '';
if ($session && isset($session['openid'])) {
$openid = $session['openid'];
$session_key = $session['session_key'];
} else {
return $this->failure('no openid');
}
$is_register = 0;
$wechat = Wechat::with('user')->where('openid', $openid)->first();
if ($wechat && $wechat->user) {
$is_register = 1;
}
return $this->success('ok', compact('is_register', 'wechat'));
}
/**
* 小程序跳转查询user
*/
public function userV4(Request $request)
{
$uid = $request->uid;
if ($uid == 'undefined') {
return $this->success('ok');
}
$session = $this->getWechatSession($request->wechat_code);
$session_key = '';
$openid = '';
if ($session) {
$openid = $session['openid'];
$session_key = $session['session_key'];
}
// if ($request->has('iv') && $request->has('encryptedData')) {
// $mp = \WechatService::app();
// $user_info = $mp->encryptor->decryptData($session_key, $request->iv, $request->encryptedData);
// $unionid = $user_info['unionId'];
$url = config('app.account_url') . "/api/user/$uid";
$account_user = json_decode(Http::http($url, $data = [], 'GET'), true);
// if ($unionid != $account_user->wechat->unionid) {
// return $this->failure('账号错误');
// }
// }
//获取公众账号的unionid
$wechat = Wechat::with('user')->where('openid', $openid)->first();
if ($wechat) {
if (!empty($wechat->user)) {
$wechat->user->uid = $uid;
$wechat->user->save();
$user = $wechat->user;
$user->access_token = $user->createToken($user->mobile)->accessToken;
return $this->success('ok', $user);
} else {
$user = User::where('mobile', $account_user['mobile'])->first();
if (empty($user)) {
$user = new User;
}
}
} else {
$user = User::where('mobile', $account_user['mobile'])->first();
if (empty($user)) {
$user = new User;
}
$wechat = new Wechat;
}
$user->name = $account_user['name'];
$user->uid = $uid;
$user->mobile = $account_user['mobile'];
$user->email = $account_user['email'];
$user->password = '';
$user->save();
$wechat->user_id = $user->id;
$wechat->openid = $openid;
$wechat->nickname = $account_user['wechat']['nickname'];
$wechat->gender = $account_user['wechat']['gender'];
$wechat->city = $account_user['wechat']['city'];
$wechat->province = $account_user['wechat']['province'];
$wechat->country = isset($account_user['wechat']['country']) ? $account_user['wechat']['country'] : '中国';
$wechat->avatar = $account_user['wechat']['avatar'];
$wechat->unionid = $account_user['wechat']['unionid'];
$wechat->save();
$user->access_token = $user->createToken($user->mobile)->accessToken;
return $this->success('ok', $user);
}
public function updateWechatAvatar(Request $request)
{
$user = auth()->user();
$user_id = $user->id;
$wechat = Wechat::where('user_id', $user_id)->first();
if ($request->has('avatar') && !empty($request->avatar) && $wechat->avatar != $request->avatar) {
$wechat->avatar = $request->avatar;
$wechat->avatar2 = '';
$user->photo = '';
$user->circle_avatar = '';
$user->is_photo_audited = 0;
$user->save();
$wechat->save();
}
return $this->success('ok');
}
/**
* 是否可以领取临时会员
* @param int $user_id 用户ID
* @return [type] [description]
*/
public function canGetTempMember($user_id = 0)
{
//是否是临时会员
if (empty($user_id)) {
$user_id = auth()->id();
}
$user = User::find($user_id);
$can_get_temp_member = 0;
$is_profile = 1;
//是否可以领取注册红包
$can_get_red_packet = 0;
$order = RedPacketOrder::where('user_id', $user->id)->where('type', 'REGISTER')->first();
$time = date('Y-m-d H:i:s');
$end_time = $user->created_at->modify('+1 day')->toDateTimeString();
$start_time = $user->created_at->toDateTimeString();
if ($end_time > $time && $start_time < $time && empty($order)) { //24h内注册用户可领取
$can_get_red_packet = 1;
}
$can_get_red_packet = 0;
if ($user->type == 'marriage') {
return $this->success('ok', compact('can_get_temp_member', 'is_profile', 'can_get_red_packet'));
}
if ($user->rank_id != 0) {
return $this->success('ok', compact('can_get_temp_member', 'is_profile', 'can_get_red_packet'));
}
$profile = ProfileCourtship::where('user_id', $user_id)->first();
if (!$user->sex || !$profile->birthday || !$profile->province || !$profile->city || !$profile->state || !$user->belief) {
$is_profile = 0;
return $this->success('ok', compact('can_get_temp_member', 'is_profile', 'can_get_red_packet'));
}
$temp_member = TempMember::where('user_id', $user_id)->count();
if ($temp_member) {
$can_get_temp_member = 0;
} else {
$can_get_temp_member = 1;
}
return $this->success('ok', compact('can_get_temp_member', 'is_profile', 'can_get_red_packet'));
}
public function getTempMember($user_id = 0)
{
if (empty($user_id)) {
$user_id = auth()->id();
}
$user = User::find($user_id);
if ($user->type == 'marriage') {
return $this->failure('介绍人不能领取');
}
$profile = ProfileCourtship::where('user_id', $user_id)->first();
if (!$user->sex || !$profile->birthday || !$profile->province || !$profile->city || !$profile->state || !$user->belief || !$profile->max_age || !$profile->min_age) {
return $this->fail('请先完善个人资料领取爱心红包最高10元!', 3, 'pages/users/userInfo', '这就去', '请先完善个人资料领取爱心红包最高10元!');
}
$temp_member = TempMember::where('user_id', $user_id)->count();
if (empty($temp_member)) {
TempMember::create([
'user_id' => $user_id,
'status' => 0,
]);
$user->temp_member = 1;
$user->save();
}
return $this->success('ok');
}
/**
* 阿里云三要素认证(姓名+手机号+身份证)
* @param [type] $name [description]
* @param [type] $mobile [description]
* @param [type] $card_num [description]
* @return [type] [description]
*/
public function aliCheckInfo($name, $mobile, $card_num)
{
//appcode ad41385e76184cffab0a5dc7654f8db2
//AppKey24577465 AppSecretf0692206dab320b431eec0ac5825dc6a
$host = "https://mobilecert.market.alicloudapi.com";
$path = "/safrv_cert_phone_check";
$method = "GET";
$appcode = "ad41385e76184cffab0a5dc7654f8db2";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$param = [
'__userId' => '35102108',
'verifyKey' => 'IV9DIyZ52DsOUC',
'extData' => [
"validator_attr_input_phone" => $mobile,
"validator_attr_user_name" => $name,
"validator_attr_card_num" => $card_num
],
'customerID' => '1',
];
$serviceParameters = json_encode($param);
$querys = "serviceParameters=" . $serviceParameters;
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$" . $host, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
return curl_exec($curl);
}
public function aliCheckInfoV2($user_id, $name, $card_num)
{
$host = "https://safrvcert.market.alicloudapi.com";
$path = "/safrv_2meta_id_name/";
$method = "GET";
$appcode = "ad41385e76184cffab0a5dc7654f8db2";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
$__userId = "35102108";
$customerID = $user_id;
$identifyNum = $card_num;
$userName = Str::trimall($name);
$verifyKey = "IV9DIyZ52DsOUC";
$querys = "__userId=" . $__userId . "&customerID=" . $customerID . "&identifyNum=" . $identifyNum . "&userName=" . $userName . "&verifyKey=" . $verifyKey;
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$" . $host, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
return curl_exec($curl);
}
/**
* 用户认证
* 赠送一个月市级会员
* 退款推荐人认证费
* @param Request $request [description]
* @return [type] [description]
*/
public function mobileApprove(Request $request)
{
try {
$user = auth()->user();
$blacklist = [42805, 42802, 42801];
if (in_array($user->id, $blacklist)) {
return $this->failure('请进入人工认证,上传手持身份证照!');
}
$name = $request->input('name');
if (empty($name)) {
return $this->failure('请输入真实姓名');
}
$card_num = $request->input('card_num');
if (empty($card_num)) {
return $this->failure('请输入身份证号');
}
// if (empty($user->approve_time)) {
// return $this->failure('无自动认证资格,请通过人工认证');
// }
//是否身份已经验证过
$history = User::where('id', '<>', $user->id)->where('card_num', $card_num)->exists();
if ($history) {
return $this->failure('此身份证已经实名验证过,请使用真实信息!');
}
if ($user->name != $name) {
$user->name = $name;
}
// if ($user->mobile != $mobile) {
// $user->mobile = $mobile;
// }
if ($user->card_num != $card_num) {
$user->card_num = $card_num;
}
$user->save();
// $result = $this->aliCheckInfo($name, $mobile, $card_num);
$result = $this->aliCheckInfoV2($user->id, $name, $card_num);
$result = json_decode($result);
if (empty($result)) {
return $this->failure('服务错误,请重试');
}
if ($user->approve_time > 0) $user->decrement('approve_time', 1);
if ($result->code == 200) {
$bizCode = $result->value->bizCode;
if ($bizCode == 0) {
//添加身份证号
if ($user->card_num && $user->is_approved == 1) {
return $this->failure('已认证');
}
//认证状态
$user->is_approved = 1;
//认证时间
$user->approve_date = date('Y-m-d H:i:s');
$user->save();
//增加认证记录
$history = ApproveHistory::where('user_id', $user->id)->whereIn('status', [0, 1])->first();
if (empty($history)) {
ApproveHistory::create([
'user_id' => $user->id,
'type' => 'name',
'status' => 1,
'from_platform' => $request->from_platform,
]);
} else {
$history->status = 1;
$history->save();
}
//更新出生年月日
$this->cardBirthdayToProfile($user);
//赠送市级会员一个月
// $rank_history = RankHistory::where('user_id', $user->id)->first();
// if (empty($rank_history)) {
// RankHistory::create([
// 'user_id'=>$user->id,
// 'rank_id'=>1,
// 'deadline'=>date('Y-m-d H:i:s', strtotime('+1 month')),
// ]);
// $user->rank_id = 1;
// $user->save();
// }else{
// $this->addUserRank($user->id, 1, 1);
// }
//推荐人退认证费
// $this->orderCon->refundApprove($user->from_openid);
return $this->success('ok', ['name' => $name, 'card_number' => $card_num]);
} else {
return $this->failure($result->message);
}
} else {
$message = explode(':', $result->message);
if (is_array($message) && count($message)) {
if ($message[1] == '参数非法') {
$error = '信息不匹配';
return $this->failure($error);
} elseif ($message[1] != '参数非法') {
return $this->failure($message[1]);
}
}
return $this->failure($result->message);
}
} catch (\Exception $e) {
return $this->failure('认证失败,请稍后再试');
}
}
/**
* 用户认证
* 赠送一个月市级会员
* 退款推荐人认证费
* @param Request $request [description]
* @return [type] [description]
*/
public function approve(Request $request)
{
try {
$user = auth()->user();
$blacklist = [42805, 42802, 42801];
if (in_array($user->id, $blacklist)) {
return $this->failure('请进入人工认证,上传手持身份证照!');
}
$name = $request->input('name');
if (empty($name)) {
return $this->failure('请输入真实姓名');
}
$card_num = $request->input('card_num');
if (empty($card_num)) {
return $this->failure('请输入身份证号');
}
//是否身份已经验证过
$history = User::where('id', '<>', $user->id)->where('card_num', $card_num)->exists();
if ($history) {
return $this->failure('此身份证已经实名验证过,请使用真实信息!');
}
if ($user->name != $name) {
$user->name = $name;
}
if ($user->card_num != $card_num) {
$user->card_num = $card_num;
}
DB::beginTransaction();
$user->save();
$result = $this->aliCheckInfoV2($user->id, $name, $card_num);
$result = json_decode($result);
if (empty($result)) throw new \Exception("认证失败", 1);
if ($result->code == 200) {
$bizCode = $result->value->bizCode;
if ($bizCode == 0) {
//添加身份证号
if ($user->card_num && $user->is_approved == 1) {
DB::rollback();
return $this->failure('已认证');
}
//认证状态
$user->is_approved = 1;
//认证时间
$user->approve_date = date('Y-m-d H:i:s');
$user->save();
//增加认证记录
$history = ApproveHistory::where('user_id', $user->id)->first();
if (empty($history)) {
ApproveHistory::create([
'user_id' => $user->id,
'type' => 'name',
'status' => 1,
'from_platform' => $request->from_platform,
]);
} else {
$history->status = 1;
$history->from_platform = $request->from_platform;
$history->save();
}
//标记邀请
$openid = Wechat::where('user_id', $user->id)->value('openid');
$from_openid = $user->from_openid;
InviteHistory::where('openid', $openid)->where('invite_openid', $from_openid)->update(['is_approved' => 1]);
//更新出生年月日
$this->cardBirthdayToProfile($user);
SendProfileCoin::dispatch($user, $type = "approve")->onQueue('love');
//渠道认证记录
if ($request->from_platform) {
$platform_id = Platform::where('app_id', $request->from_platform)->value('id');
if ($platform_id) {
PlatformBehavior::create([
'user_id' => $user->id,
'platform_id' => $platform_id,
'model' => 'APPROVE'
]);
}
}
DB::commit();
auth()->user()->updateCacheUser('is_approved');
return $this->success('ok', ['name' => $name, 'card_number' => $card_num]);
} else {
DB::rollback();
return $this->failure($result->message);
}
} else {
$message = explode(':', $result->message);
if (is_array($message) && count($message)) {
if ($message[1] == '参数非法') {
$error = '信息不匹配';
DB::rollback();
return $this->failure($error);
} elseif ($message[1] != '参数非法') {
DB::rollback();
return $this->failure($message[1]);
}
}
DB::rollback();
return $this->failure($result->message);
}
} catch (\Exception $e) {
DB::rollback();
$this->getError($e);
return $this->failure('认证失败,请稍后再试');
}
}
public function cardBirthdayToProfile($user)
{
//拿到身份证的出生日期
$result = \CommonUtilsService::checkCardBirhday($user->card_num);
if ($result['error'] != 2) {
return;
}
$birthday = $result['tdate'];
if ($user->type == 'single') {
$user->profileCourtship->birthday = $birthday;
$user->profileCourtship->save();
} else {
$user->profileMarriage->birthday = $birthday;
$user->profileMarriage->save();
}
return;
}
/**
* 实人认证
*/
public function approveFace(Request $request)
{
$name = $request->input('name');
if (empty($name)) {
return $this->failure('请输入真实姓名');
}
$card_num = $request->input('card_num');
if (empty($card_num)) {
return $this->failure('请输入身份证号');
}
$face_type = $request->input('face_type', 'h5');
if ($face_type == 'h5') {
$res = $this->userCon->h5Face(auth()->id(), $name, $card_num);
} elseif ($face_type == 'mp') {
$res = $this->userCon->mpFace(auth()->id(), $name, $card_num);
}
return $this->success('ok', $res);
}
public function faceNotify(Request $request)
{
$data = $request->all();
if (isset($data['data']) && $data['data']) {
$result = json_decode($data['data']);
$status = $result->status;
$verify_result = $result->verify_result;
$error_message = null;
if (property_exists($verify_result, "error_message")) {
$error_message = $verify_result->error_message;
};
$biz_no = $result->biz_info->biz_no;
$biz_id = $result->biz_info->biz_id;
$result = $result->liveness_result->result;
$detail = $data['data'];
$history = FaceIdHistory::where('biz_no', $biz_no)->first();
if ($history) {
$history->update([
'status' => $status,
'error_message' => $error_message,
'biz_id' => $biz_id,
'result' => $result,
'detail' => $detail,
]);
if ($status == 'OK' && $result == "PASS") {
User::where('id', $history->user_id)->update(['is_real_approved' => 1]);
}
}
}
return $this->success('ok', $request->all());
}
/**
* 好友问题列表
* @param Request $request [description]
* @return [type] [description]
*/
public function friendQuestionList(Request $request)
{
$questions = FriendQuestion::all();
return $this->success('ok', $questions);
}
public function import()
{
$result = Excel::import(new UsersImport, 'user.xlsx');
// dd($result);
return $this->success('ok');
}
/**
* 申请约见
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function appointPlan(Request $request, $user_id)
{
$user = auth()->user();
$other_user = User::findOrFail($user_id);
//判断是否有约见次数
$history = AppointmentHistory::where('user_id', $user->id)->where('num', '>', 0)->where('type', 'active')->first();
if (empty($history)) {
return $this->failure('请购买约见服务');
}
//生成与人约见记录
$plan = new AppointmentPlan();
$plan->user_id = $user->id;
$plan->other_user_id = $other_user->id;
$plan->status = 0;
$plan->save();
//消耗一次
if (!empty($history) && !empty($history->num)) {
$history->decrement('num', 1);
}
//通知对方与管理员
$message = '用户' . $user->name . '约见用户' . $other_user->name . '一次';
$this->sms->sentMessage('18898888797', $message);
$this->sms->sentMessage('18682191714', $message);
$other_message = '用户' . $user->name . '对你感兴趣,想与你见面进一步互相了解。';
$this->sms->sentMessage($other_user->mobile, $message);
return $this->success('ok');
}
/**
* 邀请好友列表
* @param Request $request [description]
* @return [type] [description]
*/
public function userInviteHistories(Request $request)
{
$user = auth()->user();
if ($user->rank_id == 0) {
$user->rank_id = 1;
RankHistory::create([
'rank_id' => 1,
'user_id' => $user->id,
]);
$user->save();
}
$openid = $this->getOpenid();
$histories = InviteHistory::where('invite_openid', $openid)->where('status', 0)->orderBy('is_approved', 'asc')->orderBY('id', 'desc')->get();
foreach ($histories as $history) {
$wechat = Wechat::where('openid', $history->openid)->select('openid', 'nickname', 'user_id', 'avatar')->first();
if (empty($wechat)) {
$history->status = 1;
$history->save();
continue;
}
$other_user = User::where('id', $wechat->user_id)->select('id', 'name')->first();
if ($other_user) {
$wechat->nickname = $other_user->name;
}
$history->wechat = $wechat;
}
//成功邀请人数
$success_count = InviteHistory::where('invite_openid', $openid)->where('status', 0)->count();
//剩余人数
//当前等级
if ($user->rank_id == 1) {
if ($success_count >= 2) {
$remain_amount = 0;
} else {
$remain_amount = 2 - $success_count;
}
} elseif ($user->rank_id == 2) {
if ($success_count >= 3) {
$remain_amount = 0;
} else {
$remain_amount = 3 - $success_count;
}
} elseif ($user->rank_id == 3) {
if ($success_count >= 5) {
$remain_amount = 0;
} else {
$remain_amount = 5 - $success_count;
}
}
$deadline = RankHistory::where('user_id', $user->id)->where('rank_id', $user->rank_id)->whereNotNull('deadline')->orderBy('deadline', 'desc')->value('deadline');
$user->deadline = $deadline;
return $this->success('ok', compact('histories', 'success_count', 'remain_amount', 'user'));
}
/**
* 用户分享列表
*/
public function userInviteHistoriesV2(Request $request)
{
$user = auth()->user();
// $users = User::where('from_openid', $user->wechat->openid);
// $user_ids = InviteHistory::where('invite_openid', $user->wechat->openid)->whereNotNull('user_id')->pluck('user_id')->toArray();
$user_id = $user->id;
$openid = $user->wechat->openid;
$users = User::where(function ($query) use ($user_id, $openid) {
$query->where('from_openid', $openid)->orWhere('from_user_id', $user_id);
});
$keyword = $request->input('keyword');
if ($keyword) {
$users = $users->where('nickname', 'like', '%' . $keyword . '%');
}
$users = $users
->orderBy('created_at', 'desc')
->select('id', 'nickname', 'name', 'type', 'photo', 'nickname', 'sex', 'is_approved', 'rank_id', 'from_openid', 'created_at')->paginate();
foreach ($users as $user) {
$wechat = $user->wechat;
if ($wechat) {
$user->photo = $user->photo ?: ($user->wechat->avatar2 ?: $user->wechat->avatar);
}
}
return $this->success('ok', $users);
}
/**
* 未标识的邀请人数
*/
public function remainIviteHistoryCount()
{
$data = $this->shareData();
$user = auth()->user();
//未领取数
$remain_count = InviteHistory::where('invite_openid', $user->wechat->openid)->where('status', 0)->count() ?: 0;
$total_count = InviteHistory::where('invite_openid', $user->wechat->openid)->count() ?: 0;
$register_time = $user->created_at->toDateTimeString();
if ($remain_count) {
foreach ($data as $key => $field) {
if ($remain_count >= $data[$key]['num']) {
$data[$key]['enable'] = 1;
$invite_histories = InviteHistory::where('invite_openid', $user->wechat->openid)->where('status', 0)->orderBy('id', 'asc')->limit($data[$key]['num'])->get()->toArray();
$last_invite = $invite_histories[$data[$key]['num'] - 1];
$data[$key]['created_at'] = ($last_invite['created_at']);
}
}
}
if ($user->id == 665) {
$total_count = 200;
$remain_count = 188;
$data = [
'first' => ['num' => 1, 'day' => 1, 'enable' => 0, 'created_at' => '2020-02-01 16:05:46'],
'second' => ['num' => 3, 'day' => 7, 'enable' => 0, 'created_at' => '2020-02-01 20:34:46'],
'third' => ['num' => 5, 'day' => 15, 'enable' => 0, 'created_at' => '2020-02-01 23:23:06'],
'fourth' => ['num' => 10, 'day' => 30, 'enable' => 0, 'created_at' => '2020-02-05 15:03:45'],
];
}
return $this->success('ok', compact('remain_count', 'register_time', 'data', 'total_count'));
}
public function shareData()
{
$data = [
'first' => ['num' => 1, 'day' => 1, 'enable' => 0, 'created_at' => null],
'second' => ['num' => 3, 'day' => 7, 'enable' => 0, 'created_at' => null],
'third' => ['num' => 5, 'day' => 15, 'enable' => 0, 'created_at' => null],
'fourth' => ['num' => 10, 'day' => 30, 'enable' => 0, 'created_at' => null],
];
return $data;
}
/**
* 分享领取会员
*/
public function getInviteSuperRank(Request $request, $serial_number)
{
$data = $this->shareData();
$result = $data[$serial_number];
$user = auth()->user();
//未领取数
$remain_count = InviteHistory::where('invite_openid', $user->wechat->openid)->where('status', 0)->count() ?: 0;
if ($remain_count < $result['num']) {
return $this->failure('兑换失败,需要请更多新用户注册!');
}
$day = $result['day'];
try {
\DB::beginTransaction();
$user->addSuperRank($day);
//更新分享记录
$invite_histories = InviteHistory::where('invite_openid', $user->wechat->openid)->where('status', 0)->orderBy('id', 'asc')->limit($result['num'])->update(['status' => 1]);
\DB::commit();
} catch (Exception $e) {
\DB::rollBack();
return $this->failure('兑换失败');
}
return $this->success('兑换成功');
}
/**
* 提醒对方认证
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function remindUserApprove(Request $request, $user_id)
{
$myUser = auth()->user();
$user = User::find($user_id);
if (empty($user)) {
return $this->failure('用户不存在');
}
$message = '用户' . $myUser->name . '提醒您进行福恋小程序实名认证';
$m = Message::where('phone', $user->mobile)->where('message', $message)->where('created_at', '>', date('y-m-d', time()))->first();
if (empty($m)) {
$this->sms->sentMessage($user->mobile, $message);
}
return $this->success('ok');
}
public function updateUserPhoto(Request $request)
{
try {
$user_id = auth()->id();
$user = User::with('wechat')->findOrFail($user_id);
$photo = $request->input('photo');
if (empty($photo) || !is_string($photo)) {
return $this->failure('请上传头像');
}
//内容安全-图片
$result = \CommonUtilsService::imageContentCecurity([$photo]);
if ($result && isset($result['result']) && $result['result']) {
return $this->failure('图片' . $result['result'] . ',请换一张照片');
}
// //人脸识别
// $result = $this->userCon->faceDelectBaiDu($photo);
// $res = $this->userCon->checkPhotoResult($result);
// if (empty($res)) throw new \Exception("图片分析失败", 1);
// if (is_array($res) && $res['code']) {
// //增加错误头像记录
// ErrorPhoto::firstOrCreate(['user_id' => $user_id, 'photo' => $photo, 'error_msg' => $res['msg']]);
// if ($res['msg'] == "pic not has face") return $this->failure('图片上传失败,可能未获取到人脸,请换一张照片');
// if ($res['msg'] == "image download fail") return $this->failure('图片解析失败,请重新上传');
// if ($res['msg'] != 'Open api daily request limit reached') {
// \Log::info($res);
// return $this->failure($res['msg']);
// }
// }
$result = 1;
if ($request->input('photo') && $request->photo != $user->photo) {
// $face_list = $result->result->face_list;
$user->photo = $request->photo;
$user->app_avatar = $request->photo;
$user->wechat->avatar2 = $request->photo;
$user->circle_avatar = null;
$user->my_share = null;
$user->home_share = null;
$user->is_audited = 0;
$user->is_photo_audited = 0;
// $user->is_photo_audited = 1;
// $user->face_score = $face_list[0]->beauty;
$user->save();
$user->wechat->save();
// //创建百度图片信息
// $this->userCon->addImageInfo($user, $user->photo, $face_list[0]);
// $user->updateCacheUser('photo');
// $user->updateCacheUser('app_avatar');
//
// FaceMatchJob::dispatch($user->id)->onQueue('love');
// //同步IM头像
// $birthday = $user->profileCourtship ? $user->profileCourtship->birthday : null;
// $im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
// $result = $im_service->updateUinfo($user->id, $user->nickname, $user->app_avatar, $sign = '', $user->email, $birthday, $user->mobile, $user->sex);
}
return $this->success('OK', $result);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('头像上传失败,请稍后再试');
}
}
/**
* 行业
* @return [type] [description]
*/
public function industries()
{
$industries = Industry::with('subIndustry')->get()->toArray();
return $this->success('industries', $industries);
}
/**
* 上传生活照
* @param Request $request [description]
* @return [type] [description]
*/
public function uploadProfilePhoto(Request $request)
{
$photos = $request->input('photos', []);
//内容安全-图片
$result = \CommonUtilsService::imageContentCecurity($photos);
if ($result && isset($result['result']) && $result['result']) {
return $this->failure('图片' . $result['result'] . ',请换一张照片');
}
$arr = [];
if (count($photos)) {
foreach ($photos as $photo) {
if (empty($photo)) {
continue;
}
$photo_obj = new ProfilePhoto();
$photo_obj->photo = $photo;
$photo_obj->user_id = auth()->id();
$photo_obj->dateline = date('Y-m-d');
$photo_obj->save();
$arr[] = $photo_obj;
}
SendProfileCoin::dispatch(auth()->user(), $type = "profile_photo")->onQueue('love');
}
return $this->success('ok', $arr);
}
/**
* 上传生活照
* @param Request $request [description]
* @return [type] [description]
*/
public function officialUploadProfilePhoto(Request $request)
{
ProfilePhoto::where('user_id', auth()->id())->delete();
$photos = $request->input('photos', []);
if (count($photos)) {
foreach ($photos as $photo) {
if (empty($photo)) {
continue;
}
$photo_obj = new ProfilePhoto();
$photo_obj->photo = $photo;
$photo_obj->user_id = auth()->id();
$photo_obj->dateline = date('Y-m-d');
$photo_obj->save();
}
}
return $this->success('ok');
}
/**
* 生活照列表
* @param Request $request [description]
* @return [type] [description]
*/
public function profilephotos(Request $request, $user_id = null)
{
if (empty($user_id)) {
$user_id = auth()->id();
}
$date = ProfilePhoto::where('user_id', $user_id)->distinct('dateline')->orderBy('created_at', 'desc')->pluck('dateline');
$array = [];
foreach ($date as $da) {
$arr['time'] = $da;
$photos = ProfilePhoto::where('user_id', $user_id)->where('dateline', $da)->orderBy('id', 'desc')->get();
$arr['photos'] = $photos;
$array[] = $arr;
}
return $this->success('ok', $array);
}
/**
* 删除图片
* @param Request $request [description]
* @return [type] [description]
*/
public function deleteProfilePhoto(Request $request, $id)
{
$photo_obj = ProfilePhoto::find($id);
if ($photo_obj) {
$photo_obj->delete();
}
return $this->success('ok');
}
/**
* 修改狀態
* @param Request $request [description]
* @return [type] [description]
*/
public function changeUserType(Request $request)
{
$user = auth()->user();
$type = $request->input('type');
if ($user->type == 'marriage' && $type != 'marriage') {
return $this->failure('已婚状态下暂不支持修改状态,请联系客服!');
}
$court = ProfileCourtship::where('user_id', $user->id)->first();
$marriage = ProfileMarriage::where('user_id', $user->id)->first();
if ($user->type == 'single') { //如果你是单身
if ($type == 'loveing' || $type == 'marriage') {
$sex = $user->sex;
if (!empty($court)) {
$belief = $court->belief;
$birthday = $court->birthday;
$company = $court->company;
$province = $court->province;
$city = $court->city;
} else {
$belief = '其他';
$birthday = '';
$company = '';
$province = null;
$city = null;
}
if (empty($marriage)) {
$user->profileMarriage()->create(['sex' => $sex, 'belief' => $belief, 'birthday' => $birthday, 'province' => $province, 'city' => $city]);
} else {
$user->profileMarriage()->update(['sex' => $sex, 'belief' => $belief, 'birthday' => $birthday, 'province' => $province, 'city' => $city]);
}
}
} elseif ($user->type == 'loveing') {
if ($type == 'single') {
$sex = $user->sex;
if (!empty($marriage)) {
$belief = $marriage->belief;
$birthday = $marriage->birthday;
$company = $marriage->company;
$province = $marriage->province;
$city = $marriage->city;
} else {
$belief = '其他';
$birthday = '';
$company = '';
$province = null;
$city = null;
}
if (empty($court)) {
$user->profileCourtship()->create(['sex' => $sex, 'belief' => $belief, 'birthday' => $birthday, 'province' => $province, 'city' => $city]);
} else {
$user->profileCourtship()->update(['sex' => $sex, 'belief' => $belief, 'birthday' => $birthday, 'province' => $province, 'city' => $city]);
}
}
}
$user->type = $type;
$user->save();
return $this->success('ok');
}
/**
* 地址列表
* @param Request $request [description]
* @return [type] [description]
*/
public function addresses(Request $request)
{
$addresses = Address::orderBy('codeId', 'asc')->get()->toArray();
$data = $this->addressSort($addresses);
return $this->success('ok', $data);
}
public function addressesV2(Request $request)
{
$cache_name = 'love_address';
if (Cache::has($cache_name)) {
$data = Cache::get($cache_name);
} else {
$addresses = Address::where('name', '<>', '不限')->orderBy('codeId', 'asc')->get()->toArray();
$data = $this->addressSort($addresses);
Cache::forever($cache_name, $data);
}
return $this->success('ok', $data);
}
public function addressesV3(Request $request)
{
$addresses = Address::where('parentId', 2)->where('id', '<>', 3762)->orderBy('codeId', 'asc')->get()->toArray();
$item['name'] = '不限';
foreach ($addresses as &$address) {
$son = Address::where('parentId', $address['codeId'])->get()->toArray();
array_unshift($son, $item);
$address['son'] = $son;
}
return $this->success('addresses', $addresses);
}
public function getSonAddress(Request $request)
{
$code_id = $request->code_id;
if(config('app.debug')) {
if (!$code_id) {
return $this->failure('id不能为空值');
}
}
$result = Address::where('name','!=','不限')->where('name','!=','市辖区')->where('parentId',$code_id)->withTrashed()->get()->toArray();
return $this->success('ok',$result);
}
public function addressesV4(Request $request)
{
$addresses = Address::where('parentId', 2)->where('name', '<>', '不限')->where('id', '<>', 3762)->orderBy('codeId', 'asc')->get()->toArray();
foreach ($addresses as &$address) {
$son = Address::where('parentId', $address['codeId'])->where('name', '<>', '不限')->get()->toArray();
$address['son'] = $son;
}
return $this->success('addresses', $addresses);
}
public function searchUsers(Request $request)
{
$users = User::orderBy('id', 'desc');
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%');
});
}
$users = $users->select('name', 'circle_avatar', 'sex', 'mobile', 'type', 'id')->paginate();
return $this->success('ok', $users);
}
public function ranksV3(Request $request)
{
$ranks = Rank::where('is_show', 1)->get();
return $this->success('ok', $ranks);
}
/**
* 超级会员
* 改版后三合一
*/
public function superRank(Request $request)
{
$rank = Rank::with(['subRanks' => function ($query) {
$query->where('is_show_mini', 1);
}])->where('name', '超级会员')->first();
if (!empty($rank)) {
$rank->explain = json_decode($rank->explain);
$rank->feature = json_decode($rank->feature);
}
return $this->success('ok', $rank);
}
/**
* 超级会员
* 改版后三合一
*/
public function superRankTest(Request $request)
{
$rank = Rank::with(['subRanks' => function ($query) {
$query->where('is_show_mini', 1);
}])->where('name', '超级会员')->first();
if (!empty($rank)) {
$rank->explain = json_decode($rank->explain);
$rank->feature = json_decode($rank->feature);
}
//添加测试会员数据
//$test_rank = SubRank::where('name', '测试')->first();
//$rank->subRanks[] = $test_rank;
return $this->success('ok', $rank);
}
/**
* 查询访客记录 版本2
* 黄宾棠
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\View\View
*/
public function previewHistroiesV2(Request $request)
{
$user_id = auth()->id();
$user = auth()->user();
$user->cacheUser();
$size = $request->input('size',15);
$histories = UserPreviewHistory::with('previewUser:id,nickname,name,photo,circle_avatar,app_avatar,sex,type,hidden_profile,is_photo_audited')
->with('profileCourtship:province,city,birthday,user_id,stature')
->with('profileMarriage:province,city,birthday,user_id')
->whereHas('previewUser', function($sql){
$sql->where('hidden_profile', '<>', 'ALLSEX');
})->where('user_id', $user_id)->where('is_hidden', 0)
->select(DB::raw('max(id) as some_id, count(*) as count, id, user_id, preview_user_id,is_hidden, max(created_at) as created_at'))
->orderBY('some_id', 'desc')
->groupBy('preview_user_id');
$histories = $histories->whereHas('user', function ($sql) {
$sql->where('hidden_profile', '!=','ALLSEX');
});
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$histories = $histories->whereHas('user', function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%');
});
}
$histories = $histories->paginate($size);
foreach ($histories as $history) {
$user = $history->previewUser;
$profile = $user->type == 'single' ? $history->profileCourtship : $history->profileMarriage;
$user->province = !empty($profile) ? $profile->province : '无';
$user->city = !empty($profile) ? str_replace('市', '', $profile->city) : '无';
$user->year = !empty($profile) ? substr($profile->birthday, 2, 2) . '年' : '未填写';
$user->stature = !empty($profile) && $profile->stature? $profile->stature.'cm' : '未填写';
$history->other_user = $user;
unset($history->previewUser);
}
//更新查看
UserPreview::where('user_id', $user_id)->where('status', 0)->update(['status' => 1]);
return $this->success('ok', $histories);
}
public function userPreviewHistories(Request $request, $preview_user_id)
{
$user_id = auth()->id();
$user = auth()->user();
$user->cacheUser();
$size = $request->input('size',15);
$histories = UserPreviewHistory::with('previewUser:id,nickname,name,photo,circle_avatar,app_avatar,sex,type,hidden_profile')
->with('profileCourtship:province,city,birthday,user_id,stature')
->with('profileMarriage:province,city,birthday,user_id')
->whereHas('previewUser')->where('user_id', $user_id)->where('preview_user_id', $preview_user_id)->where('is_hidden', 0)
->select(DB::raw( 'id, user_id, preview_user_id,is_hidden, created_at'))
->orderBY('created_at', 'desc');
$histories = $histories->whereHas('user', function ($sql) {
$sql->where('hidden_profile', '!=','ALLSEX');
});
$histories = $histories->paginate($size);
foreach ($histories as $history) {
$user = $history->previewUser;
$profile = $user->type == 'single' ? $history->profileCourtship : $history->profileMarriage;
$user->province = !empty($profile) ? $profile->province : '无';
$user->city = !empty($profile) ? str_replace('市', '', $profile->city) : '无';
$user->year = !empty($profile) ? substr($profile->birthday, 2, 2) . '年' : '未填写';
$user->stature = !empty($profile) && $profile->stature? $profile->stature.'cm' : '未填写';
$history->other_user = $user;
unset($history->previewUser);
}
return $this->success('ok', $histories);
}
//刪除访问记录
public function removePreviewHistory(Request $request){
try {
$mine = auth()->user();
$user_id = $request->user_id;
UserPreview::where('preview_user_id',$user_id)->where('user_id',$mine->id)->delete();
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('操作失败,请稍后再试');
}
}
// 删除访问记录
public function delAccessRecord(Request $request)
{
$user = auth()->user();
$result = UserPreview::where('id',$request->id)->first();
if(!$result)
return $this->failure('该记录不存在');
if($result->user_id!=$user->id)
return $this->failure('操作失败,请稍后再试。');
$result->delete();
return $this->success('操作成功');
}
/** 我的访问 */
public function myPreviewHistroies(Request $request){
$user = auth()->user();
$user_id = $user->id;
$user->cacheUser();
$size = $request->input('size',15);
$histories = UserPreview::with('otherpreviewUser:id,nickname,name,photo,circle_avatar,app_avatar,sex,type,age,hidden_profile')
->whereNotNull('preview_time')
->with('otherProfileCourtship:province,city,birthday,user_id')
->with('otherProfileMarriage:province,city,birthday,user_id')
->whereHas('otherpreviewUser', function ($sql) {
// $sql->where('hidden_profile', '<>', 'ALLSEX')/*->whereIn('type', $types)*/;
})->where('preview_user_id', $user_id)
->orderBY('preview_time', 'desc');
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$histories = $histories->whereHas('user', function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%');
});
}
$histories = $histories->paginate($size);
foreach ($histories as $history) {
$user = $history->otherpreviewUser;
$u_id = $history->preview_user_id;
$history->preview_user_id = $history->user_id;
$history->user_id = $u_id;
$profile = $user->type == 'single' ? $history->otherProfileCourtship : $history->otherProfileMarriage;
$user->province = !empty($profile) ? $profile->province : '无';
$user->city = !empty($profile) ? str_replace('市', '', $profile->city) : '无';
$user->year = !empty($profile) ? substr($profile->birthday, 2, 2) . '年' : '未填写';
$history->other_user = $user;
$history->preview_user = $history->otherpreviewUser;
$history->profile_courtship = $history->otherProfileCourtship;
$history->profile_marriage = $history->otherProfileMarriage;
unset($history->otherpreviewUser,$history->otherProfileCourtship,$history->otherProfileMarriage);
}
//更新查看
UserPreview::where('user_id', $user_id)->where('status', 0)->update(['status' => 1]);
return $this->success('ok', $histories);
}
/**
* 對所有人隐身
* @return [type] [description]
*/
public function hidden($other_user_id = null)
{
try {
$user = auth()->user();
if($user->hidden){
$this->userCon->userHidden(auth()->id(), $other_user_id);
}else if($user->rank_id == 9){
$this->userCon->userHidden(auth()->id(), $other_user_id);
}else{
return $this->failure('该功能目前仅限VIP');
}
return $this->success('ok');
} catch (\Exception $e) {
return $this->failure('操作失败,请稍后再试');
}
}
//修改来访通知状态
public function updateVisitNotice() {
$user = auth()->user();
if ($user->visit_notice) {
$user->visit_notice = 0;
}else {
$user->visit_notice = 1;
}
$user->save();
return $this->success('ok', ['visit_notice'=>$user->visit_notice]);
}
/**
* 问题反馈
* @param Request $request [description]
* @return [type] [description]
*/
public function feedback(Request $request)
{
$content = $request->input('content');
$photos = $request->input('photos', []);
$type = $request->input('type', 'other');
$value = FeedbackHistory::where('user_id',auth()->id())->whereNotNull('star')->where('address','home')->where('created_at','>','2022-07-07 00:00:00')->first();
if($value) return $this->success('ok');
if($request->has('address') && $request->address == 'home'){
if(empty($content)) return $this->failure('请选择要提升的技能');
}
if ($type == 'product' || $type == 'order') {
if(empty($content)){
return $this->failure('请输入反馈内容');
}
}
if($type == 'team'){
if(!empty($request->star) || empty($photos)){
return $this->failure('请提供反馈截图');
}
}
if($type == 'other'){
if(!empty($request->star) && empty($request->address)){
return $this->failure('请提供反馈地址');
}
if(!empty($request->address) && empty($request->star)){
return $this->failure('请提供反馈星级');
}
}
$this->userCon->feedback($request, auth()->id());
return $this->success('ok');
}
/**
* 修改隐藏信息状态
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function changeHiddenProfile(Request $request)
{
$this->userCon->changeHiddenProfile($request);
return $this->success('ok');
}
public function hiddenProfileOptions(Request $request)
{
$options = [
['id'=>'1', 'text'=>'已经在福恋找到伴侣了'],
['id'=>'2', 'text'=>'通过其它方式找到伴侣了'],
['id'=>'3', 'text'=>'被婚托,酒托骚扰'],
['id'=>'4', 'text'=>'人少,看来看去就那么几个'],
['id'=>'5', 'text'=>'想要找的意中人太少'],
['id'=>'6', 'text'=>'其它原因'],
];
return $this->success('ok', compact('options'));
}
/**
* 人脸识别
* @param Request $request [description]
* @return [type] [description]
*/
public function faceDelect(Request $request)
{
$img_url = $request->input('img_url');
$result = $this->faceDelectDetail($img_url);
return $result;
}
public function faceDelectDetail($img_url)
{
$result = $this->userCon->faceDelectBaiDu($img_url);
if (empty($result->result)) {
return $this->failure('图片无法识别,请上传个人真实正面照片');
}
return $this->success('ok', $result);
}
/**
* 平台注册填写资料
* @return [type] [description]
*/
public function updateUserProfile(Request $request)
{
$photo = $request->input('photo');
if ($photo) {
$result = $this->userCon->faceDelectBaiDu($photo);
if (empty($result->result)) {
$photo = null;
}
}
if ($request->has('name')) {
$name = $request->input('name');
if (empty($name)) {
return $this->failure('请输入姓名');
}
$sex = $request->input('sex');
if (empty($sex)) {
return $this->failure('请选择性别');
}
$birthday = $request->input('birthday');
if (empty($birthday)) {
return $this->failure('请选择出生日期');
}
$belief = $request->input('belief');
if (empty($belief)) {
return $this->failure('请选择信仰');
}
$type = $request->input('type');
if (empty($type)) {
return $this->failure('请选择注册类型');
}
$user = auth()->user();
$user->name = $name;
$user->type = $type;
$user->sex = $sex;
$user->photo = $photo;
$user->belief = $belief;
$user->save();
}
$this->userCon->updateProfile($request);
return $this->success('ok');
}
/**
* 聊天数
* @param Request $request [description]
*/
public function noticeNum(Request $request)
{
$status = $request->input('status', 0);
$chat_message_num = $this->userCon->chatMessageNum($status);
$notice_num = $this->userCon->noticeNum($status);
return $this->success('ok', compact('chat_message_num', 'notice_num'));
}
/**
* 我的
*/
public function officialMine(Request $request)
{
$user = $this->userCon->officialMine();
$paas = $request->input('paas');
$paas_obj = (object)null;
if (!empty($paas) && $paas != 'null') {
$paas_obj = Paas::where('name', $paas)->first();
}
$user->paas_obj = $paas_obj;
return $this->success('ok', $user);
}
/**
* 聊天消息列表
*/
public function officialMessageLinkmanList(Request $request)
{
$result = $this->userCon->officialMessageLinkmanList();
return $this->success('ok', $result);
}
/**
* 用户详情
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function officialUser(Request $request, $user_id)
{
$paas_official_openid = $request->session()->get('paas_official_openid');
$subscribe = 0;
$qrcode_url = null;
$paas_name = Cache::get('paas_name');
if ($paas_name && $paas_official_openid) {
//获取对应微信信息
$lower_paas_name = strtolower($paas_name);
$app = \EasyWeChat::officialAccount($lower_paas_name);
$wechat_user = $app->user->get($paas_official_openid);
$result = $app->qrcode->temporary('foo', 6 * 24 * 3600);
$qrcode_url = $app->qrcode->url($result['ticket']);
$subscribe = array_key_exists('subscribe', $wechat_user) ? $wechat_user['subscribe'] : 0;
}
$user = $this->userCon->officialUser($user_id);
if (empty($user)) {
return $this->failure('用户不存在');
}
$user->subscribe = $subscribe;
$user->qrcode_url = $qrcode_url;
return $this->success('ok', $user);
}
/**
* 添加好友
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function officailAddFriend(Request $request, $user_id)
{
$user = auth()->user();
//是否禁言
$banned = $user->isBanned('friend');
if ($banned) {
return $this->failure('您已被禁言,时间:' . $banned->start_time . '至' . $banned->end_time);
}
$this->userCon->officailAddFriend($user_id);
return $this->success('ok');
}
/**
* 聊天联系人
* @param Request $request [description]
* @return [type] [description]
*/
public function officialMessageLinkmen(Request $request)
{
$linkmen = $this->userCon->officialMessageLinkmen($request);
return $this->success('ok', $linkmen);
}
/**
* 用户资料
* @param Request $request [description]
* @return [type] [description]
*/
public function officialUserProfile(Request $request)
{
$profile = $this->userCon->officialUserProfile();
return $this->success('ok', $profile);
}
/**
* 生活照
* @param Request $request [description]
* @return [type] [description]
*/
public function officailUserPhotos(Request $request)
{
$photos = $this->userCon->lifePhotos(auth()->id(), 0, 'asc');
return $this->success('ok', $photos);
}
public function officialDeleteProfilePhoto(Request $request)
{
$photo = $request->input('photo');
$photo_obj = ProfilePhoto::where('photo', $photo)->first();
if ($photo_obj) {
$photo_obj->delete();
}
return $this->success('ok');
}
/**
* 上传头像
* @param Request $request [description]
* @return [type] [description]
*/
public function updateOfficialUserPhoto(Request $request)
{
$user_id = auth()->id();
$user = User::with('wechat')->findOrFail($user_id);
$photo = $request->input('photo');
//人脸识别
$result = $this->userCon->faceDelectBaiDu($photo);
if (empty($result->result)) {
return $this->failure('图片无法识别,请上传个人真实正面照片');
}
// return $this->success('ok', $result);
if ($request->input('photo') && $request->photo != $user->photo) {
$user->photo = $request->photo;
$user->circle_avatar = null;
$user->my_share = null;
$user->home_share = null;
$user->is_audited = 0;
$user->save();
if ($user->wechat) {
$user->wechat->avatar2 = $request->photo;
$user->wechat->save();
}
$face_list = $result->result->face_list;
$this->userCon->addImageInfo($user, $user->photo, $face_list[0]);
}
return $this->success('OK', $result);
}
/**
* 获取微信信息
* @param Request $request [description]
* @return [type] [description]
*/
public function wXBindV2(Request $request)
{
// $is_register = 0;
// $token = null;
$wechat_user = session('wechat.oauth_user.new');
dd($wechat_user);
// $official_openid = $wechat_user['id'];
// $wechat = Wechat::where('official_openid', $official_openid)->first();
// if ($wechat && $wechat->user_id) {//已注册
// $is_register = 1;
// }
// $user = $this->authCheck();
// if ($user) {
// $is_register = 1;
// }
// $from_official_openid = $request->input('from_official_openid');
// $request->session()->put('official_openid', $official_openid);
// $request->session()->put('is_register', $is_register);
// $request->session()->put('from_official_openid', $from_official_openid);
// if (config('app.env') == 'local') {
// return redirect('http://localhost:8080/#/sharePage?from_official_openid='.$from_official_openid);
// }
// return redirect(env('APP_URL').'/mobile/#/sharePage?from_official_openid=' . $from_official_openid);
}
public function communityShare(Request $request, Community $community)
{
$is_register = $request->session()->get('is_register', 0);
//活动是否开始
$data = $this->getRedPacketActivityStatus();
$status = $data['status'];
$start_time = $data['start_time'];
if ($status == 1 && empty($is_register)) {
//缓存人数
$member_count = $this->cacheTotalMember();
if ($member_count >= 100) {
return $this->failure('由于人数过多,请稍后重试');
}
}
$token = null;
$official_openid = $request->session()->get('official_openid');
$from_official_openid = $request->session()->get('from_official_openid');
if (config('app.env') == 'local') {
$official_openid = 'ojvHq5kvZai3mvwc18wx066uUjqk';
}
if (empty($official_openid)) {
// return redirect(env('APP_URL').'/wx/bind/v2?from_official_openid='.$from_official_openid);
return $this->failure('获取微信信息失败,请重新进入!');
}
// $official_openid = $request->input('official_openid');
$app = \WechatService::officialApp();
$user = $app->user->get($official_openid);
if (empty($user) || (isset($user['errcode']) && $user['errcode'] == '40003')) {
return $this->failure('获取的微信信息不正确,请重新进入');
}
//缓存社群
$communities = $this->getCommunities();
return $this->success('ok', compact('communities', 'is_register', 'token', 'official_openid', 'status', 'start_time'));
}
public function cacheTotalMember()
{
if (Cache::has('activity_member_count')) { //已缓存
// $count = Cache::get('activity_member_count');
// if ($count >= 100) {
// return false;
// }
//添加一位
$count = Cache::increment('activity_member_count', 1);
} else {
//存入缓存 缓存时间两分钟
Cache::put('activity_member_count', 1, 1);
$count = Cache::get('activity_member_count');
}
return $count;
}
public function decrementCacheMember()
{
if (Cache::has('activity_member_count')) { //已缓存
//添加一位
$count = Cache::decrement('activity_member_count', 1);
}
return $count;
}
public function getRedPacketActivityStatus()
{
$time = time();
$status = -1;
$activity = RedPacketActivity::orderBy('id', 'desc')->first();
if (empty($activity)) {
$status = -1;
}
$start_time = strtotime($activity->start_time);
$end_time = strtotime($activity->end_time);
if ($time < $start_time) {
$status = 0; //未开始
} elseif ($time >= $start_time && $time <= $end_time) {
$status = 1; //开始
} else {
$status = -1; //结束
}
//判断是否超出金额
if ($activity->used_amount >= $activity->amount) {
$status = -1;
}
$data['status'] = $status;
$data['start_time'] = $start_time;
return $data;
}
public function getCommunities()
{
if (Cache::has('communities')) { //已缓存
//直接获取
$communities = Cache::get('communities');
} else {
//存入缓存
$communities = Community::all();
Cache::put('communities', $communities, 2);
}
return $communities;
}
/**
* 获取红包金额
* @param Request $request [description]
* @return [type] [description]
*/
// public function openRedPacket(Request $request)
// {
// $is_register = $request->session()->get('is_register', 0);
// if ($is_register) {
// $red_amount = 0;
// if ($official_openid) {
// $wechat = Wechat::where('official_openid', $official_openid)->first();
// if ($wechat && $wechat->user_id) {
// $user = User::find($wechat->user_id);
// $token = $user->createToken($user->mobile)->accessToken;
// }
// }
// return $this->failure('该微信账号已经抢过红包');
// } else {
// $red_amount = $this->redPacketAmount();
// $request->session()->put('red_amount', $red_amount);
// return $this->success('ok', compact('red_amount'));
// }
// }
/**
* 红包金额
* @param Request $request [description]
* @return [type] [description]
*/
public function redPacketAmount()
{
$array = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2];
$key = array_rand($array);
$num = $array[$key];
if ($num == 2) {
return 2.00;
}
$amount = $num + mt_rand(0, 9) / 10 + mt_rand(0, 9) / 100;
return $amount;
}
/**
* 绑定手机号
*/
public function wxBindMobile(Request $request)
{
$mobile = $request->input('mobile');
if (empty($mobile)) {
return $this->failure('请输入手机号');
}
//判断手机号正确性
if (!Str::isMobile($mobile)) {
return $this->failure('手机号格式错误,请重新输入');
}
$official_openid = $request->input('official_openid');
if (empty($official_openid)) {
return $this->failure('未获取到微信信息');
}
$wechat = Wechat::where('official_openid', $official_openid)->first();
if ($wechat) {
return $this->failure('该微信已经绑定账号');
}
$code = $request->input('code');
if (empty($code)) {
return $this->failure('请输入验证码');
}
//判断验证码
$result = $this->sms->check($mobile, $code);
if ($result) {
return $this->failure($result);
}
// $red_amount = $request->input('red_amount');
$red_amount = $request->session()->get('red_amount', 1.23);
if (empty($red_amount) || $red_amount == 0) {
return $this->failure('未获取到红包金额, 请重新进入!');
}
if ($red_amount > 7) {
return $this->failure('红包金额有误,请重新进入!');
}
$from_official_openid = $request->input('from_official_openid');
if ($from_official_openid) {
$from_user_id = Wechat::where('official_openid', $from_official_openid)->value('user_id') ?: 0;
} else {
$from_user_id = 0;
}
// return $this->failure('红包已领完,敬请期待下一轮');
//判断手机号是否已注册
$user = User::where('mobile', $mobile)->first();
if ($user) {
$wechat = Wechat::where('user_id', $user->id)->first();
if ($wechat && $wechat->official_openid) {
return $this->failure('手机号已注册,请更新手机号');
}
if (empty($wechat)) {
$wechat = new Wechat();
$wechat->user_id = $user->id;
}
$wechat->official_openid = $official_openid;
$wechat->save();
} else {
//注册
$user = new User();
$user->name = $mobile;
$user->mobile = $mobile;
$user->email = $mobile . '@ufutx.com';
$user->from_user_id = $from_user_id;
$user->from_official_openid = $from_official_openid;
$user->password = bcrypt($mobile);
$user->type = 'marriage';
$user->save();
$wechat = Wechat::firstOrCreate(['official_openid' => $official_openid]);
$wechat->user_id = $user->id;
$wechat->save();
$profile = ProfileMarriage::firstOrCreate(['user_id' => $user->id]);
}
$token = $user->createToken($user->mobile)->accessToken;
//发红包注册人
$order = $this->sendRedPacket($red_amount, $official_openid, $user->id);
if ($order->err_code == 'NOTENOUGH') {
return $this->failure('红包已领完,敬请期待下一轮');
}
$activity = RedPacketActivity::orderBy('id', 'desc')->first();
if ($activity) {
$activity->increment('used_amount', $red_amount);
}
if ($user) {
//发红包分享人
$this->sendRedPacketToSharer($from_official_openid, $user->name);
}
$this->decrementCacheMember();
return $this->success('ok', compact('token'));
}
public function sendRedPacketToSharer($from_official_openid, $user_name)
{
if ($from_official_openid) {
$from_wechat = Wechat::where('official_openid', $from_official_openid)->first();
if (empty($from_wechat)) {
$from_user_name = '';
$from_user_id = 0;
$from_user_mobile = null;
} elseif ($from_wechat && empty($from_wechat->user_id)) {
$from_user_id = 0;
$from_user_name = $from_wechat->nickname;
$from_user_mobile = null;
} elseif ($from_wechat && $from_wechat->user_id) {
$from_user_id = $from_wechat->user_id;
$from_user = User::where('id', $from_wechat->user_id)->first();
$from_user_mobile = $from_user ? $from_user->mobile : null;
$from_user_name = $from_user ? $from_user->name : null;
}
$data = [
'user_name' => $user_name,
'from_official_openid' => $from_official_openid,
'from_user_name' => $from_user_name,
'from_user_id' => $from_user_id,
'from_user_mobile' => $from_user_mobile,
'type' => "SHARE",
];
// CommunityShare::dispatch($data)->onQueue('love');
}
return;
}
public function sendRedPacket($price, $official_openid, $user_id)
{
//发红包
$trade_no = \CommonUtilsService::getTradeNO();
$total_num = 1;
$total_amount = number_format($price, 2, '', '');
$wishing = '福恋一家,有你,有我、有祂!';
$send_name = '来自福恋社群';
$act_name = '福恋社群'; //act_name字段必填,并且少于32个字符.
//生成红包订单
// $order = RedPacketOrder::create([
// 'user_id'=>$user_id,
// 'type'=>'REGISTER',
// 'official_openid'=>$official_openid,
// 'trade_no'=>$trade_no,
// 'amount'=>$price,
// 'is_hooked'=>0,
// ]);
// $result = \WechatService::sendNormalRedPackV2($trade_no, $send_name, $total_amount, $official_openid, $wishing, $act_name, $remark='');
// if (is_array($result)) {//红包发送失败
// $order->err_code = $result['err_code'];//错误代码
// $order->return_msg = $result['return_msg'];//错误信息
// }elseif ($result == true) {
// $order->err_code = 'SUCCESS';
// }else{
// $order->err_code = 'FALSE';
// }
// $order->save();
return ;
}
/**
* 绑定openid
* @param Request $request [description]
* @return [type] [description]
*/
public function wXBind(Request $request)
{
$openid_bind = 0;
$bind_mobile = '';
$mobile = $request->input('mobile');
$wechat_user = session('wechat.oauth_user.new');
$nickname = '';
$sex = '';
$avatar = '';
if ($wechat_user) {
$nickname = isset($wechat_user['nickname']) ? $wechat_user['nickname'] : '';
$sex = isset($wechat_user['sex']) ? $wechat_user['sex'] : '';
$avatar = isset($wechat_user['avatar']) ? $wechat_user['avatar'] : '';
}
$request->session()->put('nickname', $nickname);
$request->session()->put('avatar', $avatar);
if (empty($mobile)) {
$official_openid = $wechat_user['id'];
} else {
$user = User::where('mobile', $mobile)->firstOrFail();
$official_openid = '';
if (!empty($wechat_user)) {
//该微信是否绑定账号
$wechat = Wechat::where('official_openid', $wechat_user['id'])->first();
if ($wechat && $wechat->user_id != $user->id) {
// return $this->failure('该微信已经绑定账号,昵称:'.$wechat->nickname);
$bind_mobile = User::where('id', $wechat->user_id)->value('mobile');
$openid_bind = 1;
} else {
$wechat = Wechat::firstOrCreate(['user_id' => $user->id]);
if ($wechat_user['id'] != 'undefined') {
$wechat->official_openid = $wechat->official_openid ?: $wechat_user['id'];
}
$official_openid = $wechat->official_openid;
if (empty($wechat->nickname)) {
$wechat->nickname = $wechat_user['nickname'];
}
if (empty($wechat->avatar)) {
$wechat->avatar = $wechat_user['avatar'];
}
$wechat->avatar2 = $user->photo;
$wechat->save();
}
}
}
$type = $request->input('type');
if ($type == 'rank') {
return redirect(env('APP_URL').'/mobile/#/upgrade?official_openid=' . $official_openid . '&openid_bind=' . $openid_bind . '&bind_mobile=' . $bind_mobile);
} elseif ($type == 'approve') {
return redirect(env('APP_URL').'/mobile/#/authentication?official_openid=' . $official_openid . '&openid_bind=' . $openid_bind . '&bind_mobile=' . $bind_mobile);
} elseif ($type == 'activity') {
$activity_id = $request->input('activity_id');
return redirect(env('APP_URL').'/mobile/#/activityDetail/' . $activity_id . '?official_openid=' . $official_openid . '&openid_bind=' . $openid_bind . '&bind_mobile=' . $bind_mobile);
} elseif ($type == 'community') {
$community_id = $request->input('id');
$from_user_id = $request->input('from_user_id');
$from_official_openid = $request->input('from_official_openid');
$request->session()->put('official_openid', $official_openid);
$request->session()->put('openid_bind', $openid_bind);
$request->session()->put('from_user_id', $from_user_id);
$request->session()->put('from_official_openid', $from_official_openid);
// return redirect(env('APP_URL').'/mobile/#/wxGroup/'.$community_id.'?official_openid='.$official_openid.'&openid_bind='.$openid_bind.'&bind_mobile='.$bind_mobile.'&avatar='.$avatar.'&nickname='.$nickname.'&sex='.$sex);
return redirect(env('APP_URL').'/mobile/#/communityDetail/' . $community_id . '?official_openid=' . $official_openid . '&openid_bind=' . $openid_bind . '&bind_mobile=' . $bind_mobile . '&from_user_id=' . $from_user_id . '&from_official_openid=' . $from_official_openid . '&community_share=1');
} elseif ($type == 'donation') { //奉献金
return redirect(env('APP_URL').'/mobile/#/givingMoney?official_openid=' . $official_openid . '&openid_bind=' . $openid_bind . '&bind_mobile=' . $bind_mobile);
} elseif ($type == 'appointments') {
return redirect(env('APP_URL').'/mobile/#/loveMate?official_openid=' . $official_openid . '&openid_bind=' . $openid_bind . '&bind_mobile=' . $bind_mobile);
}
}
public function passUser(Request $request, $user_id)
{
$openid = Wechat::where('user_id', $user_id)->value('openid');
if ($user_id == 4655) {
$paas = 'TLLC';
} elseif ($user_id == 5068) {
$paas = 'MYZA';
}
$paas_id = Paas::where('name', $paas)->value("id");
$user_ids = User::where('from_openid', $openid)->pluck('id');
foreach ($user_ids as $user_id) {
PaasUser::firstOrCreate(['user_id' => $user_id, 'paas_id' => $paas_id, 'type' => "MAIN"]);
}
return $this->success('ok');
}
/**
* 消息联系人列表
* @param Request $request [description]
* @return [type] [description]
*/
public function messageLinkmenV2(Request $request)
{
//福恋助手
// $chat = $this->userCon->lastAssistantMessage();
//系统通知
// $notice = $this->userCon->lastNotice();
//最近访问
// $visit = $this->userCon->lastVisit($request);
$chat = null;
$visit = null;
$notice = null;
//联系人
$linkmen = $this->userCon->messageLinkmen($request);
//好友请求数
$friend_count = $this->userCon->systemNoticeCount($type = 'friend') ?: 0;
// //系统消息未读数
$system_count = $this->userCon->systemNoticeCount($type = 'system') ?: 0;
// //关注消息未读数
$follow_count = $this->userCon->systemNoticeCount($type = 'follow') ?: 0;
// //来访未读数
$preview_count = $this->userCon->userPreviewCount()?:0;
//是否真人认证
$my_real_approved = auth()->user()->is_real_approved;
//系统通知
$system_notice = Notice::where(['user_id'=>auth()->id(), 'send_user_id'=>1])->select('content', 'type', 'type_id', 'created_at')->orderByDesc('id', 'desc')->first();
if ($system_notice) {
$system_notice->count = Notice::where(['user_id'=>auth()->id(), 'send_user_id'=>1, 'status'=>0])->count();
}
return $this->success('ok', compact('chat', 'notice', 'linkmen', 'visit', 'friend_count', 'system_count', 'follow_count', 'preview_count', 'my_real_approved','system_notice'));
}
/**
* 消息联系人列表
* @param Request $request [description]
* @return [type] [description]
*/
public function messageLinkmenV3(Request $request)
{
//福恋助手
// $chat = $this->userCon->lastAssistantMessage();
//系统通知
// $notice = $this->userCon->lastNotice();
//最近访问
// $visit = $this->userCon->lastVisit($request);
$chat = null;
$visit = null;
$notice = null;
//联系人
$linkmen = $this->userCon->messageLinkmen($request);
//好友请求数
$friend_count = $this->userCon->systemNoticeCount($type = 'friend') ?: 0;
//系统消息未读数
$system_count = $this->userCon->systemNoticeCount($type = 'system') ?: 0;
//关注消息未读数
$follow_count = $this->userCon->systemNoticeCount($type = 'follow') ?: 0;
//来访未读数
$preview_count = $this->userCon->userPreviewCount()?:0;
//是否真人认证
$my_real_approved = auth()->user()->is_real_approved;
// $logs = DB::getQueryLog();
// dd($logs); // 获取查询日志
return $this->success('ok', compact('chat', 'notice', 'linkmen', 'visit', 'friend_count', 'system_count', 'follow_count', 'preview_count', 'my_real_approved'));
}
/**
* 删除聊天联系人
*/
public function deleteMessageLinkman(Request $request, $message_linkman)
{
//删除聊天通信人
$message_linkman = MessageLinkman::find($message_linkman);
if (empty($message_linkman)) {
return $this->failure('联系人不存在');
}
$message_linkman->forceDelete();
//聊天记录已查看
ChatMessage::where("user_id", $message_linkman->other_user_id)->where('other_user_id', $message_linkman->user_id)->where('status', 0)->update(['status' => 1]);
return $this->success('ok');
}
//额外奖励信息到处excel
public function addedBonusesExport()
{
//这周一
$this_monday = strtotime('-1 monday', time());
//上周一
$last_monday = $this_monday - 7 * 24 * 3600;
$start_time = date('Y-m-d', $last_monday);
$end_time = date('Y-m-d', $this_monday);
$user_ids = AddedBonus::where('created_at', '>', $start_time)->where('created_at', '<', $end_time)->distinct('user_id')->pluck('user_id');
$data = [];
foreach ($user_ids as $user_id) {
//上周邀请
$bonuses = AddedBonus::where('user_id', $user_id)->where('created_at', '>', $start_time)->where('created_at', '<', $end_time)->get();
$first_week_count = $bonuses->where('amount', 7)->count();
$other_week_count = $bonuses->where('amount', 0)->count();
//人数
$bonus_count = $bonuses->count();
$award = 0;
if ($bonus_count >= 30 && $bonus_count < 100) {
//多少个是第一周的
$award = $first_week_count * 7 + $other_week_count * 5;
} elseif ($bonus_count >= 100 && $bonus_count < 200) {
$award = $bonus_count * 7;
} elseif ($bonus_count >= 200) {
$award = $bonus_count * 10;
} elseif ($first_week_count) {
$award = $first_week_count * 7;
}
$user = User::where('id', $user_id)->with('wechat')->first();
$new_data['name'] = $user->name;
$new_data['openid'] = $user->wechat->openid;
$new_data['first_week_count'] = $first_week_count;
$new_data['other_week_count'] = $other_week_count;
$new_data['bonus_count'] = $bonus_count;
$new_data['award'] = $award;
$data[] = $new_data;
}
return \Excel::download(new ReferreExport($data), 'referres.xlsx');
}
/**
* Ta的好友
* @param Request $request [description]
* @return [type] [description]
*/
public function userFriends(Request $request, UserProfile $user, Linking $linking)
{
$ids = $linking->where('user_id', $user->id)->pluck('user_linking_id');
$other_ids = $linking->where('user_linking_id', $user->id)->pluck('user_id');
$users = $user->where(function ($sql) use ($ids, $other_ids) {
$sql->whereIn('id', $ids)->orWhereIn('id', $other_ids);
});
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where('name', 'like', '%' . $keyword . '%');
}
$users = $users->paginate();
foreach ($users as $user) {
$user->age = \CommonUtilsService::getAge($user->birthday);
}
return $this->success('ok', $users);
}
/**
* 我的红包
* @param Request $request [description]
* @return [type] [description]
*/
public function userRedPackets(Request $request, RedPacketOrder $order)
{
$official_openid = $request->session()->get('official_openid');
if (empty($official_openid)) {
$official_openid = $request->input('official_openid');
}
$orders = $order->where('official_openid', $official_openid)->orderBy('id', 'desc')->paginate();
return $this->success('ok', $orders);
}
/**
* 我的收藏社群动态列表
* @param Request $request [description]
* @return [type] [description]
*/
public function myFavoriteCommunityMoments(Request $request)
{
$user = auth()->user();
$moments = $user->favorites(CommunityMoment::class)->with('user', 'community:id,title')->whereHas('community', function ($query) {
$query->where('is_hided', 0);
});
if ($request->has('keyword') && $request->keyword) {
$moments = $moments->where('content', 'like', '%' . $request->keyword . '%');
}
$moments = $moments->orderBy('created_at', 'desc')->paginate();
foreach ($moments as $moment) {
if (!empty($moment)) {
$moment->photos = json_decode($moment->photos, true);
$moment->momentCommentCount = $moment->totalCommentsCount();
$isLkerMoment = $moment->isLikedBy($user) ? 1 : 0;
$isFavoritet = $user->hasFavorited($moment) ? 1 : 0;
//是否是自己的
$is_self = $moment->user_id == $user->id ? 1 : 0;
//是否点赞
$moment->isLkerMoment = $isLkerMoment;
//点赞数
$moment->momentLikerCount = $moment->likers()->get()->count() ?: 0;
//是否收藏
$moment->is_favorite = $isFavoritet;
//收藏数
$moment->favoriteCount = $moment->favoriters()->count();
//是否是自己的
$moment->is_self = $is_self;
//评论列表
$comments = $this->getCommunityMomentComments($moment, $nopage = 1);
$moment->comments = $comments;
//点赞人列表
$momentLikers = $moment->likers->all();
$moment->momentLikers = $momentLikers;
}
}
return $this->success('ok', $moments);
}
//我收藏的文章列表
public function myFavoriteArticles(Request $request)
{
$user = auth()->user();
$articles = $user->favorites(Article::class);
if ($request->has('keyword') && $request->keyword) {
$articles = $articles->where('content', 'like', '%' . $request->keyword . '%');
}
$articles = $articles->orderBy('created_at', 'desc')->paginate();
// foreach ($articles as $article) {
// if(!empty($article)){
// if (empty($user)) {
// $isLkerArticle = 0;
// $is_self = 0;
// }else{
// $isLkerArticle = $user->hasLiked($article) ?1:0;
// $is_self = $article->user_id == $user->id?1:0;
// }
// $article->is_self = $is_self;
// $article->isLkerArticle = $isLkerArticle;
// //点赞数
// $article->ArticleLikerCount = $article->likers()->get()->count()?:0;
// //点赞人列表
// $article->likers = $article->likers->all();
// //是否收藏
// if (empty($user)) {
// $article->is_favorite = 0;
// }else{
// $article->is_favorite = $user->hasFavorited($article)?1:0;
// }
// //收藏数
// $article->favoriteCount = $article->favoriters()->count()?:0;
// if(empty($article->user->photo)){
// $article->user->photo = $article->user->circle_avatar;
// }
// }
// }
return $this->success('ok', $articles);
}
public function getCommunityMomentComments($community_moment, $nopage = 0)
{
if ($nopage) {
$momentComments = $community_moment->comments()->orderBy('id', 'desc')->get();
} else {
$momentComments = $community_moment->comments()->orderBy('id', 'desc')->paginate();
}
foreach ($momentComments as $momentComment) {
$user = User::find($momentComment->commented_id);
$momentComment->user = $user;
}
return $momentComments;
}
/**
* 我的点赞社群动态列表
* @param Request $request [description]
* @return [type] [description]
*/
public function myLikeCommunityMoments(Request $request)
{
$user = auth()->user();
$moments = $user->likes(CommunityMoment::class)->with('user', 'community:id,title')->paginate();
foreach ($moments as $like) {
$like->likeable; // App\Post instance
}
foreach ($moments as $moment) {
$moment->photos = json_decode($moment->photos, true);
$moment->momentCommentCount = $moment->totalCommentsCount();
$isLkerMoment = $moment->isLikedBy($user) ? 1 : 0;
$isFavoritet = $user->hasFavorited($moment) ? 1 : 0;
//是否是自己的
$is_self = $moment->user_id == $user->id ? 1 : 0;
//是否点赞
$moment->isLkerMoment = $isLkerMoment;
//点赞数
$moment->momentLikerCount = $moment->likers()->get()->count() ?: 0;
//是否收藏
$moment->is_favorite = $isFavoritet;
//收藏数
$moment->favoriteCount = $moment->favoriters()->count();
//是否是自己的
$moment->is_self = $is_self;
//评论列表
$comments = $this->getCommunityMomentComments($moment, $nopage = 1);
$moment->comments = $comments;
//点赞人列表
$momentLikers = $moment->likers->all();
$moment->momentLikers = $momentLikers;
}
return $this->success('ok', $moments);
}
public function getRedPacket(Request $request)
{
$user = auth()->user();
$openid = $user->wechat->openid;
$trade_no = \CommonUtilsService::getTradeNO();
$amount = \CommonUtilsService::mpRegisterRedAmount();
$send_name = '福恋注册奖励';
$packet_data = [
'user_id' => $user->id,
'openid' => $openid,
'amount' => $amount,
'send_name' => $send_name,
'packet_type' => 'normal',
'type' => 'REGISTER',
'trade_no' => $trade_no,
];
SendRedPacket::dispatch($packet_data)->onQueue('love');
return $this->fail('ok', 3, $path = 'pages/users/realName', $operate = '去认证', $notice = '成功领取红包' . $amount . '元,如果还没有认证,请前往认证!');
}
/**
* 共同好友
*/
public function mutualFriends(Request $request, User $user)
{
$mine = auth()->user();
$users = $mine->mutualFriends($request, $user);
return $this->success('ok', $users);
}
/**
* 我的单身好友
*/
public function mySingleFriend(Request $request, User $user)
{
$mine = auth()->user();
$single_ids = $mine->userFriendIds($mine);
// dd($single_ids);
$key = array_search($user->id, $single_ids);
if ($key !== false) {
array_splice($single_ids, $key, 1);
}
$users = User::whereIn('id', $single_ids)->where('is_approved', 1)->where('type', 'single')->where('sex', '<>', 0)->where('sex', '<>', $user->sex)->with('profileCourtship', 'profileMarriage');
$keyword = $request->input('keyword');
if ($keyword) {
$keyword = trim($keyword);
$users = $users->where(function ($sql) use ($keyword) {
$sql->where('name', 'like', '%' . $keyword . '%')
->orWhere('mobile', 'like', '%' . $keyword . '%');
});
}
$users = $users->paginate();
foreach ($users as $user) {
if ($user->type == 'single') {
$user->age = \CommonUtilsService::getAge($user->profileCourtship->birthday);
$user->stature = $user->profileCourtship->stature;
$user->city = $user->profileCourtship->city;
} else {
$user->age = \CommonUtilsService::getAge($user->profileMarriage->birthday);
$user->stature = '';
$user->city = $user->profileMarriage->city;
}
}
return $this->success('ok', $users);
}
/**
* 为他推荐单身卡片
*/
public function sendSingleCard(Request $request, User $user)
{
$mine = auth()->user();
$single_user_id = $request->input('single_user_id');
if (empty($single_user_id)) {
return $this->failure('请选择推荐好友!');
}
$single_user = User::find($single_user_id);
$content_arr = $this->singleCard($single_user);
$this->userCon->sendChatMessage($mine, $user, json_encode($content_arr), $type = 'CARD');
return $this->success('ok');
}
public function singleCard($user)
{
$single_profile = $user->profileCourtship;
$content_arr = [];
$content_arr['user_id'] = $user->id;
$content_arr['circle_avatar'] = $user->circle_avatar;
$content_arr['name'] = $user->name;
$content_arr['age'] = $this->getAge($single_profile->birthday);
$content_arr['stature'] = $single_profile->stature;
$content_arr['city'] = $single_profile->city;
$content_arr['degree'] = $single_profile->degree;
$content_arr['belief'] = $user->belief;
$content_arr['state'] = $single_profile->state;
return $content_arr;
}
/**
* 大数据推荐
*/
public function recommendLinkings(Request $request, $user_id)
{
$num = $request->num??15;
$linkings = RecommendLinkingNew::where('id_users_left', $user_id)->where('is_recommend', 1)->with(['otherUser', 'profileCourtship'])->whereHas('otherUser', function ($sql) {
$sql->where('hidden_profile', 'NONE')->photo();
})->orderBy('score', 'desc')->orderBy('id','desc')->paginate($num);
foreach ($linkings as $link) {
$link->otherUser->card_num = '';
$link->otherUser->profileCourtship->age = $this->getAge($link->otherUser->profileCourtship->birthday);
}
return $this->success('ok', $linkings);
}
/**
* 简单的用户信息
*/
public function userSimpleInfo(Request $request)
{
$id = auth()->id();
$user = User::where('id', $id)->select('id', 'nickname', 'photo', 'app_avatar', 'circle_avatar', 'rank_id')->first();
//会员名称
$rank_name = $user->rank ? $user->rank->name : null;
//会员期限
$rank_deadline = $user->rankHistories()->where('rank_id', $user->rank_id)->orderBy('deadline', 'desc')->value('deadline');
$user->rank_name = $rank_name;
$user->rank_deadline = $rank_deadline;
//头像
$photo = $user->photo;
if(!$photo){
if($user->sex == 1){
$photo = 'https://image.fulllinkai.com/202203/09/39cb4692a41a0a26efa4832e5e0bed91.png';
}elseif($user->sex == 2){
$photo = 'https://image.fulllinkai.com/202203/22/28bcaafeb28c375e3cd6ecf7530eee50.png';
}else{
$photo = User::DefaultAvatar;
}
}
$user->photo = $photo;
unset($user->rank);
unset($user->wechat);
//剩余福币总数
$user->coin = $user->totalCoin();
return $this->success('ok', $user);
}
/**
* 领取一天的超级会员
*/
public function getDailySuperRank(Request $request)
{
$user = auth()->user();
if ($user->type != 'single') {
return $this->failure('领取失败,只限于单身类型用户');
}
$result = $user->canGetDailySuperRank();
if ($result) {
return $this->failure($result);
}
try {
\DB::beginTransaction();
TempMember::create([
'user_id' => $user->id,
'status' => 1,
]);
$user->addSuperRank(1);
\DB::commit();
return $this->success('ok');
} catch (\Exception $e) {
\DB::rollBack();
$this->getError($e);
return $this->failure('领取失败,请稍后再试');
}
}
/**
* 獲取其他单身列表信息
*/
public function otherSingleProfiles(Request $request, User $user)
{
try {
$profile = $user->profileCourtship;
$sex = $profile->sex;
$profiles = ProfileCourtship::where('sex', '<>', $sex)->whereNotNull('sex')->whereNotNull('birthday')->whereHas('user', function ($sql) use ($profile) {
$sql->where('type', 'single')->where('sex', '<>', $profile->sex)->where('sex', '<>', '0')->where('hidden_profile', 'NONE')->whereNotNull("photo");
});
//信仰
$belief = $request->input('belief', '不限');
if ($belief && $belief != '不限') {
$profiles->where(function ($sql) use ($belief) {
$sql->where('belief', $belief)->orWhereHas('user', function ($sq) use ($belief) {
$sq->where('belief', $belief);
});
});
}
// //年龄
$max_age = $request->input('max_age', '不限');
$min_age = $request->input('min_age', '不限');
if (is_numeric($max_age) && is_numeric($min_age)) {
$max_birthday = \CommonUtilsService::agetobirthday($max_age);
$min_birthday = \CommonUtilsService::agetobirthday($min_age);
$profiles = $profiles->where('birthday', '>=', $max_birthday)->where('birthday', '<=', $min_birthday);
} elseif (($max_age == '不限' || empty($max_age)) && is_numeric($min_age)) {
$min_birthday = \CommonUtilsService::agetobirthday($min_age);
$profiles = $profiles->where('birthday', '<=', $min_birthday);
} elseif (($min_age == '不限' || empty($min_age)) && is_numeric($max_age)) {
$max_birthday = \CommonUtilsService::agetobirthday($max_age);
$profiles = $profiles->where('birthday', '>=', $max_birthday);
}
//身高
$min_stature = $request->input('min_stature', '不限');
$max_stature = $request->input('max_stature', '不限');
if (is_numeric($min_stature) && is_numeric($max_stature)) {
$profiles = $profiles->where('stature', '>=', $min_stature)->where('stature', '<=', $max_stature);
} elseif (is_numeric($min_stature) && ($max_stature == '不限' || empty($max_stature))) {
$profiles = $profiles->where('stature', '>=', $min_stature);
} elseif (is_numeric($max_stature) && ($min_stature == '不限' || empty($min_stature))) {
$profiles = $profiles->where('stature', '<=', $max_stature);
}
//学历
$degree = $request->input('degree', '不限');
if ($degree && $degree != '不限') {
$profiles = $profiles->where('degree', $degree);
}
//是否认证
$is_approved = $request->input('is_approved');
if ($is_approved != '不限') {
$profiles = $profiles->whereHas('user', function ($sql) use ($is_approved) {
$sql->where('is_approved', $is_approved);
});
}
//是否有小孩
// $has_child = $request->input('has_child');
// if ($has_child && $has_child != '不限') {
// if ($has_child == '有') {
// $profiles = $profiles->where('has_child', $has_child);
// }else{
// $profiles = $profiles->where(function($sql) use($has_child){
// $sql->where('has_child', $has_child)->orWhereNull('has_child');
// });
// }
// }
// \Log::info($profiles->count());
//工作地
$province = $request->input('province');
$city = $request->input('city');
if ($province && $city) {
$profiles = $profiles->where('province', $province)->where('city', $city);
}
//婚姻状态
$state = $request->input('state');
if ($state && $state != '不限') {
if ($state == '从未结婚') {
$profiles = $profiles->where(function ($sql) {
$sql->where('state', '未婚')->orWhere('state', '从未结婚');
});
} else {
$profiles = $profiles->where('state', $state);
}
}
$profiles = $profiles->select('user_id', 'belief', 'birthday', 'province', 'city')->orderBy('id', 'desc')->paginate();
foreach ($profiles as $pro) {
$pro->name = $pro->user->name;
$pro->mobile = $pro->user->mobile;
$pro->sex = $pro->user->sex == 1 ? '男' : '女';
$pro->age = $this->getAge($pro->birthday);
$pro->address = $pro->province . ' ' . $pro->city;
$pro->resident_address = $pro->resident_province . ' ' . $pro->resident_city;
unset($pro->user);
$pro->user = $pro->user()->select('id', 'nickname', 'photo', 'rank_id', 'is_approved', 'sex', 'belief')->first();
}
return $this->success('ok', $profiles);
} catch (\Exception $e) {
\Log::error($e->getMessage());
return $this->failure('获取信息失败,请稍后再试');
}
}
/**
* @param Request
* @param Messenger 福恋使者
* @param User 小程序用户
* @return json
*/
public function messengerRecommendUser(Request $request, User $user)
{
try {
//判断自己是否是福恋使者
$mine = auth()->user();
$viewer_id = $user->getViewerId();
if (empty($viewer_id)) {
return $this->failure('暂无权限操作');
}
$exist = LiveMessenger::where('viewer_id', $viewer_id)->where('is_audit', 1)->exists();
if (empty($exist)) {
return $this->failure('请先申请福恋使者');
}
$content['user_id'] = $request->input('recomend_user_id');
$content['sharer_user_id'] = $mine->id;
//生成小助手消息
$this->userCon->sendAssistantMessage([$user->id], json_encode($content), $msg_type = 'card');
return $this->success('ok');
} catch (\Exception $e) {
\Log::error($e->getMessage());
return $this->failure('推荐失败');
}
}
//不喜欢
public function dislike(Request $request, $user_id)
{
$is_set = User::where('id', $user_id)->count();
if (empty($is_set)) {
return $this->failure('用户不存在');
}
auth()->user()->dislikeLogs()->firstOrCreate(['type_id' => $user_id, 'type' => 'user']);
return $this->success('ok', '操作成功');
}
/**
* 签到时间记录
* @param Request $request [description]
* @return [type] [description]
*/
public function signLogs(Request $request)
{
try {
$endYesterday = date("Y-m-d 00:00:00");
$beginYesterday = date("Y-m-d 00:00:00", strtotime("-1 day"));
$now = date("Y-m-d", time());
$user='';
if (\Auth::guard('api')->check()) {
$user = \Auth::guard('api')->user();
}
if (empty($user)) {
$logs = [];
$current_sign = 0;
$coin = 0;
$sign_days = 0;
$WithdrawableCash = 0;
$sign_calendar = $sign_calendar = $this->signCalendar(0);
$is_new = 0;
$week = [];
} else {
$logs = $user->signLogs()->signType(SignLog::NEWYEARTYPE)->order('sign_date')->pluck('sign_date')->toArray();
//今天是否签到
$current_sign = 0;
$today_is_sign = $user->signLogs()->signType(SignLog::NEWYEARTYPE)->currentDay()->count() ? 1 : 0;
$coin = $user->coinInfo();
$coin = $coin->remain_amount + $coin->amount_from_other;
//今日已签到
if ($today_is_sign) {
$current_sign = 1;
}
//连续签到天数
$sign_days = UserSign::where('user_id', $user->id)->value('sign_days') ?: 0;
//三十天重置一天
if (!$today_is_sign && $sign_days == 30) {
$sign_days = 0;
UserSign::where('user_id', $user->id)->update(['sign_days' => 0]);
}
//全新的一轮
$new_day = $sign_days % 7;
//昨日是否签到
$yesterdaySign = SignLog::where('user_id', $user->id)->whereBetween('sign_date', [$beginYesterday, $endYesterday])->count();
$sign_raw = SignLog::where('user_id', $user->id)->orderBy('sign_date', 'desc')->limit($new_day)->pluck('sign_date')->toarray();
//赠送的金额
$sign_coin = config('sign.old');
//是否新用户
$is_new = 0;
if (count($logs) < 3 && $user->created_at > '2020-12-31 23:59:59' && $sign_days == count($logs)) {
$is_new = 1;
$sign_coin = config('sign.new2');
}
$day = 0;
$today = date('Y-m-d');
$yday = date("Y-m-d", strtotime("-1 day"));
if (!empty($sign_raw)) {
$nearly = date('Y-m-d', strtotime($sign_raw[0]));
if ($nearly != $today && $nearly != $yday) {
$day = 0;
} else {
foreach ($sign_raw as $key => $value) {
//最近一条记录的前一天
$time = date('Y-m-d', strtotime("-1 day", strtotime($value)));
//最近第二条记录
if (isset($sign_raw[$key + 1])) {
$second = date('Y-m-d', strtotime($sign_raw[$key + 1]));
} else {
break;
}
if ($time == $second) {
$day++;
} else {
break;
}
}
}
}
if ($yesterdaySign == 1 && $current_sign == 0 && $new_day) {
$day = $day + 1;
}
//进行到第几天
$working_day = $sign_days % 7;
if ($sign_days >= 7 && $new_day == 0 && $current_sign == 0) {
//已经进行到第七天未签到
for ($i = 1; $i <= 7; $i++) {
$data['sign_date'] = date('Y-m-d', time() - 24 * 3600 * ($day));
if ($day > 0) {
$data['is_sign'] = true;
} elseif ($current_sign && !$day) {
$data['is_sign'] = true;
} else {
$data['is_sign'] = false;
}
$week[] = $data;
$day--;
}
foreach ($week as $key => $value) {
//如果循环天数大于30
if (($sign_days + $key + 1 - $working_day) > 30) {
//月签到天数-本周签到天数+循环次数+1-30
$week[$key]['coin'] = config('sign.old')[$sign_days + $key + 1 - $working_day - 30];
} else {
$week[$key]['coin'] = $sign_coin[$key + $sign_days + 1];
}
}
} elseif ($sign_days >= 7 && $new_day == 0 && $current_sign == 1) {
//如果进行到了第七天但是已经签到
$week_day = 6;
for ($i = 0; $i <= 6; $i++) {
$data['sign_date'] = date('Y-m-d', time() - 24 * 3600 * ($week_day));
$data['is_sign'] = true;
$week[] = $data;
$week_day--;
}
$coin_day = $sign_days;
if ($sign_days >= 2) {
$coin_day = 1;
}
$day = $sign_days - 7;
foreach ($week as $key => $value) {
if ($coin_day == 0) {
$week[$key]['coin'] = $sign_coin[$key + 1 + $day];
} else {
$week[$key]['coin'] = $sign_coin[$key + $coin_day + $day];
}
}
} elseif ($sign_days > 7) { //超过第七天
for ($i = 0; $i <= 6; $i++) {
if ($new_day > 0) {
$data['sign_date'] = date('Y-m-d', time() - 24 * 3600 * ($day));
$data['is_sign'] = true;
} else {
$data['sign_date'] = date('Y-m-d', time() + 24 * 3600 * (0 - $day));
$data['is_sign'] = false;
}
$week[] = $data;
$new_day--;
$day--;
}
$created_at = array_column($week, 'sign_date');
array_multisort($created_at, SORT_ASC, $week);
foreach ($week as $key => $value) {
if (($sign_days + $key + 1 - $working_day) > 30) {
//已经成为老用户
$week[$key]['coin'] = config('sign.old')[$sign_days + $key + 1 - $working_day - 30];
} else {
$week[$key]['coin'] = $sign_coin[$sign_days + $key + 1 - $working_day];
}
}
} else {
for ($i = 1; $i <= 7; $i++) {
$data['sign_date'] = date('Y-m-d', time() - 24 * 3600 * ($day));
if ($day > 0) {
$data['is_sign'] = true;
} elseif ($current_sign && !$day) {
$data['is_sign'] = true;
} else {
$data['is_sign'] = false;
}
$week[] = $data;
$day--;
}
$coin_day = $sign_days;
if ($sign_days >= 2) {
$coin_day = 1;
}
foreach ($week as $key => $value) {
if ($coin_day == 0) {
$week[$key]['coin'] = $sign_coin[$key + 1];
} else {
$week[$key]['coin'] = $sign_coin[$key + $coin_day];
}
}
}
if ($sign_days > $today_is_sign && !$yesterdaySign) {
$sign_days = $today_is_sign ? 1 : 0;
UserSign::where('user_id', $user->id)->update(['sign_days' => $sign_days]);
}
$sign_calendar = $this->signCalendar($user->id);
//可提现福币
$WithdrawableCash = $user->user_coin($user->id);
}
$d = date('d');
// $sign_days = 1;
// $sign_calendar = 0;
// dump('已经签到:'.$sign_days);
// dump('今天是否签到'.$sign_calendar);
$a = 1;
if ($current_sign == 1) {
$a = 0;
}
// if($sign_days < 3 && $is_new == 1){
// $apart_d = (3 - $sign_days - $a);
// $gift[] = date('Y-m-d', strtotime("+{$apart_d} day"));
// }
$gift = array();
if ($sign_days < 7) {
$apart_d = (7 - $sign_days - $a);
$gift[] = date('Y-m-d', strtotime("+{$apart_d} day"));
}
if ($sign_days < 14) {
$apart_d = (14 - $sign_days - $a);
$gift[] = date('Y-m-d', strtotime("+{$apart_d} day"));
}
if ($sign_days < 21) {
$apart_d = (21 - $sign_days - $a);
$gift[] = date('Y-m-d', strtotime("+{$apart_d} day"));
}
if ($sign_days < 30) {
$apart_d = (30 - $sign_days - $a);
$gift[] = date('Y-m-d', strtotime("+{$apart_d} day"));
}
$sign_notice = 0;
if($user)
$sign_notice = UserInfo::where('user_id',$user->id)->value('sign_notice')??0;
return $this->success('ok', compact('logs', 'current_sign', 'coin', 'sign_days', 'sign_calendar', 'is_new', 'week', 'now', 'gift','WithdrawableCash','sign_notice'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取签到记录失败,请稍后再试');
}
}
/**
* 签到
*/
public function signIn(Request $request)
{
try {
//判断签到权限
$result = $this->checkSignIn();
if (empty($result)) throw new \Exception("判断签到权限失败", 1);
if (is_array($result) && $result['code']) return $this->failure($result['msg']);
//增加签到记录
auth()->user()->signLogs()->create([
'sign_date' => date('Y-m-d H:i:s'),
'type' => SignLog::NEWYEARTYPE
]);
SendSignCoin::dispatch(auth()->id())->onQueue('love');
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('签到失败,请稍后再试');
}
}
/**
* 签到
*/
public function signInV2(Request $request)
{
try {
$endYesterday = date("Y-m-d 00:00:00");
$beginYesterday = date("Y-m-d 00:00:00", strtotime("-1 day"));
//判断签到权限
$result = $this->checkSignIn();
if (empty($result)) throw new \Exception("判断签到权限失败", 1);
if (is_array($result) && $result['code']) return $this->failure($result['msg']);
DB::beginTransaction();
$prefix = ($request->route()->getAction())['prefix'];
$source = 1;
if ($prefix === 'api/app') {
$source = 2;
}
//增加签到记录
auth()->user()->signLogs()->create([
'sign_date' => date('Y-m-d H:i:s'),
'type' => SignLog::NEWYEARTYPE,
'source'=> $source
]);
$user = auth()->user();
//连续签到天数
$sign_days = UserSign::where('user_id', $user->id)->value('sign_days') ?: 0;
$yesterdaySign = SignLog::where('user_id', $user->id)->whereBetween('sign_date', [$beginYesterday, $endYesterday])->count();
if ($sign_days && !$yesterdaySign) {
UserSign::where('user_id', $user->id)->update(['sign_days' => 0]);
}
//增加连续签到天数
$result = $this->addSignDays();
//赠送福币(异步)
SendSignCoinV2::dispatch(auth()->id())->onQueue('love');
//临时先处理不走异步,不知道什么原因上面的队列没执行
// $this->SendSignCoinV2($user);
//完成任务还可获得福币
$tasks = $this->userCon->infoTasks();
$task_coin = 10;
foreach ($tasks as $task => $val) {
if (!$val) {
switch ($task) {
case 'coin_user_info':
case 'is_approved':
$task_coin += 10;
break;
case 'profile_photo':
$task_coin += 5;
break;
case 'ideal_mate':
case 'introduction':
case 'interest_hobby':
$task_coin += 3;
break;
default:
break;
}
}
}
DB::commit();
//连续签到天数
$sign_days = UserSign::where('user_id', $user->id)->value('sign_days') ?: 0;
//是否新用户
$is_new = 0;
if (empty($user)) {
$logs = [];
}else{
$logs = $user->signLogs()->signType(SignLog::NEWYEARTYPE)->order('sign_date')->pluck('sign_date')->toArray();
}
if (count($logs) <= 3 && $user->created_at > '2020-12-31 23:59:59' && $sign_days == count($logs)) {
$is_new = 1;
$sign_coin = config('sign.new2');
}
$msg_sign_award = '';
$msg_tomorrow_sign_award = '明日签到可得2福币';
if($is_new==1){
if($sign_days==1){
$msg_sign_award = '+7福币';
$msg_tomorrow_sign_award = '明日签到可得15福币';
}else if($sign_days==2){
$msg_sign_award = '+15福币';
$msg_tomorrow_sign_award = '明日签到可得20福币';
}else if($sign_days==3){
$msg_sign_award = '+20福币';
}
}else{
if($sign_days == 3){
$msg_sign_award = '+7福币';
}else if($sign_days == 7){
$msg_sign_award = '15福币+3天vip会员';
}else if($sign_days == 14){
$msg_sign_award = '30福币+7天vip会员';
}else if($sign_days == 21){
$msg_sign_award = '50福币+15天vip会员';
}else if($sign_days == 30){
$msg_sign_award = '70福币+30天vip会员';
}else{
$msg_sign_award = '+2福币';
}
if($sign_days == 2){
$msg_tomorrow_sign_award = '明日签到可得7福币';
}else if($sign_days == 6){
$msg_tomorrow_sign_award = '明日签到可得15福币+3天vip';
}else if($sign_days == 13){
$msg_tomorrow_sign_award = '明日签到可得30福币+7天vip';
}else if($sign_days == 20){
$msg_tomorrow_sign_award = '明日签到可得50福币+15天vip';
}else if($sign_days == 29){
$msg_tomorrow_sign_award = '明日签到可得70福币+30天vip';
}
}
return $this->success('ok', compact('task_coin','msg_sign_award','msg_tomorrow_sign_award','sign_days'));
} catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure('签到失败,请稍后再试');
}
}
public function SendSignCoinV2($user)
{
// $user = User::find($this->user_id);
//连续签到天数
$sign_days = UserSign::where('user_id', $user->id)->value('sign_days') ?: 0;
if($sign_days == 0) return;
//是否新用户
$logs = $user->signLogs()->signType(SignLog::NEWYEARTYPE)->order('sign_date')->pluck('sign_date')->toArray();
$is_new = 0;
if (count($logs) < 4 && $user->created_at > '2020-12-31 23:59:59' && $sign_days == count($logs)) {
$is_new = 1;
}
//\Log::info('签到天数---'.$sign_days);
//新用户
if ($is_new) {
$new_coin = config('sign.new');
$this->sendCoin($user, $new_coin[$sign_days], $sign_days, 1);
} else {
$old_coin = config('sign.old');
$this->sendCoin($user, $old_coin[$sign_days], $sign_days);
//赠送会员
$rank = config('sign.rank');
if (!empty($rank[$sign_days])) {
$user->addSuperRank($rank[$sign_days], $month = 0, $type = RankHistory::SIGNNEWYEAR);
}
}
}
public function sendCoin($user, $coin, $count,$is_new=0)
{
$remark=$is_new ? '新用户连续'.$count.'天签到' : '连续'.$count.'天签到';
//增加福币记录
$user->addCoinLog(CoinLog::RECSYSTEM, 0, $coin, $remark);
//修改福币钱包
$user->updateCoinInfo('add', $coin, 'other');
}
//增加签到天数
public function addSignDays()
{
$user_id = auth()->id();
$user_sign = UserSign::where('user_id', $user_id)->first();
if (empty($user_sign)) {
UserSign::create([
'user_id' => $user_id,
'sign_days' => 1,
]);
} else {
if ($user_sign->sign_days >= 30) {
$user_sign->sign_days = 1;
$user_sign->save();
} else {
UserSign::where('user_id', $user_id)->increment('sign_days');
}
}
}
/**
* 检测签到权限
* @return [type] [description]
*/
public function checkSignIn()
{
try {
//是否当天已经签到过
$count = auth()->user()->signLogs()->signType(SignLog::NEWYEARTYPE)->currentDay()->count();
if ($count) return ['code' => 1, 'msg' => '今日已经签到'];
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
//签到日历
public function signCalendar($user_id)
{
try {
$year = request()->input('year', '2021') ?: '2021';
$month = request()->input('month', '1') ?: '1';
$sign_calendar = SignLog::where('user_id', $user_id)->where('type', 'NEWYEAR')->where('sign_date', '>', '2021-01-19 18:00:00')->pluck('sign_date')->toArray();
// $j = cal_days_in_month(CAL_GREGORIAN, $month, $year); //获取当前月份天数
$j = date("t", strtotime("$year-$month"));
$start_time = strtotime(date($year . '-' . $month . '-01')); //获取本月第一天时间戳
$array = array();
for ($i = 0; $i < $j; $i++) {
$array[] = date('Y-m-d', $start_time + $i * 86400); //每隔一天赋值给数组
}
foreach ($sign_calendar as &$value) {
$value = substr($value, 0, 10);
}
foreach ($array as $key => $val) {
//已签到
if (in_array($val, $sign_calendar)) {
$data[$key] = 1;
} elseif ($val >= date("Y-m-d")) {
//未到签到时间
$data[$key] = 0;
} else {
//未签到
$data[$key] = -1;
}
}
return $data;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 分享记录
* @param Request $request [description]
* @return [type] [description]
*/
public function shareLogs(Request $request)
{
try {
//分享列表
$logs = $this->userCon->inviteLogs();
if (empty($logs) && !is_object($logs)) throw new \Exception("获取分享记录失败", 1);
//已邀请人数
$member_count = $this->userCon->inviteMemberCount();
if (empty($member_count) && !is_numeric($member_count)) throw new \Exception("获取分享人数失败", 1);
//已获得福币
$coin_count = $this->userCon->inviteCoinCount();
if (empty($coin_count) && !is_numeric($coin_count)) throw new \Exception("获取分享福币数失败", 1);
return $this->success('ok', compact('logs', 'member_count', 'coin_count'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure("获取分享记录失败,请稍后再试");
}
}
/**
* 领取限时玫瑰
* @param Request $request [description]
* @return [type] [description]
*/
public function getFlashRose(Request $request)
{
try {
//判断权限
$result = $this->checkGetFlashRose();
if (empty($result)) throw new \Exception("检测领取限时玫瑰权限失败", 1);
if (is_array($result) && $result['code']) return $this->failure($result['msg']);
//获取限时玫瑰
$result = $this->userCon->gainFlashRose();
if (empty($result)) throw new \Exception("领取限时玫瑰失败", 1);
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('领取限时玫瑰失败,请稍后再试');
}
}
/**
* 检查领取限时玫瑰权限
* @return [type] [description]
*/
public function checkGetFlashRose()
{
try {
$first_start = '12:00';
$first_end = '18:00';
$second_start = '18:00';
$second_end = '20:00';
//判断时间是否正确 1200-2:00 18:00-20:00
$time = date('H:i');
if (!($time >= $first_start && $time <= $first_end) && !($time >= $second_start && $time <= $second_end)) {
return ['code' => 1, 'msg' => '领取时间已过,请等待下一段时间'];
}
//判断这个时间段是否已领取
if ($time >= $first_start && $time <= $first_end) {
$count = auth()->user()->flashRoseLogs()->where('type', 'GAIN')->whereBetween('created_at', [date('Y-m-d ' . $first_start), date('Y-m-d ' . $first_end)])->count();
} elseif ($time >= '18:00' && $time <= "20:00") {
$count = auth()->user()->flashRoseLogs()->where('type', 'GAIN')->whereBetween('created_at', [date('Y-m-d ' . $second_start), date('Y-m-d ' . $second_end)])->count();
}
if ($count) return ['code' => 1, 'msg' => '已领取过,请等待下一段时间'];
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 赠送限时玫瑰
* @param Request $request [description]
* @param [type] $user_id [description]
* @return [type] [description]
*/
public function giveFlashRose(Request $request, $user_id)
{
try {
//检测赠送权限
$result = $this->checkGiveFlashRose();
if (empty($result)) throw new \Exception("检测赠送权限失败", 1);
if (is_array($result) && $result['code']) return $this->failure($result['msg']);
//赠送限时玫瑰
$result = $this->userCon->giveFlashRose($user_id, request()->input('num', 1));
if (empty($result)) throw new \Exception("赠送限时玫瑰失败", 1);
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('赠送限时玫瑰失败,请稍后再试');
}
}
public function checkGiveFlashRose()
{
try {
$num = request()->input('num');
//检查数量是否足够
$rose = auth()->user()->flashRose;
if (empty($rose) || ($rose && $rose->remain_amount < $num)) return ['code' => 1, "msg" => '您的限时玫瑰数不足,请等待活动时间内领取'];
return true;
} catch (\Exception $e) {
$this->getError($e);
return false;
}
}
/**
* 打招呼信息
* @param Request $request [description]
* @return [type] [description]
*/
public function greetLog(Request $request)
{
try {
if (auth()->id() == '69938') {
$log = ['id'=>0, 'name'=>'你好,我是福恋的工作人员,想和你沟通一下。', 'is_show'=>1];
}elseif(auth()->id() == '61848'){
$log = ['id'=>0, 'name'=>'你好我是平台的工作人员现在启动了真人交友群群内会不定期分享活动福利需要进群请添加小恋企微15323700967', 'is_show'=>1];
}elseif(auth()->id() == '90852'){
$log = ['id'=>0, 'name'=>'你好,我是福恋的工作人员,有位优秀的异性想要更多的了解你,你是否愿意和工作人员聊聊?', 'is_show'=>1];
}elseif(auth()->id() == 1){
$log = ['id'=>0, 'name'=>'你好,我是福恋脱单小助手小恋,陪伴你一起找对象,有什么情感困惑可以随时找我!', 'is_show'=>1];
}else{
$status = $request->input("status", 1);
if ($status) {
$logs = \DB::table('greet_logs')->get()->toArray();
$count = count($logs);
if (empty($count)) return $this->success('ok');
$index = random_int(0, $count - 1);
$log = $logs[$index];
}else {
$log = ['name'=>'你好!', 'is_show'=>1];
}
}
return $this->success('ok', $log);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取问候信息失败,请稍后再试');
}
}
public function infoTasks(Request $request)
{
try {
//任务进度
$progress = $this->userCon->infoTaskProgress();
//各任务完成
$tasks = $this->userCon->infoTasks();
return $this->success('ok', compact('progress', 'tasks'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取任务列表失败,请稍后再试');
}
}
/**
* 曝光
* @param Request $request [description]
* @return [type] [description]
*/
public function userExpose(Request $request)
{
try {
$log = ExposeLog::firstOrCreate(['user_id' => auth()->id()]);
$log->increment('num');
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('曝光失败');
}
}
//妇女节/白色情人节赠送一个月vip
public function reciveWomendayGift(Request $request)
{
$user = auth()->user();
$key = "recive_whiteday_gift_$user->id";
$has_recive = Redis::get($key);
if ($user->type != 'single' || $has_recive) {
return $this->failure('您不符合领取条件');
}
$result = $user->addSuperRank(0, 1);
if ($result) {
Redis::set($key, 1);
}
return $this->success('ok');
}
//是否可以领取妇女节/白色情人节礼品
public function canReciveGift()
{
$user = auth()->user();
$key = "recive_whiteday_gift_$user->id";
$has_recive = Redis::get($key) ?: 0;
$arr = [
'sex' => $user->sex,
'type' => $user->type,
'has_recive' => $has_recive,
];
return $this->success('ok', $arr);
}
public function approveShare(Request $request)
{
$user_id = auth()->id();
$users = ApproveHistory::with('user:id,name,nickname,circle_avatar,app_avatar,photo,sex')->whereHas('user')->where('status', 1)->where('from_user_id', $user_id)->where('type', 'body')->orderBy('updated_at', 'desc')->paginate();
$key = "real_approve_share_qrcode_$user_id";
foreach ($users as $user) {
$updated_at = date('Y-m-d H:i', strtotime($user->updated_at->toDateTimeString()));
$user->update_at = $updated_at;
}
$qrcode = Redis::get($key);
if (!$qrcode) {
$qrcode = $this->getUrlqrcode(env('APP_URL')."/h5/#/realCertificationApp?app_url=certification&from_user_id=$user_id");
}
Redis::set($key, $qrcode);
return $this->success('ok', compact("users", "qrcode"));
}
public function getUrlqrcode($url, $size = 100)
{
$name = substr($url, stripos($url, '='));
$path = "../storage/qrcode/$name.png";
QrCode::format('png')->margin(1)->size($size)->generate($url, $path);
$pic = $this->uploadFile($path);
unlink($path);
return $pic;
}
//使用福币兑换
public function exchangeWithCoin(Request $request)
{
try {
$user = auth()->user();
$coin = $user->totalCoin();
$type = $request->input('type', 'RANK');
if ($coin < 100) return $this->failure('福币不足');
\DB::beginTransaction();
$result = $user->updateCoinInfo('sub', 100);
if (!$result) {
\DB::rollback();
throw new \Exception("福币解锁会员失败", 1);
}
CoinLog::create([
'user_id' => $user->id,
'type' => $type,
'type_id' => 9,
'coin' => 100,
'remark' => '100福兑换三天会员',
'is_hooked' => 1
]);
switch ($type) {
case 'RANK':
$result = $user->addSuperRank(3);
if (!$result) {
\DB::rollback();
throw new \Exception("福币解锁会员失败", 1);
}
break;
default:
break;
}
\DB::commit();
return $this->success('解锁成功');
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
return $this->failure('解锁失败');
}
}
//用户喜好
public function preference(Request $request)
{
$user = auth()->user();
$profile = $user->profileCourtship;
if (!empty($profile)) {
$profile->min_age = \CommonUtilsService::getAge($profile->min_age);
$profile->max_age = \CommonUtilsService::getAge($profile->max_age);
$profile->mate_conditon = json_decode($profile->mate_conditon,true);
$profile->min_height = $profile->min_height ?: 160;
$profile->max_height = $profile->max_height ?: 180;
$profile->city_claim = $profile->city_claim ?: 1;
$profile->hometown_claim = $profile->hometown_claim ?: 1;
$profile->approve_claim = $profile->approve_claim ?: 1;
$profile->is_approved = $user->is_approved;
}
return $this->success('ok', $profile);
}
//设置用户喜好
public function setPreference(Request $request)
{
$user = auth()->user();
$preference = $user->profileCourtship;
$mate_conditon = json_decode($preference->mate_conditon, true);
$test = json_decode($preference->mate_condition, true);
if (empty($preference)) return $this->failure('不是单身用户或者没有单身资料');
if (empty($preference->city)) return $this->failure('请先选择您的城市');
// if (empty($preference->resident_province) && $request->hometown_claim == 1) return $this->failure('请先选择您的出生地');
if (empty($user->is_approved) && $request->approve_claim == 2) return $this->failure('请先认证');
// if(!empty($preference->min_age)){
$has_change = 0;
if (is_numeric($request->min_age) && $request->min_age != $preference->min_age) {
$preference->min_age = \CommonUtilsService::ageToDate($request->min_age);
$has_change = 1;
}
$mate_conditon['age'] = $request->min_age;
if (is_numeric($request->max_age) && $request->max_age != $preference->max_age) {
$preference->max_age = \CommonUtilsService::ageToDate($request->max_age);
$has_change = 1;
}
$mate_conditon['age'] = $mate_conditon['age'].'-'.$request->max_age.'岁';
if (is_numeric($request->min_height) && $request->min_height != $preference->min_height) {
$preference->min_height = $request->min_height;
$has_change = 1;
}
$mate_conditon['stature'] = $request->min_height;
if (is_numeric($request->max_height) && $request->max_height != $preference->max_height) {
$preference->max_height = $request->max_height;
$has_change = 1;
}
$mate_conditon['stature'] = $mate_conditon['stature'].'-'.$request->max_height.'cm';
if ($request->city_claim && $request->city_claim != $preference->city_claim) {
$preference->city_claim = $request->city_claim;
$has_change = 1;
}
//默认情感不限 单身、离异、丧偶
$mate_conditon_state = $mate_conditon['state'] ?? '';
$mate_conditon['state'] = $request->state;
if($request->state && $request->state != $mate_conditon_state){
$has_change = 1;
}
if ($request->hometown_claim && $request->hometown_claim != $preference->hometown_claim) {
$preference->hometown_claim = $request->hometown_claim;
$has_change = 1;
}
if ($request->approve_claim && $request->approve_claim != $preference->approve_claim) {
$preference->approve_claim = $request->approve_claim;
$has_change = 1;
}
// 我希望Ta所在的城市:城市字符串
$city_list_claim = $request->city_list_claim;
if($request->city_claim == 3){
if ($request->city_list_claim && $city_list_claim != $preference->city_list_claim){
$city_list_claim_array = explode(',',$city_list_claim);
if(count($city_list_claim_array) > 7){
return $this->failure('设置 “你希望Ta所在的城市” 不能超过7个');
}
$preference->city_list_claim = $city_list_claim;
$has_change = 1;
}
}else if($request->city_claim == 1){
$preference->city_list_claim = '';
$has_change = 1;
}
if ($has_change) {
$end_time = date('Y-m-d H:i:s');
RecommendUser::where('user_id', $user->id)->where('end_time', '>', $end_time)->limit(7)->delete();
}
$preference->mate_conditon = json_encode($mate_conditon);
$preference->save();
return $this->success('ok');
}
//分区用户
public function areaUser(Request $request)
{
try {
$user = auth()->user();
$sex = null;
$belief = null;
//如果是单身用户推荐异性,介绍人推荐全部
if ($user && $user->type == 'single') {
$sex = $user->sex == 2 ? 1 : 2;
$belief = $user->belief;
}
$area_id = $request->input('area_id', 1);
$area_users = AreaUser::with(['user:id,circle_avatar,photo,app_avatar,nickname,name,sex,hidden_profile', 'user.profileCourtship:id,user_id,city,birthday'])
->whereHas('user', function ($query) use ($sex, $belief) {
$query->where('type', 'single')
->where('hidden_profile', 'NONE');
if (!empty($sex)) {
$query->where('sex', $sex);
}
})->where('area_id', $area_id)
->where('is_audited', 1)
->where('is_show', 1)
->orderBy('id', 'desc');
$areas = [];
if ($area_id == 1) {
$area_users = $area_users->get();
$areas = ClassArea::where('is_show', 1)->where('id', '!=', 1)->orderBy('sort', 'asc')->get();
} else {
$area_users = $area_users->paginate(16);
}
foreach ($area_users as $area_user) {
$area_user->user->city = !empty($area_user->user->profileCourtship) ? $area_user->user->profileCourtship->city : '';
$area_user->user->age = !empty($area_user->user->profileCourtship) ? \CommonUtilsService::getAge($area_user->user->profileCourtship->birthday) : 0;
// $area_user->user->profileCourtship->age = !empty($area_user->user->profileCourtship->birthday) ? \CommonUtilsService::getAge($area_user->user->profileCourtship->birthday) : 0;
// unset($area_user->user->profileCourtship);
$area_user->user->year = isset($area_user->user->profileCourtship->birthday) && $area_user->user->profileCourtship->birthday?substr($area_user->user->profileCourtship->birthday, 2, 2).'年':"未知";
}
return $this->success('ok', compact('area_users', 'areas'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
public function areaUserV2(Request $request) {
try {
$user = auth()->user();
$area_id = $request->input('area_id');
if (empty($area_id)) throw new \Exception("未获取到专区id");
$sex = 0;
// $belief = null;
//如果是单身用户推荐异性,介绍人推荐全部
if ($user && $user->type == 'single') {
$sex = $user->sex;
// $belief = $user->belief;
}
$users = DB::table('users as u')->rightJoin('area_users as au', 'au.user_id', '=', 'u.id')
->leftJoin('profile_courtships as pc', 'pc.user_id', 'u.id')
->where('au.area_id', $area_id)
->where('au.is_audited', 1)
->where("u.sex", '<>', $sex)
->where('u.type','single')
->where('u.hidden_profile', 'NONE')
->where('u.negative_score','<',200)
// ->where('u.is_educate_approved',1)
// ->where('u.belief', $belief)
->select('u.id','u.photo', 'u.nickname', 'pc.city','pc.birthday', 'u.hidden_profile');
// https://blog.csdn.net/u011095976/article/details/103879333?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-22-103879333-null-null.pc_agg_new_rank&utm_term=mysql+%E9%9A%8F%E6%9C%BA%E6%8E%92%E5%BA%8F+%E5%88%86%E9%A1%B5&spm=1000.2123.3001.4430
if($area_id == 6) {
$users = $users->where('u.is_educate_approved',1);
}
$rand = rand(1,100);
$redis_key = 'area_id_'.$area_id.'_user_id_';
if($user) $redis_key = $redis_key.$user->id;
if($request->page == 1){//每次页码page=1时更新N和key 避免出现重复数据
$redis_value = $rand;
Redis::setex($redis_key,30*60,$redis_value);//30分钟
}else{
$redis_value = Redis::get($redis_key);
if(empty($redis_value)){
$redis_value = $rand;
Redis::setex($redis_key,30*60,$redis_value);
}
$redis_value = Redis::get($redis_key);
}
$users = $users->orderByRaw("RAND($redis_value)")->paginate(16);
foreach ($users as $user) {
$user->year = $user->birthday?substr($user->birthday, 2, 2).'年':"未知";
}
return $this->success('ok', $users);
}catch (\Exception $e) {
$this->getError($e);
return $this->failure();
}
}
//申请置顶推荐
public function applyAreaUser(Request $request)
{
$user_id = auth()->id();
//检查资料
$res = $this->userCon->isCompleteProfile($user_id);
if (empty($res)) return $this->failure('申请失败,请先完善资料');
$area_id = $request->input('area_id', 1);
$area_user = AreaUser::where('user_id', $user_id)->where('area_id', $area_id)->first();
if (!empty($area_user)) {
if ($area_user->is_audited != -1) return $this->failure('请勿重复申请');
$area_user->is_audited = 0;
$area_user->save();
} else {
AreaUser::create([
'user_id' => $user_id,
'area_id' => $area_id,
'sort' => 20,
'is_apply'=>1
]);
}
return $this->success('ok');
}
public function areaUserCondition(Request $request)
{
try {
$user = auth()->user();
$c_profile = $user->profileCourtship;
//个人资料
$profile = (empty($c_profile) || empty($this->userCon->isCompleteAllInfo($user))) ? 0:1;
//生活照6张
$profile_photo = $user->profilePhoto->count() < 6 ? 0:1;
//兴趣爱好50字
$interest_hobby = (empty($c_profile) || mb_strlen($c_profile->interest_hobby) < 50) ? 0:1;
//自我描述200字
$introduction = (empty($c_profile) || mb_strlen($c_profile->introduction) < 200) ? 0:1;
//择偶标准超200字
$ideal_mate = (empty($c_profile) || mb_strlen($c_profile->ideal_mate) < 200) ? 0:1;
//真人认证
$is_real_approved = $user->is_real_approved;
//学历认证
$is_educate_approved = $user->is_educate_approved;
return $this->success('ok', compact('profile', 'profile_photo', 'interest_hobby', 'introduction', 'ideal_mate','is_real_approved', 'is_educate_approved'));
}catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
public function remindProfile(Request $request, $user_id)
{
try {
$mobile = User::where('id', $user_id)->value('mobile');
$content = '【' . auth()->user()->nickname . '】对你的资料非常感兴趣,希望你能完善交友卡片';
$type = 'remind_profile';
$count = Notice::where('user_id', $user_id)->where('send_user_id', auth()->id())->where('type', $type)->count();
if ($count) return $this->failure('已提醒对方');
//发送短信提醒
$this->sms->sentMessage($mobile, $content);
//生成提醒记录
$notice = $this->userCon->sendNotice($user_id, auth()->id(), $type, $content, $content);
//发送提醒推送消息
$result = $this->momentCon->sendAttachMsg($notice->id, $type, $content, auth()->id(), $user_id, auth()->user()->app_avatar);
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('提醒失败,请稍后再试');
}
}
//首页单身广场
public function users(Request $request)
{
DB::connection()->enableQueryLog();
$my_user = auth()->user();
if (empty($my_user)) {
$my_user = $this->authCheck();
}
try {
$sex = $request->input('sex');
$age = $request->input('age');
$province = $request->input('province');
$city = $request->input('city');
$is_approve = $request->input('is_approve');
$keyword = $request->input('keyword');
if (!empty($my_user)) {
if (empty($sex) && empty($age) && empty($province) && empty($city) && !is_numeric($is_approve) && empty($keyword)) {
$is_locked = $this->isLock();
if (!$is_locked) {
$result = $this->bigDataLink($my_user);
if ($result) return $this->success('获取大数据推荐成功', $result);
}
}
}
//成员类型 良人 佳偶 介绍人 红娘
$select_sex = !empty($my_user->sex) ? $my_user->sex : 1;
if($my_user->type == 'single'){
$sex = $select_sex == 2 ? 1 : 2;
}else if($my_user->type == 'marriage'){
$sex = $select_sex == 2 ? 1 : 2;
}
$age = $age ?: '不限';
$times = CommonUtilsService::searchAge($age);
$province = $province ?: '不限';
$city = $city ?: '不限';
$is_approve = $request->input('is_approve');
$now = date('Y-m-d H:i:s');
$users = User::with('profileCourtship')
->with(['rankHistories' => function ($q) use ($now) {
$q->where('deadline', '>', $now);
$q->select();
}])
->whereHas('profileCourtship', function ($sql) use ($province, $city, $sex, $age, $times, $is_approve) {
if ($province && $province != '不限') {
$sql = $sql->where('province', $province);
}
if ($city && $city != "不限") {
$sql = $sql->where('city', $city);
}
$sql = $sql->where('sex', $sex);
if (config('app.env') == 'production') {
$sql = $sql->where('is_real_approved', 1);
}
if ($age != '不限') {
$sql = $sql->where('birthday', '>=', $times['start_time'])->where('birthday', '<', $times['end_time']);
} else {
$sql = $sql->where('birthday', '>=', '1986-01-01')->where('birthday', '<', '1998-01-01');
}
if (is_numeric($is_approve)) {
$sql = $sql->where('is_approved', $is_approve);
}
});
if ($keyword) {
$users = $users->where(function ($sql) use ($keyword) {
$sql->where('nickname', 'like', '%' . $keyword . '%');
});
} else {
if (!empty($my_user)) {
$users = $users->photo()->where('belief', $my_user->belief);
}
}
//增加黑名单隐藏
$blacklist_user_ids = !empty($my_user) ? LinkingBlackList::where('user_id', $my_user->id)->pluck('other_user_id')->toArray() : [];
$dislike_user_ids = !empty($my_user) ? $my_user->dislikeLogs()->where('type', 'user')->pluck('type_id')->toArray() : [];
$internal_user = TestUser::get()->pluck('user_id')->toArray();
//客服id
$unset_user_ids = array_merge($blacklist_user_ids, $dislike_user_ids, User::FULLLINKIDS,$internal_user);
//小程序查看22-35的用户
$users = $users->whereHas('profileCourtship', function ($query) {
$query->whereBetween('birthday', ['1989-01-01 00:00:00', '1999-01-01 00:00:00']);
});
//排除大数据用户
if (!empty($my_user)) {
$user_ids = RecommendUser::where('user_id', $my_user->id)->whereHas('otherUser', function ($sql) use ($my_user) {
$sql->where('is_approved', 1)->where('sex', '<>', $my_user->sex)
->where('belief', $my_user->belief)->where('hidden_profile', '<>', 'ALLSEX')
->whereNotIn('id', User::FULLLINKIDS)
->where('can_be_found', 1);
})
->limit(7)
->orderBy('start_time', 'asc')
->pluck(
'other_user_id'
)->toArray();
$users = $users->whereNotIn('id', $user_ids);
} else {
$sex = $request->input('sex') == 1 ? 2 : 1;
$min_birthday = CommonUtilsService::ageToDate(23);
$max_birthday = CommonUtilsService::ageToDate(35);
if (empty($age) && empty($province) && empty($city) && !is_numeric($is_approve) && empty($keyword)) {
$home_user_id = User::whereHas('profileCourtship', function ($sql) use ($min_birthday, $max_birthday) {
$sql->whereBetween('birthday', [$max_birthday, $min_birthday]);
})->where('nickname', 'not like', '%福恋%')
->where('sex', $sex)
->where('hidden_profile', 'NONE')
->where('type', 'single')
->orderBy('is_real_approved', 'desc')
->orderBy('is_approved', 'desc')
->orderBy('liveness', 'desc')
->orderBy('last_visit', 'desc')
->orderBy('info_complete_score', 'desc')
->limit(7)
->pluck('id')
->toArray();
$users = $users->whereNotIn('id', $home_user_id);
}
}
$users = $users->whereNotIn('id', $unset_user_ids);
$users = $users->where('hidden_profile', 'NONE')
->orderBy('rank_id', 'desc')
->where('type', 'single')
->orderBy('is_real_approved', 'desc')
->orderBy('is_approved', 'desc')
->orderBy('liveness', 'desc')
->orderBy('info_complete_score', 'desc')
->orderBy('last_visit', 'desc')
->paginate();
// dd(DB::getQueryLog());
$users = $users->toArray();
$user_data = $users['data'];
for ($u = 0; $u < count($user_data); $u++) {
$user = $user_data[$u];
$user['profile_courtship']['interest_label'] = [];
if($user['profile_courtship']['interest_label'])
$user['profile_courtship']['interest_label'] = json_decode($user['profile_courtship']['interest_label'],true) ?: [];
//是否关注
$user['is_followed'] = !empty($my_user) ? $my_user->isFollowing($user) : 0;
//是否是超级会员
if ($user['rank_histories'] == []) {
$user['isSuperRank'] = 0;
} else {
$user['isSuperRank'] = 1;
}
$user['photo'] = $user['avatar'];
$user['year'] = substr($user['profile_courtship']['birthday'], 2, 2) . '年';
if (isset($user['profile_courtship']['stature'])) {
$user['stature'] = $user['profile_courtship']['stature'] . 'cm';
}
$user_data[$u] = $user;
}
$users['data'] = $user_data;
return $this->success('ok', $users);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取用户列表失败,请稍后再试');
}
}
//首页单身广场
public function usersV2(Request $request)
{
DB::connection()->enableQueryLog();
$my_user = auth()->user();
if (empty($my_user)) {
$my_user = $this->authCheck();
}
try {
$sex = $request->input('sex');
$age = $request->input('age');
$province = $request->input('province');
$city = $request->input('city');
$is_approve = $request->input('is_approve');
$keyword = $request->input('keyword');
$now = date('Y-m-d H:i:s');
if (!empty($my_user)) {
if (empty($sex) && empty($age) && empty($province) && empty($city) && !is_numeric($is_approve) && empty($keyword)) {
$is_locked = $this->isLock();
if (!$is_locked) {
$result = $this->bigDataLink($my_user);
if ($result) return $this->success('获取大数据推荐成功', $result);
}
}
}
else{
//客服人员
$unset_user_ids = TestUser::get()->pluck('user_id')->toArray();
$areaUser= AreaUser::where('area_id',17)
->offset(7)
->whereNotIn('user_id', $unset_user_ids)
->limit(1000)
->where('is_audited',1)
->pluck('user_id')
->toarray();
$users = User::with('profileCourtship')
->whereIn('id',$areaUser)
->with(['rankHistories' => function ($q) use ($now) {
$q->where('deadline', '>', $now);
$q->select();}])
->where('hidden_profile', 'NONE')
->orderBy('rank_id', 'desc')
->where('type', 'single')
->orderBy('is_real_approved', 'desc')
->orderBy('is_approved', 'desc')
->orderBy('liveness', 'desc')
->orderBy('info_complete_score', 'desc')
->orderBy('last_visit', 'desc')
->paginate();
$users = $users->toArray();
$user_data = $users['data'];
for ($u = 0; $u < count($user_data); $u++) {
$user = $user_data[$u];
$user['profile_courtship']['interest_label'] = [];
if($user['profile_courtship']['interest_label']){
$user['profile_courtship']['interest_label'] = json_decode($user['profile_courtship']['interest_label'],true) ?: [];
}
//是否关注
$user['is_followed'] = !empty($my_user) ? $my_user->isFollowing($user) : 0;
//是否是超级会员
if ($user['rank_histories'] == []) {
$user['isSuperRank'] = 0;
} else {
$user['isSuperRank'] = 1;
}
$user['photo'] = $user['avatar'];
$user['year'] = substr($user['profile_courtship']['birthday'], 2, 2) . '年';
if (isset($user['profile_courtship']['stature'])) {
$user['stature'] = $user['profile_courtship']['stature'] . 'cm';
}
$user_data[$u] = $user;
}
if($user_data){
$users['data'] = $user_data;
return $this->success('ok.', $users);
}
}
if(!empty($my_user)){
if($my_user->type == 'single'){
$sex = $my_user->sex == 2 ? 1 : 2;
}
}
$age = $age ?: '不限';
$times = CommonUtilsService::searchAge($age);
$province = $province ?: '不限';
$city = $city ?: '不限';
$is_approve = $request->input('is_approve');
$users = User::with('profileCourtship')
->with(['rankHistories' => function ($q) use ($now) {
$q->where('deadline', '>', $now);
$q->select();
}])
->whereHas('profileCourtship', function ($sql) use ($province, $city, $sex, $age, $times, $is_approve) {
if ($province && $province != '不限') {
$sql = $sql->where('province', $province);
}
if ($city && $city != "不限") {
$sql = $sql->where('city', $city);
}
if(!empty($sex)){
$sql = $sql->where('sex', $sex);
}
if (config('app.env') == 'production') {
$sql = $sql->where('is_real_approved', 1);
}
if ($age != '不限') {
$sql = $sql->where('birthday', '>=', $times['start_time'])->where('birthday', '<', $times['end_time']);
} else {
$sql = $sql->where('birthday', '>=', '1986-01-01')->where('birthday', '<', '1998-01-01');
}
if (is_numeric($is_approve)) {
$sql = $sql->where('is_approved', $is_approve);
}
});
if ($keyword) {
$users = $users->where(function ($sql) use ($keyword) {
$sql->where('nickname', 'like', '%' . $keyword . '%');
});
} else {
if (!empty($my_user)) {
$users = $users->photo()->where('belief', $my_user->belief);
}
}
//增加黑名单隐藏
$blacklist_user_ids = !empty($my_user) ? LinkingBlackList::where('user_id', $my_user->id)->pluck('other_user_id')->toArray() : [];
$dislike_user_ids = !empty($my_user) ? $my_user->dislikeLogs()->where('type', 'user')->pluck('type_id')->toArray() : [];
//客服人员
$internal_user = TestUser::get()->pluck('user_id')->toArray();
$unset_user_ids = array_merge($blacklist_user_ids, $dislike_user_ids, User::FULLLINKIDS,$internal_user);
//小程序查看22-35的用户
$users = $users->whereHas('profileCourtship', function ($query) {
$query->whereBetween('birthday', ['1989-01-01 00:00:00', '1999-01-01 00:00:00']);
});
//排除大数据用户
if (!empty($my_user)) {
$RecommendUser_user_ids = RecommendUser::where('user_id', $my_user->id)->whereHas('otherUser', function ($sql) use ($my_user) {
$sql->where('is_approved', 1)
->where('sex', '<>', $my_user->sex)
->where('can_be_found', 1);
})->limit(7)
->orderBy('start_time', 'asc')
->pluck('other_user_id')
->toArray();
$RecommendLinkingNewUserId = RecommendLinkingNew::with('otherUser:id,nickname,is_approved,sex,is_real_approved,rank_id,photo,belief,industry_sub')
->where('id_users_left', $my_user->id)
->pluck('id_users_right')
->toArray();
$recommendLinkingNew_unset_user_ids = array_merge($RecommendUser_user_ids, $RecommendLinkingNewUserId);
$users = $users->whereNotIn('id', $recommendLinkingNew_unset_user_ids);
}
$users = $users->whereNotIn('id', $unset_user_ids);
$users = $users->where('hidden_profile', 'NONE')
->orderBy('rank_id', 'desc')
->where('type', 'single')
->orderBy('is_real_approved', 'desc')
->orderBy('is_approved', 'desc')
->orderBy('liveness', 'desc')
->orderBy('info_complete_score', 'desc')
->orderBy('last_visit', 'desc')
->paginate();
$users = $users->toArray();
$user_data = $users['data'];
for ($u = 0; $u < count($user_data); $u++) {
$user = $user_data[$u];
$user['profile_courtship']['interest_label'] = [];
if($user['profile_courtship']['interest_label']){
$user['profile_courtship']['interest_label'] = json_decode($user['profile_courtship']['interest_label'],true) ?: [];
}
//是否关注
$user['is_followed'] = !empty($my_user) ? $my_user->isFollowing($user) : 0;
//是否是超级会员
if ($user['rank_histories'] == []) {
$user['isSuperRank'] = 0;
} else {
$user['isSuperRank'] = 1;
}
$user['photo'] = $user['avatar'];
$user['year'] = substr($user['profile_courtship']['birthday'], 2, 2) . '年';
if (isset($user['profile_courtship']['stature'])) {
$user['stature'] = $user['profile_courtship']['stature'] . 'cm';
}
$user['profile_courtship']['city']=str_replace('市','',$user['profile_courtship']['city']);
$user_data[$u] = $user;
}
$users['data'] = $user_data;
return $this->success('ok', $users);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('获取用户列表失败,请稍后再试');
}
}
public function isLock()
{
$result = \DB::select("show OPEN TABLES where In_use > 0;");
$is_locked = 0;
if (count($result)) {
foreach ($result as $re) {
if ($re->Table == 'ufutx_recommend_linking') {
$is_locked = 1;
break;
}
}
}
return $is_locked;
}
public function bigDataLink($my_user)
{
//黑名单列表
$recommend_user_list = RecommendUser::where(['user_id' => $my_user->id])
->orderBy('start_time', 'asc')->orderBy('id','asc')->limit(7)
->pluck('other_user_id')
->toArray();
$internal_user = TestUser::get()->pluck('user_id')->toArray();
$unset_user_ids = array_merge($recommend_user_list, $internal_user,User::FULLLINKIDS);
if (request()->page == 1 || empty(request()->page)) {
$ids = RecommendLinkingNew::with('otherUser:id,nickname,is_approved,sex,is_real_approved,rank_id,photo,belief,industry_sub', 'otherUser.profileCourtship:id,user_id,province,city,stature,interest_hobby,birthday,introduction,degree')
->where('id_users_left', $my_user->id)
->whereHas('otherUser', function ($sql) use ($unset_user_ids, $my_user) {
$sql->where('is_recommend', 1)
->whereNotIn('id', $unset_user_ids)
->photo();
})
->limit(100)
->orderBy('score', 'desc')
->orderBy('id','desc')
->pluck('id')->toArray();
shuffle($ids);
Redis::set('user_linking_news_'.$my_user->id, json_encode($ids));
}else {
$ids = Redis::get('user_linking_news_'.$my_user->id);
$ids = json_decode($ids, true);
}
$logs = RecommendLinkingNew::with('otherUser:id,nickname,is_approved,sex,is_real_approved,rank_id,photo,belief,industry_sub', 'otherUser.profileCourtship:id,user_id,province,city,stature,interest_hobby,birthday,introduction,degree')->whereIn('id', $ids)->orderBy(\DB::raw('FIND_IN_SET(id, "' . implode(",", $ids) . '"' . ")"))->paginate(10);
foreach ($logs as $log) {
$log->age = CommonUtilsService::getAge($log->otherUser->profileCourtship->birthday);
$log->year = substr($log->otherUser->profileCourtship->birthday, 2, 2) . '年';
$log->stature = $log->otherUser->profileCourtship->stature . 'cm';
//是否关注
$log->is_followed = $my_user->isFollowing($log->otherUser);
//是否是超级会员
$log->isSuperRank = $log->otherUser->isSuperRank();
$log->photo = $log->otherUser->photo . '?x-oss-process=style/scale1';
$user = $log->otherUser->toArray();
foreach ($user as $key => $value) {
$log->$key = $user[$key];
}
$log->otherUser->profileCourtship->city = str_replace('市','',$log->otherUser->profileCourtship->city );
unset($log->otherUser);
}
if (empty(count($logs))) {
return false;
}
return $logs;
}
//云盾活体检测+实名认证
public function livePersonAudit(Request $request)
{
try {
$user = auth()->user();
$request->validate([
'card_num' => 'required',
'name' => 'required',
]);
//添加身份证号
if ($user->is_real_approved == 1) {
return $this->failure('已认证');
}
// if (empty($user->approve_time)) {
// return $this->failure('无自动认证资格,请通过人工认证');
// }
//是否身份已经验证过
$card_user = User::where('id', '<>', $user->id)->where('card_num', $request->card_num)->where(function ($sql) {
$sql->where('is_approved', 1)->orWhere('is_real_approved', 1);
})->first();
if ($card_user) {
$mobile = substr_replace($card_user->mobile, '****', 3, 4);
$data = [
'type' => 'mobile',
'message' => $mobile
];
return $this->success('ok', $data);
// return $this->fail("认证失败,身份信息已在其他账号".PHP_EOL.$mobile."认证");
}
$yd_service = new YDService();
$result = $yd_service->livePersonAudit($request);
if (empty($result)) {
$data = [
'type' => 'approve',
'message' => '进行重新认证或人工认证'
];
return $this->success('认证失败', $data);
}
if ($result['code'] != 200) {
$data = [
'type' => 'approve',
'message' => $result['msg']
];
return $this->success('认证失败', $data);
}
if (!array_key_exists('status', $result['result']) || $result['result']['status'] != 1) {
$data = [
'type' => 'approve',
'message' => '进行重新认证或人工认证'
];
return $this->success('认证失败', $data);
}
$result['user_id'] = $user->id;
$result['avatar'] = $user->avatar;
\DB::beginTransaction();
if ($user->name != $request->name) {
$user->name = $request->name;
}
if ($user->card_num != $request->card_num) {
$user->card_num = $request->card_num;
}
//认证状态
$user->is_approved = 1;
$user->is_real_approved = 1;
//认证时间
$user->approve_date = date('Y-m-d H:i:s');
$user->save();
//增加认证记录
$history = ApproveHistory::where('user_id', $user->id)->where('type', 'name')->first();
if (empty($history)) {
ApproveHistory::create([
'user_id' => $user->id,
'type' => 'name',
'status' => 1,
'from_platform' => $request->from_platform,
'from_user_id' => $request->from_user_id,
]);
} else {
$history->status = 1;
$history->save();
}
$body_history = ApproveHistory::where('user_id', $user->id)->where('type', 'body')->first();
if (empty($body_history)) {
ApproveHistory::create([
'user_id' => $user->id,
'type' => 'body',
'status' => 1,
'from_platform' => $request->from_platform,
'from_user_id' => $request->from_user_id,
]);
} else {
$body_history->status = 1;
$body_history->save();
}
//更新出生年月日
$user->cardBirthdayToProfile();
\DB::commit();
//缓存用户认证
auth()->user()->updateCacheUser('is_approved');
auth()->user()->updateCacheUser('is_real_approved');
return $this->success('ok');
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
$data = [
'type' => 'approve',
'message' => '进行重新认证或人工认证'
];
return $this->success('认证失败', $data);
}
}
//云盾活体检测+实名认证
public function livePersonAuditV2(Request $request)
{
try {
$user = auth()->user();
if(empty($request->name)) return $this->failure('请输入真实姓名');
if(empty($request->card_num)) return $this->failure('请输入身份证号');
//添加身份证号
if ($user->is_real_approved == 1) {
$data = [
'type' => 1,
'message' => "您已认证"
];
return $this->success('认证失败', $data);
}
// if (empty($user->approve_time)) {
// return $this->failure('无自动认证资格,请通过人工认证');
// }
//是否身份已经验证过
$card_user = User::where('id', '<>', $user->id)->where('card_num', $request->card_num)->where(function ($sql) {
$sql->where('is_approved', 1)->orWhere('is_real_approved', 1);
})->first();
if ($card_user) {
$mobile = substr_replace($card_user->mobile, '****', 3, 4);
$message = "认证失败,身份信息已在其他账号" . PHP_EOL . $mobile . "认证";
$data = [
'type' => 1,
'message' => $message
];
return $this->success('认证失败', $data);
// return $this->fail("认证失败,身份信息已在其他账号".PHP_EOL.$mobile."认证");
}
$yd_service = new YDService();
$result = $yd_service->livePersonAudit($request);
if (empty($result)) {
$data = [
'type' => 1,
'message' => '认证失败,系统繁忙,稍后重试'
];
return $this->success('认证失败', $data);
}
if ($result['code'] != 200) {
$data = [
'type' => 1,
'message' => $result['msg']
];
return $this->success('认证失败', $data);
}
if (!array_key_exists('status', $result['result'])) {
$data = [
'type' => 1,
'message' => '认证失败,系统繁忙,稍后重试'
];
return $this->success('认证失败', $data);
}
if ($result['result']['status'] != 1 && !empty($result['result']['reasonType'])) {
switch ($result['result']['reasonType']) {
case 2:
$type = 1;
$message = '认证失败,姓名身份证号一致,人脸比对非同一人';
break;
case 3:
$type = 1;
$message = '认证失败,姓名身份证号不一致';
break;
case 4:
$type = 3;
$message = "认证失败,活体检测不通过";
$extra = ["1、录制时没有眨眼睛;", "2、录制时间过短请超过3秒时长;", "3、在灯光较暗或曝光下无法识别人脸;", "4、人脸拍摄不全无法检测到人脸;", "5、保持正对手机不要斜视屏幕;", "6、手机网络不顺畅请检查网络状况"];
break;
case 5:
$type = 1;
$message = '认证失败,活体检测超时';
break;
case 6:
$type = 2;
$message = '认证失败,库中无此身份证照片';
break;
case 7:
$type = 2;
$message = '认证失败,库中无此身份证照片';
break;
case 8:
$type = 1;
$message = '认证失败,请勿过于靠近手机屏幕拍摄';
break;
case 9:
$type = 1;
$message = '认证失败,系统繁忙,请稍后重试';
break;
default:
$type = 1;
$message = '认证失败';
break;
}
$data = [
'type' => $type,
'message' => $message
];
if (!empty($extra)) {
$data['extra'] = $extra;
}
return $this->success('认证失败', $data);
}
$result['user_id'] = $user->id;
$result['avatar'] = $user->avatar;
\DB::beginTransaction();
if ($user->name != $request->name) {
$user->name = $request->name;
}
if ($user->card_num != $request->card_num) {
$user->card_num = $request->card_num;
}
//认证状态
$user->is_approved = 1;
$user->is_real_approved = 1;
//认证时间
$user->approve_date = date('Y-m-d H:i:s');
$user->save();
//增加认证记录
$history = ApproveHistory::where('user_id', $user->id)->where('type', 'name')->first();
if (empty($history)) {
ApproveHistory::create([
'user_id' => $user->id,
'type' => 'name',
'status' => 1,
'from_platform' => $request->from_platform,
'from_user_id' => $request->from_user_id,
]);
} else {
$history->status = 1;
$history->save();
}
$body_history = ApproveHistory::where('user_id', $user->id)->where('type', 'body')->first();
if (empty($body_history)) {
ApproveHistory::create([
'user_id' => $user->id,
'type' => 'body',
'status' => 1,
'from_platform' => $request->from_platform,
'from_user_id' => $request->from_user_id,
]);
} else {
$body_history->status = 1;
$body_history->save();
}
if ($result['result']) {
$this->userCon->addLiveperson($result['result']);
}
//更新出生年月日
$user->cardBirthdayToProfile();
\DB::commit();
//缓存用户认证
auth()->user()->updateCacheUser('is_approved');
auth()->user()->updateCacheUser('is_real_approved');
if ($request->has('from_user_id')) {
$from_user = User::find($request->from_user_id);
if ($from_user)
$from_user->addCoinLog('RECSYSTEM', $user->id, 50, '邀请好友认证');
}
StoreApproveWorthShare::dispatch($user->id, $request->from_user_id,$request->chat_user_id)->onQueue('love');
$data = [
'type' => 0,
'message' => '认证成功'
];
//人脸认证图片和账号图片对比
FaceMatchJob::dispatch($user->id)->onQueue('love')->delay(now()->addMinutes(2));;
return $this->success('认证成功', $data);
} catch (\Exception $e) {
\DB::rollback();
$this->getError($e);
$data = [
'type' => 1,
'message' => '认证失败,进行重新认证或人工认证'
];
return $this->success('认证失败', $data);
}
}
//我的邀请数据
public function invitationData(Request $request)
{
// $user_id = auth()->user()->id;
// $from_user_id = $request->input('from_user_id');
// if ($from_user_id && $user_id && $from_user_id != $user_id) {
// //邀请好友赠送1福币
// $count = CoinLog::where('user_id', $from_user_id)->where('type_id', $user_id)->where(function ($query) {
// $query->where('remark', '分享用户')
// ->orWhere('remark', '邀请好友注册');
// })->count();
// if (!$count) {
// $from_user = User::where('id', $from_user_id)->first();
// if ($from_user) {
// //增加福币记录
// CoinLog::create([
// 'user_id' => $from_user_id,
// 'type' => 'RECSYSTEM',
// 'coin' => 1,
// 'type_id' => $user_id,
// 'is_hooked' => 1,
// 'remark' => '分享用户',
// ]);
// //增加剩余福币
// Coin::where('user_id', $from_user_id)->increment('remain_amount', 1);
// }
// }
// }
// //共邀请好友数,已获得福币,可兑换福币
// //获取用户的openid
// $num = 0;
// $openid = auth()->user()->wechat->openid??0;
// if($openid){
// $ids = User::where(function ($query) use ($user_id, $openid) {
// $query->where('from_openid', $openid)
// ->orWhere('from_user_id', $user_id);
// })->pluck('id');
// $num = count($ids);
// }
// $result['user_num'] = CoinLog::where('type', 'RECSYSTEM')->where('user_id', $user_id)->wherenotin('type_id', $ids)->groupBy('type_id')->where('remark', 'like', '%邀请好友%')->get()->count();
// $result['user_num'] = $num;
// $user = auth()->user();
// $user_id = $user->id;
// $openid = auth()->user()->wechat->openid;
// $sql = CoinLog::orderBy('id', 'DESC')->limit(1000);
// $res = CoinLog::select('user_id', 'coin', 'remark', 'type_id', 'created_at')
// ->from(DB::raw('(' . $sql->toSql() . ') as a'))
// ->where('type', 'RECSYSTEM')
// ->where('user_id', $user_id)
// ->where(function($sql) {
// $sql->where('remark', 'like', '%邀请好友%')
// ->orWhere("remark", '分享用户');
// })
// ->groupBy('type_id')
// ->orderBy('id', 'desc')->get()->toarray();
// $user_ids = CoinLog::where('type', 'RECSYSTEM')
// ->where('user_id', $user_id)
// ->where(function($sql) {
// $sql->where('remark', 'like', '%邀请好友%')
// ->orWhere("remark", '分享用户');
// }) ->groupBy('type_id')
// ->pluck('type_id');
// $user = User::select('id as user_id', 'nickname', 'created_at')
// ->wherenotin('id', $user_ids)
// ->where(function ($query) use ($user_id, $openid) {
// $query->where('from_user_id', $user_id)
// ->orWhere('from_openid', $openid);
// })->orderBy('id', 'desc')->get()->toarray();
// $res = array_merge($res, $user);
// $result['user_num'] = count($res);
$user = auth()->user();
$user_id = $user->id;
$openid = $user->wechat->openid;
$user_num = User::where('from_user_id', $user->id)->orWhere("from_openid",$openid)->count();
$result['user_num'] = $user_num;
//总金额
$result['coin'] = CoinLog::where('type', 'RECSYSTEM')->where('user_id', $user_id)->where(function ($query) {
$query->where('remark', 'like', '%邀请好友%')
->orWhere('remark', '分享用户');
})->sum('coin');
//减去提现的金额
$consume_coin = CoinWithdrawLog::where('user_id', $user_id)->wherein('status', [0, 1])->wherein('is_hooked', [0, 1])->where('remark', '邀请好友')->sum('value');
$result['coin'] = $result['coin'] - $consume_coin ?: 0;
$result['totle_coin'] = CoinLog::where('type', 'RECSYSTEM')->where('user_id', $user_id)->where(function ($query) {
$query->where('remark', 'like', '%邀请好友%')
->orWhere('remark', '分享用户');
})->sum('coin');
return $this->success('ok', $result);
}
//我的邀请列表
public function invitationList(Request $request)
{
$user_id = auth()->user()->id;
$openid = auth()->user()->wechat->openid;
$sql = CoinLog::orderBy('id', 'DESC')->limit(1000);
$result = CoinLog::select('user_id', 'coin', 'remark', 'type_id', 'created_at')
->from(DB::raw('(' . $sql->toSql() . ') as a'))
->where('type', 'RECSYSTEM')
->where('user_id', $user_id)
->where(function($sql) {
$sql->where('remark', 'like', '%邀请好友%')
->orWhere("remark", '分享用户');
})
->groupBy('type_id')
->orderBy('id', 'desc')->get()->toarray();
$user_ids = CoinLog::where('type', 'RECSYSTEM')
->where('user_id', $user_id)
->where(function($sql) {
$sql->where('remark', 'like', '%邀请好友%')
->orWhere("remark", '分享用户');
}) ->groupBy('type_id')
->pluck('type_id');
$user = User::select('id as user_id', 'nickname', 'created_at')
->wherenotin('id', $user_ids)
->where(function ($query) use ($user_id, $openid) {
$query->where('from_user_id', $user_id)
->orWhere('from_openid', $openid);
})->orderBy('id', 'desc')->get()->toarray();
$result = array_merge($result, $user);
//根据字段创建时间对数组$data进行降序排列
$created_at = array_column($result, 'created_at');
array_multisort($created_at, SORT_DESC, $result);
$page = $request->page ?? 1;
$perPage = 10;
$offset = ($page * $perPage) - $perPage;
foreach ($result as $key => &$value) {
$value['user_id'] = $value['type_id'] ?? $value['user_id'];
$userinfo = User::where('id', $value['user_id'])->first();
$value['nickname'] = '未知';
$value['nickname'] = $userinfo->nickname ?? $value['nickname'];
$value['avatar'] = '未知';
$value['avatar'] = $userinfo->avatar ?? $value['avatar'];
//判断用户认证的阶段
$value['status'] = 0;
if (!isset($value['remark'])) {
$value['remark'] = '真人认证成功后,可解锁50福币';
$value['status'] = 1;
}
//未查询到用户信息
if (!$userinfo) {
$value['remark'] = '该用户已关闭了资料,未能解锁更多的福币';
$value['status'] = 0;
}
if ($value['remark'] == '邀请好友注册') {
$value['remark'] = '真人认证成功后,可解锁50福币';
$value['status'] = 1;
} elseif ($value['remark'] == '邀请好友认证') {
$value['remark'] = '完成了真人认证,已解锁' . $value['coin'] . '福币';
$value['status'] = 2;
}
unset($value->user, $value->type_id);
}
$result = new LengthAwarePaginator(
array_slice($result, $offset, $perPage, true),
count($result),
$perPage,
$page,
['path' => $request->url(), 'query' => $request->query()]
);
return $this->success('ok', $result);
}
public function invitationListV2(Request $request)
{
$user = auth()->user();
$openid = $user->wechat->openid;
$users = User::where('from_user_id', $user->id)->orWhere("from_openid",$openid)->orderByDesc("id")->paginate();
foreach($users as $user) {
$user->user_id = $user->id;
$status = 0;
if ($user->is_real_approved != 1) {
$user->remark = '真人认证成功后,可解锁50福币';
$status = 1;
}else {
$user->remark = '完成了真人认证,已解锁50福币';
$status = 2;
}
//未查询到用户信息
if ($user->is_real_approved != 1 && $user->hidden_profile == "ALLSEX") {
$user->remark = '该用户已关闭了资料,未能解锁更多的福币';
$status = 0;
}
$user->status = $status;
}
return $this->success('ok', $users);
}
//解锁记录详情
public function RecordDetails(Request $request)
{
$user_id = auth()->user()->id;
if ($request->has('id')) {
$from_user = User::where('id', $request->id)->first();
if (!$from_user)
return $this->failure('该用户不存在或已删除!');
$info['user']['nickname'] = $from_user->nickname ?? '未知';
$info['user']['avatar'] = $from_user->avatar ?? '未知';
$info['user']['mobile'] = $from_user->mobile ?? '未知';
$result = CoinLog::select('user_id', 'coin', 'remark', 'created_at', 'type_id')
->where('type', 'RECSYSTEM')
->where('user_id', $user_id)
->where('remark', 'like', '%邀请好友%')
->where('type_id', $request->id)
->orderBy('id', 'desc')->get()->toarray();
$openid = auth()->user()->wechat->openid;
if (empty($result) && ($from_user->from_user_id == $user_id || $from_user->from_openid == $openid)) {
$info['register']['status'] = 1;
$info['register']['remark'] = '已在其他用户邀请下完成了注册';
$info['register']['type'] = 'old';
$info['register']['time'] = 'after';
$time = date('Y:m:d H:i:s', strtotime($from_user->created_at));
if ($time < '2021:05:01 00:00:00')
$info['register']['time'] = 'front';
$info['register']['created_at'] = date('Y:m:d H:i:s', strtotime($from_user->created_at)) ?? '未知';
$info['realPerson']['remark'] = '';
$info['realPerson']['status'] = 0;
//获取真人认证的时间
$created_at = ApproveHistory::where('user_id', $request->id)->where('status', 1)->where('type', 'body')->value('created_at');
if ($from_user->is_real_approved) {
$info['realPerson']['status'] = 2;
$created_at = date('Y:m:d H:i:s', strtotime($created_at));
$info['realPerson']['created_at'] = $created_at ?? '未知';
}
return $this->success('ok', $info);
}
$data = [];
foreach ($result as $key => $value) {
//状态0为未完成状态1为已完成状态2为已在其他用户邀请下完成
$from_user = User::where('id', $value['type_id'])->first();
$info['register']['status'] = 0;
$info['register']['remark'] = '';
$info['register']['type'] = 'old';
$info['register']['time'] = 'after';
$time = date('Y:m:d H:i:s', strtotime($from_user->created_at));
if ($time < '2021:05:01 00:00:00')
$info['register']['time'] = 'front';
$info['register']['created_at'] = date('Y:m:d H:i:s', strtotime($from_user->created_at)) ?? '未知';
$info['realPerson']['remark'] = '';
$info['realPerson']['status'] = 0;
$info['realPerson']['created_at'] = date('Y:m:d H:i:s', strtotime($value['created_at'])) ?? '未知';
if ($value['remark'] == '邀请好友注册') {
$info['register']['status'] = 1;
$info['register']['type'] = 'new';
$time = date('Y:m:d H:i:s', strtotime($from_user->created_at));
if ($time < '2021:05:01 00:00:00')
$info['register']['time'] = 'front';
$info['register']['created_at'] = date('Y:m:d H:i:s', strtotime($value['created_at']));
$info['register']['remark'] = '完成了手机号注册,已解锁' . $value['coin'] . '福币';
//如果该用户已经在其他用户邀请下认证
$from_user_id = ApproveHistory::where('user_id', $value['type_id'])->value('from_user_id');
if ($from_user->is_real_approved && $from_user_id && $user_id != $from_user_id) {
$info['realPerson']['remark'] = '已在其他用户邀请下完成了真人认证';
$info['realPerson']['status'] = 2;
$info['realPerson']['created_at'] = date('Y:m:d H:i:s', strtotime($value['created_at']));
}
} elseif ($value['remark'] == '邀请好友认证') {
$info['realPerson']['remark'] = '完成了真人认证,已解锁' . $value['coin'] . '福币';
$info['realPerson']['status'] = 1;
$info['realPerson']['created_at'] = date('Y:m:d H:i:s', strtotime($value['created_at']));
}
$data['register'] = $info['register'];
$data['realPerson'] = $info['realPerson'];
$data['user'] = $info['user'];
//查询是否有通知过用户
$result = Message::where('phone', $info['user']['mobile'])->where('code', '邀请好友')->exists();
$data['message'] = $result ?? false;
}
} else {
return $this->failure('获取解锁记录失败,请稍后再试');
}
return $this->success('ok', $data);
}
//福币记录
public function getCoinlog(Request $request)
{
$user_id = auth()->user()->id;
$type = $request->type;
if (!$type)
return $this->failure('获取福币记录失败,请稍后再试');
$query = CoinLog::select('user_id', 'coin', 'remark', 'type_id', 'created_at')
->where('type', 'RECSYSTEM')->where('user_id', $user_id);
if ($type == 'old') {
$result = $query->where(function ($query) {
$query->where('remark', '分享用户')
->orWhere('remark', '邀请好友认证');
})->orderBy('id', 'desc')->paginate();
} else {
$result = $query->Where('remark', 'like', '%邀请好友%')->orderBy('id', 'desc')->paginate(10);
}
$data = [];
foreach ($result as $key => $value) {
$value['user_id'] = $value['type_id'];
if ($value->remark == '邀请好友注册')
$value->remark = '手机号注册';
if ($value->remark == '邀请好友认证')
$value->remark = '真人认证';
$shareUser = User::select('nickname', 'created_at')->where('id', $value['type_id'])->first();
if (!$shareUser) {
$value['nickname'] = '未知';
continue;
}
$value['nickname'] = $shareUser->nickname ?? '未知';
$value['avatar'] = $shareUser->userAvatar($value['type_id']) ?? '未知';
//用户创建时间
$create_time = strtotime($shareUser->created_at);
//活动开始时间
$start_time = strtotime('2021-05-01 00:00:00');
// 老用户
if ($create_time < $start_time && $type == 'new')
unset($result[$key]);
if ($create_time > $start_time && $type == 'old' && $value->remark != '分享用户')
unset($result[$key]);
unset($value['type_id']);
}
return $this->success('ok', $result);
}
//我的邀请用户数量
public function friendsNum(Request $request)
{
$user_id = auth()->user()->id;
//老用户
$old = CoinLog::select('user_id', 'coin', 'remark', 'type_id', 'created_at')
->where('type', 'RECSYSTEM')->where('user_id', $user_id)->where(function ($query) {
$query->where('remark', '分享用户')
->orWhere('remark', '邀请好友认证');
})->orderBy('id', 'desc')->get();
//新用户
$new = CoinLog::select('user_id', 'coin', 'remark', 'type_id', 'created_at')
->where('type', 'RECSYSTEM')
->where('user_id', $user_id)
->Where('remark', 'like', '%邀请好友%')
->orderBy('id', 'desc')->get();
$result['old_friend'] = 0;
$result['new_friend'] = 0;
foreach ($old as $key => $value) {
//用户创建时间
$shareUser = User::select('nickname', 'created_at')->where('id', $value['type_id'])->first();
if (!$shareUser) {
continue;
}
$create_time = strtotime($shareUser->created_at);
//活动开始时间
$start_time = strtotime('2021-05-01 00:00:00');
if ($create_time > $start_time && $value->remark != '分享用户')
unset($old[$key]);
$result['old_friend'] = $old->count();
}
foreach ($new as $key => $value) {
//用户创建时间
$shareUser = User::select('nickname', 'created_at')->where('id', $value['type_id'])->first();
if (!$shareUser) {
continue;
}
$create_time = strtotime($shareUser->created_at);
//活动开始时间
$start_time = strtotime('2021-05-01 00:00:00');
if ($create_time < $start_time)
unset($new[$key]);
$result['new_friend'] = $new->count();
}
return $this->success('ok', $result);
}
public function sendInviteSms(Request $request)
{
$user_id = $request->user_id;
$from_user_id = auth()->user()->id;
$nickname = auth()->user()->nickname ?? '您的好友';
$nickname = mb_substr($nickname, 0, 1, 'utf-8') . '*' . mb_substr($nickname, 2, 1, 'utf-8');
if ($request->has('user_id')) {
$mobile = User::where('id', $user_id)->value('mobile');
if (!$mobile)
return $this->failure('该用户暂未填写手机号,无法发送短信~');
//查询是否有通知过用户
$result = Message::where('phone', $mobile)->where('code', '邀请好友')->count();
if ($result)
return $this->failure('已通知对方');
//获取微信地址
$app = \WechatService::app()->access_token;
$token = $app->getToken(true);
$data = [];
$data['jump_wxa']['path'] = '/pages/users/realName';
$data['jump_wxa']['query'] = 'from_user_id=' . $from_user_id;
$data = json_encode($data);
$wechaturl = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $token['access_token'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_URL, $wechaturl);
// curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$" . $wechaturl, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
$result = json_decode($result, true);
$jump_url = $result['openlink'];
$m = Message::create([
'phone' => $mobile,
'message' => '',
'confirmed' => 1,
'code' => '邀请好友',
'ip' => request() ? request()->ip() : '127.0.0.1',
]);
$message_url = \CommonUtilsService::clickUrl(env('APP_URL').'/h5/#/jump_url?url='.$jump_url,$m->id);
$url = \CommonUtilsService::shortUrl($message_url);
$m->message = '【福恋】嗨,' . $nickname . '和一群有趣的人儿在等你完成真人认证,点击链接(' . $url['url'] . '加入100%真实的交友平台。';
$m->save();
Messenger::sendSMS($mobile, $m->message);
return $this->success('ok', '发送成功');
} else {
return $this->failure('发送信息失败,请稍后再试~');
}
}
/**
* 获取学院,模糊查询学院
*/
public function collegeList(Request $request)
{
$name = $request->input('name');
$list = [];
try {
$list = College::where('name', 'like', '%' . $name . '%')->get();
return $this->success('ok', ['list' => $list]);
} catch (\Exception $e) {
return $this->success('ok', ['list' => $list]);
}
}
// 获取地区
public function countryList(Request $request)
{
$keyword = $request->keyword;
$result = \DB::table('areas')->where('name','like','%'.$keyword.'%')->paginate();
return $this->success('ok',$result);
}
// 获取地区内学校
public function collegeListV2(Request $request)
{
$keyword = $request->keyword;
$result = \DB::table('area_colleges')->where(function($query) use($keyword){
$query->where('name', 'like', '%'.$keyword.'%')->orWhere('ename', 'like', '%'.$keyword.'%');
})->paginate();
return $this->success('ok',$result);
}
/**
* 学信网code认证
*/
public function xxwCodeAuth(Request $request)
{
$user = auth()->user();
$userData = User::where(['id' => $user->id])->first();
if ($userData->is_educate_approved == 1) {
return $this->failure('不能重复认证');
}
$code = $request->input('code');
$url = "https://api.jshdz.cn/xxwyz?code=$code";
$res = $this->vget($url);
if (!$res) {
return $this->failure('no');
}
$res = json_decode($res, true);
if ($res['code'] == 0) {
DB::beginTransaction();
try {
$res = $res['data'];
$user->is_educate_approved = 1;
$user->updateApproveInfo('educate', 1);
ProfileCourtship::where('user_id', $user->id)->update(['degree' => $res['level'], 'graduate_school' => $res['university']]);
DB::commit();
return $this->success('ok');
} catch (\Exception $e) {
DB::rollBack();
return $this->failure('认证失败');
}
} else {
return $this->failure('验证码错误');
}
}
// 模拟提交数据函数
public function vget($url)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
$res = curl_exec($curl); // 执行操作
curl_close($curl); // 关闭CURL会话
return $res; // 返回数据
}
// 获取小程序地址
public function getMiniUrl($id)
{
$app = \WechatService::app()->access_token;
$token = $app->getToken(true);
$data = [];
$data['jump_wxa']['path'] = '/pages/home/information';
$data['jump_wxa']['query'] = 'id=' . $id;
$data = json_encode($data);
$wechaturl = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $token['access_token'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_URL, $wechaturl);
// curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$" . $wechaturl, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
$result = json_decode($result, true);
$jump_url = $result['openlink'];
$path = env('APP_URL').'/h5/#/jump_url?url='.$jump_url;
return $path;
}
//获取小程序跳转短链
public function miniUrl(Request $request)
{
$app = \WechatService::app()->access_token;
$token = $app->getToken(true);
$data = [];
$data['jump_wxa']['path'] = $request->url;
$data['jump_wxa']['query'] = $request->query;
$data['jump_wxa']['env_version'] = $request->env_version;
$data = json_encode($data);
$wechaturl = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $token['access_token'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_URL, $wechaturl);
// curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$" . $wechaturl, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
\Log::info($result);
$result = json_decode($result, true);
$jump_url = $result['openlink'];
$path = env('APP_URL').'/h5/#/jump_url?url='.$jump_url;
$url = \CommonUtilsService::shortUrl($path);
return $this->success('ok',$url);
}
/**
* 用户推荐
*/
public function recommendList(Request $request)
{
$my_user = auth()->user();
if (empty($my_user)) {
$my_user = $this->authCheck();
}
return $this->failure("1111111111", $my_user);
}
/**领取生日礼物 */
public function receiveBirthday(){
$userinfo = $this->getMyUserinfo();
$initial_date = date('Y-01-01');
$rankHistoryCount = RankHistory::where('user_id',$userinfo->id)
->where('created_at','>=',$initial_date)
->where('type','birthday_give')
->count();
if($rankHistoryCount>0){
return $this->failure('你已领取生日礼物,不能重复领取');
}
if($userinfo->is_real_approved <> 1){
return $this->failure('你还未真人认证,请认证完毕后,再来领取会员。');
}
if($userinfo->type != 'single'){
return $this->failure('该生日礼物仅限单身用户领取');
}
if($userinfo->hidden_profile != 'NONE'){
return $this->failure('你资料已关闭,请打开资料后领取');
}
if($userinfo->profileCourtship->birthday){
$my_timestamp=strtotime($userinfo->profileCourtship->birthday);
if(date('m-d') != date('m-d',$my_timestamp)){
return $this->failure('今天不是您的生日,请生日当天前来领取.');
}
}else{
return $this->failure('今天不是您的生日,请生日当天前来领取..');
}
if($userinfo->addSuperRank(0, 1,'birthday_give')){
return $this->success('领取成功');
}
return $this->failure('领取失败');
}
/**测试 */
public function userBirthdayRemind(Request $request){
$CronService = new CronService($this->sms);
$CronService->checkRankDeadline();
}
public function verifyStatisticsArray($sourceType,$sourceId,$context,$errorCode,$errorType,$errorContext,$source_context_field){
VerifyLog::create([
'source_type'=>$sourceType,
'source_id'=>$sourceId,
'source_context'=>$context,
'source_context_field'=>$source_context_field,
'error_code'=>$errorCode,
'error_type'=>$errorType,
'error_context'=>$errorContext
]);
}
/**获取生日领取状态,从注册到今天 过了多少天 */
public function userBirthdayStatus(){
$userinfo = $this->getMyUserinfo();
$initial_date = date('Y-01-01');
$rankHistoryCount = RankHistory::where('user_id',$userinfo->id)
->where('created_at','>=',$initial_date)
->where('type','birthday_give')
->count();
$res['receive_satus'] = 0;
if($rankHistoryCount>0){
$res['receive_satus'] = 1;
}
$res['already_register_day'] = \CommonUtilsService::diffBetweenTwoDays($userinfo->created_at,date('Y-m-d'));
$res['receive'] = $this->userCon->getBirthdayStatus($userinfo);
return $this->success('ok',$res);
}
public function addWorthShare(Request $request)
{
try{
$user_id = $request->input('from_user_id');
if(empty($user_id)) return $this->success('ok');
$target_user = auth()->user();
if(empty($target_user)){
$target_user = $this->authCheck();
}
if(empty($target_user)) return $this->success('ok');
$channel = $request->input('channel');
if(empty($channel)) throw new \Exception('前端未传分享渠道参数');
$product_id = $request->input('product_id');
$data = [
'user_id'=>$user_id,
'target_user_id'=>$target_user->id,
'channel'=>$channel,
'sub_channel'=>'indirect',
'product_id'=>$product_id
];
$share = WorthShare::where($data)->first();
if($share) return $this->success('ok');
$share = WorthShare::addWorthShare($data);
return $this->success('ok');
}catch(\Exception $e){
$this->getError($e);
return $this->success('ok');
}
}
public function unfrozenUser(Request $request,$user_id){
try {
$info = WrongInfoHistories::where('user_id',$user_id)->where('type','frozen')->first();
$user = User::find($user_id);
$user->can_be_found = 1;
$user->hidden_profile = "NONE";
if ($info) $info->delete();
$user->save();
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('解锁失败,请稍后再试');
}
}
/**
* 福恋智能所有平台用户统计
* 福恋+友福同享商城+友福商圈+友福聚会+友福图书馆
*
* @return void
*/
public function userStat()
{
$total = 0;
$total_mobile = 0;
$key = Request()->input('key');
if (empty($key)) return $this->failure("请输入秘钥");
#秘钥是否缓存
$stat_key = Redis::get('user_stat');
if (empty($stat_key)) return $this->failure("秘钥失效");
#秘钥是否正确
if (!Hash::check($stat_key, $key)) return $this->failure("秘钥错误");
//获取福恋H5总用户不含手机号
$viewer_count = Viewer::count();
$total += $viewer_count;
//获取福恋h5总用户含手机号
$viewer_mobile_count = Viewer::whereNotNull('mobile')->count();
$total_mobile += $viewer_mobile_count;
//获取福恋小程序总用户(不含手机号)
$wechat_count = Wechat::count();
$total += $wechat_count;
//获取福恋小程序总用户(含手机号)
$wechat_mobile_count = User::whereNotNull('mobile')->count();
$total_mobile += $wechat_mobile_count;
//获取福恋服务平台总用户(不含手机号)
$merchant_user_count = MerchantUser::count();
$total += $merchant_user_count;
//获取福恋服务平台总用户(含手机号)
$merchant_user_mobile_count = MerchantUser::whereNotNull('mobile')->count();
$total_mobile += $merchant_user_mobile_count;
//获取福恋服务平台总用户(不含手机号)
$merchant_account_count = MerchantAccount::count();
$total += $merchant_account_count;
//获取福恋服务平台总用户(含手机号)
$merchant_account_mobile_count = MerchantAccount::whereNotNull('mobile')->count();
$total_mobile += $merchant_account_mobile_count;
//获取图书馆总用户
$url = env('LIBRARY_URL', 'http://library.ufutx.com').'//users/stat?key='.$key;
$library_res = json_decode(Http::get($url));
\Log::info($url);
if (is_array($library_res)){
$total += $library_res[0]->data;
$total_mobile += $library_res[1]->data;
} else {
$library_res =[] ;
}
//获取聚会总用户(不含手机号)
$url = env('PARTY_URL', 'http://party.ufutx.com').'//users/stat?key='.$key;
\Log::info($url);
$party_res = json_decode(Http::get($url));
if (is_array($party_res)){
$total += $party_res[0]->data;
$total_mobile += $party_res[1]->data;
}else{
$party_res = [];
}
//获取商圈总用户(不含手机号)
$url = env('MCIRCLE_URL', 'http://mcircle.ufutx.com').'//users/stat?key='.$key;
\Log::info($url);
$mcircle_res = json_decode(Http::get($url));
if (is_array($mcircle_res)){
$total += $mcircle_res[0]->data;
$total_mobile += $mcircle_res[1]->data;
}else{
$mcircle_res = [];
}
$data = [
['data'=>$viewer_count, 'desc'=> '福恋H5用户'],
['data'=>$viewer_mobile_count, 'desc'=> '福恋H5用户含手机号'],
['data'=>$wechat_count, 'desc'=> '福恋小程序用户'],
['data'=>$wechat_mobile_count, 'desc'=> '福恋小程序用户(含手机号)'],
['data'=>$merchant_user_count, 'desc'=> '福恋服务平台用户'],
['data'=>$merchant_user_mobile_count, 'desc'=> '福恋服务平台用户(含手机号)'],
['data'=>$merchant_account_count, 'desc'=> '福恋服务商'],
['data'=>$merchant_account_mobile_count, 'desc'=> '福恋服务商(含手机号)'],
];
$total_data = [
['data'=>$total, 'desc'=> '用户总量'],
['data'=>$total_mobile, 'desc'=> '用户总量(含手机号)'],
];
$data = array_merge($data, $library_res, $party_res,$mcircle_res,$total_data);
return $this->success('ok', $data);
}
public function userStatKey()
{
$key = 'user_stat';
$value = time()."_user_stat";
Redis::setex($key,600,$value);
$secret = Hash::make($value);
return $secret;
}
/**
* 获取手机国家区号
* @param Request $request
* @return \Illuminate\Http\JsonResponse|string
*/
public function getNationMobileCode(Request $request)
{
$area_code_string = file_get_contents(public_path().'/nation_mobile_area_code.json');
$area_code = json_decode($area_code_string,true);
return $this->success('ok',$area_code);
}
/**
* 增加基表账号
*/
public function createUnionUser(Request $request)
{
try {
$mobile = $request->input('mobile');
if (empty($mobile)) return $this->failure('缺少账号信息');
$password = $request->input('password');
if (empty($password)) return $this->failure('缺少密码信息');
$union_user = $this->userCon->addUnionUser($mobile, $password);
return $this->success('ok', $union_user);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('创建基表账号失败');
}
}
/**
* 是否可以領取訪客會員
* @param Request $request
*/
public function canGainVisitorRank(Request $request)
{
try {
$from_platform = $request->input('from_platform');
\Log::info('渠道'.$from_platform);
//是否含短信渠道
$prew_deadline = RankHistory::withTrashed()->where('user_id', auth()->id())->where('type','preview')->value('deadline');
$deadline = RankHistory::where('user_id', auth()->id())->orderBy('deadline', 'desc')->value('deadline');
$can_gain = empty($prew_deadline) && empty($deadline)?1:0;
return $this->success('ok', compact('deadline', 'can_gain'));
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器等待~');
}
}
/**
* 用户通过短信获取访问会员
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\View\View
*/
public function gainVisitorRank(Request $request)
{
try {
$user = auth()->user();
//是否含短信渠道
if ($request->input('from_platform') != 'sms_preview') return $this->failure('领取失败,不支持领取');
//是否已领取
$deadline = RankHistory::withTrashed()->where('user_id', $user->id)->where('type','preview')->value('deadline');
$can_gain = $deadline?0:1;
if (empty($can_gain)) return $this->failure("领取失败,已领取过");
//赠送一天访客会员
$user->addSuperRank(1, 0, 'preview');
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure('服务器等待~');
}
}
/**
* 用户基本资料
* @param Request $request
*/
public function baseUserInfo(Request $request)
{
try {
$user = User::where('id', auth()->id())->select('id', 'photo', 'nickname', 'mobile','type', 'rank_id', 'sex', 'belief')->first();
$user->profile_courtship = $user->profileCourtship()->where('user_id', $user->id)->select('id', 'user_id', 'sex', 'belief', 'birthday', 'state', 'province', 'city')->first();
unset($user->profileCourtship);
return $this->success('ok', $user);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
/**
* 修改基本资料
* @param Request $request
*/
public function updateBaseUserInfo(Request $request)
{
try {
DB::beginTransaction();
$result = $this->checkBaseInfo();
if ($result) return $this->failure($result);
$user = auth()->user();
$original_user_id = $user->id;
if ($request->has('mobile') && $request->mobile != $user->mobile) {
//手机号检测 合并账号
$user = $this->checkUserWithMobile($user, $request->mobile);
$user_info = UserInfo::firstOrCreate(['user_id'=>$user->id]);
$user_info->bind_mobile_at = date('Y-m-d H:i:s');
$user_info->save();
//todo teambiton D65
//小天使账号发起好友申请
$this->addLoveLinking($user);
}
$profile = $user->profileCourtship;
if(!$profile){
$profile = new ProfileCourtship;
$profile->user_id = $user->id;
}
if ($request->has('photo') && $request->photo != $user->photo) {
$user->photo = $request->photo;
}
if ($request->has('nickname') && $request->nickname != $user->nickname) {
$user->nickname = $request->nickname;
//可疑昵称报警
$this->sendNicknameNotice($user);
}
if ($request->has('birthday') && $request->birthday != $profile->birthday) {
$profile->birthday = $request->birthday;
}
if ($request->has('sex') && $request->sex != $user->sex) {
$user->sex = $profile->sex = $request->sex;
SignActitityMember::dispatch($user->id)->onQueue('love');
}
if ($request->has('province') && $request->province != $profile->province) {
$profile->province = $request->province;
}
if ($request->has('city') && $request->city != $profile->city) {
$profile->city = $request->city;
}
if ($request->has('state') && $request->state != $profile->state) {
$profile->state = $request->state;
if ($profile->state == "已婚") {
$user->type = "marriage";
}
}
if ($request->has('belief') && $request->belief != $user->belief) {
$user->belief = $profile->belief = $request->belief;
}
$user->save();
$profile->save();
DB::commit();
//是否游客 01
$user->is_visitor = $user->is_visitor;
//基础资料
$user->is_base_info = $this->userCon->isCompleteBaseInfo($user);
//是否更新登录token
$user->token = $user->id == $original_user_id?'':$user->createToken($user->mobile)->accessToken;
return $this->success('ok', $user);
}catch (\Exception $e) {
DB::rollback();
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
public function sendNicknameNotice($user)
{
if (strpos($user->nickname , 'frank' ) !== false || strpos($user->nickname, 'Frank' ) !== false) {
$data['touser'] = 'oPC_2vneOWpQbicNZQAUCxuwZ4mw';
$data['template_id'] = config('wechat.tpls.error_notice');
$data['url'] = '';
$data['data'] = [
'first' => '可疑用户提示',
'keyword1' => '用户['.$user->nickname.']id--'.$user->id,
'keyword2' => '福恋',
'keyword3' => date('Y-m-d H:i:s'),
'remark' => '',
];
SendTemplateMsg::dispatch($data)->onQueue('error_email');
}
}
/**
* 检查手机号是否存在其他账号
* @param $user
* @param $mobile
*/
public function checkUserWithMobile($user, $mobile)
{
$mobile_user = User::where('mobile', $mobile)->where('id', '<>', $user->id)->first();
if ($mobile_user) { //存在手机号对应其他账号
if ($mobile_user->wechat) {
$openid = $user->wechat->openid;
$user->wechat->forceDelete();
$user->forceDelete();
$mobile_user->wechat->update(['openid'=>$openid]);
}else {
Wechat::where("user_id", $user->id)->update(['user_id'=>$mobile_user->id]);
$user->forceDelete();
}
return $mobile_user;
}
$user->mobile = $mobile;
return $user;
}
/**
* 添加客服账号好友申请
* @param $user
*/
public function addLoveLinking($user)
{
$user_linking_id = 69938;
$linking_id = LinkingRequest::where(['user_id' => $user->id, 'user_linking_id' => $user_linking_id])->where('status', 0)->value('id');
if(!$linking_id){
$linking_request = new LinkingRequest;
$linking_request->user_id = $user->id;
$linking_request->user_linking_id = $user_linking_id;
$linking_request->status = 0;
$linking_request->message = '欢迎来到福恋,平台现有牵线服务和公众号推荐,你也可多发动态增加曝光,有任何问题都可以联系我,祝你早日找到合适的对象。';
$linking_request->save();
//发送系统消息
$content = $user->nickname . '您好,福恋官方 申请加你为好友!';
$message = '欢迎来到福恋,平台现有牵线服务和公众号推荐,你也可多发动态增加曝光,有任何问题都可以联系我,祝你早日找到合适的对象。';
$notice = $this->sendNotice($user->id, $user_linking_id, 'friend', $content, $message);
//订阅消息通知
$ful_user = User::find($user_linking_id);
SendSubTemplateMsg::dispatch($type = 'friend_request', $ful_user, $user)->onQueue('template_message');
//App推送消息
SendIMPushMsg::dispatch($notice->id, 'friend', $content, $user->id, $user->id, $user->userAvatar())->onQueue('love');
}
}
/**
* 检测修改基本资料内容安全
* @return false|string|void
*/
public function checkBaseInfo() {
try {
// if (request()->has('mobile')) {
// $result = $this->userCon->checkMobile(request()->mobile);
// if($result) return $result;
// }
if (request()->has('photo')) {
//头像内容安全
$result = CommonUtilsService::imageContentCecurity([request()->input('photo')]);
if ($result && isset($result['result']) && $result['result']) {
return '图片' . $result['result'] . ',请换一张照片';
}
}
//文本内容检测;
if (request()->has('nickname')) {
if (request()->nickname && (mb_strlen(request()->nickname) >12 || mb_strlen(request()->nickname) <2)) {
return "您输入的昵称有误字数不在2~12之间";
}
$result = \CommonUtilsService::textContentCecurity([request()->nickname]);
if ($result && $result['result']) {
return '您填写的内容【' . $result['context'] . "】:" . $result['result'] . ",请重新输入";
}
}
return '';
}catch (\Exception $e) {
$this->getError($e);
return false;
}
}
public function updateUserMobile(Request $request) {
try {
//检查手机号
$mp = EasyWechat::miniProgram();
$session = $this->getWechatSession($request->code);
if (!isset($session['session_key'])) throw new \Exception("缺少session_key".json_encode($session), 1);
$raw_data = $mp->encryptor->decryptData($session['session_key'], $request->iv, $request->encryptedData);
$mobile = $raw_data['phoneNumber'];
// $unionid = $raw_data['unionid'];
$user = auth()->user();
//修改手机号
if ($mobile != $user->mobile) {
$user->mobile = $mobile;
}
// if ($unionid != $user->wechat->unionid) {
// $user->wechat->unionid = $unionid;
// }
$user->save();
$user->wechat->save();
return $this->success('ok', $raw_data);
}catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
/**
* 修改用户unionid
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\View\View
*/
public function updateWechatUnionid(Request $request)
{
try {
$code = $request->input('code');
if (empty($code)) throw new \Exception('未获取到code信息');
$mp = EasyWechat::miniProgram();
$session = $mp->auth->session($code);
if (!isset($session['unionid'])) throw new \Exception("code换取微信信息失败");
$unionid = $session['unionid'];
$wechat = auth()->user()->wechat;
if ($unionid != $wechat->unionid) $wechat->unionid = $unionid;
$wechat->save();
return $this->success('ok');
} catch (\Exception $e) {
$this->getError($e);
return $this->failure("服务器休息,请稍后再试");
}
}
//
public function noticeSetting(Request $request){
//类型 label:夸夸我提醒 message:新消息提醒
$type = $request->input('type','label');
$user = auth()->user();
$info = UserInfo::firstOrCreate(['user_id'=>$user->id]);
if($type && $type == 'label'){
//当前用户夸夸我状态
$new_label_notice = $info->label_notice == 1 ? 0 : 1;
$info->update(['label_notice'=>$new_label_notice]);
}elseif($type && $type == 'message'){
//当前用户新消息提醒状态
$new_message_notice = $info->message_notice == 1 ? 0 : 1;
$info->update(['message_notice'=>$new_message_notice]);
}
return $this->success('ok');
}
public function approveInfo(Request $request)
{
$user = auth()->user();
$this->tencentRealApproveRes($user->id);
//认证次数
$approve_num = ApproveHistory::where('user_id',$user->id)->where('type','body')->value('num');
$data = [
'name' => $user->name,
'card_num' => $user->card_num,
'is_real_approved' => $user->is_real_approved,
'approve_num' => $approve_num ?: 0
];
return $this->success('ok', $data);
}
public function tencentRealApprove(Request $request)
{
try {
$user = auth()->user();
$name = $request->input('name');
$card_num = $request->input('card_num');
if(empty($name)) return $this->failure('请输入真实姓名');
if(empty($card_num)) return $this->failure('请输入身份证号');
//证件是否已认证
$exists = User::where('card_num', $card_num)->where('is_approved', 1)->where('id', '<>', $user->id)->exists();
if ($exists) return $this->failure("证件信息存在其他账号");
$merchant_id = '0NSJ2212081323066409';
$result = CommonUtilsService::tencentFaceid($merchant_id, $name, $card_num, '');
if (empty($result)) return $this->failure();
DB::beginTransaction();
//记录信息
ApproveHistory::updateOrCreate(['user_id'=>$user->id, 'type'=>'name'], [
'ways'=>0,
'status'=>0,
'from_platform'=>$request->input('from_platform'),
'from_user_id'=>$request->input('from_user_id')
]);
$log = ApproveHistory::where('user_id',$user->id)->where('type','body')->first();
$log = ApproveHistory::updateOrCreate(['user_id'=>$user->id, 'type'=>'body'], [
'ways'=>0,
'status'=>0,
'url'=>$result->Url,
'eid_token'=>$result->EidToken,
'from_platform'=>$request->input('from_platform'),
'from_user_id'=>$request->input('from_user_id'),
'num' => $log ? $log->num + 1 : 1,//认证次数
]);
//修改认证信息
$user->card_num = $card_num;
$user->name = $name;
$user->save();
DB::commit();
//异步查询认证结果
SyncTencenFaceid::dispatch($user->id)->onQueue('love')->delay(now()->addMinutes(2));
return $this->success('ok', $log);
}catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure();
}
}
/**
* 认证结果
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
*/
public function tencentRealApproveRes($user_id)
{
try {
$log = ApproveHistory::where("user_id", $user_id)->where('type', 'body')->orderBy('id', 'desc')->first();
if (empty($log) || $log->status || $log->ways) return $this->success('ok');
$res = CommonUtilsService::tencentFaceidRes($log->eid_token);
if (isset($res->Text) && isset($res->Text->ErrCode) && $res->Text->ErrCode == 0) {
//认证成功 修改认证状态
DB::beginTransaction();
User::where("id", $user_id)->update(['is_approved'=>1,'is_real_approved'=>1]);
ApproveHistory::where('user_id', $user_id)->whereIn('type', ['name', 'body'])->update(['status'=>1]);
DB::commit();
//更新出生年月日
$user = User::find($user_id);
$user->cardBirthdayToProfile();
//缓存用户认证
$user->updateCacheUser('is_approved');
$user->updateCacheUser('is_real_approved');
return $this->success('ok');
}
return $this->failure("认证失败,请核查认证信息!");
}catch (\Exception $e) {
DB::rollBack();
$this->getError($e);
return $this->failure();
}
}
public function aloneCsQrcode()
{
try {
$user = auth()->user();
$data = ['qrcode' => ''];
$res = CrmUserLog::with([
'role' /*=> function ($q) {
$q->where('type', 'c_service');
}*/
])
->where('user_id', $user->id)
->where('status',1)
->first();
if ($res) $data['qrcode'] = $res->role->qrcode;
return $this->success('ok', $data);
} catch (\Exception $e) {
$this->getError($e);
return $this->failure($e->getMessage());
}
}
public function aloneCsList()
{
try {
// $user = auth()->user();
$data = CrmRole::with('user:id,nickname,name,photo,app_avatar,mobile')
->where('is_show',1)
->where('type','c_service')
->orderBy('sort')
->get();
// foreach ($data as $item){
// if($item->id == 51){
// $item->user->nickname = '小天使·福恋客服';
// $item->user->avatar = 'https://image.fulllinkai.com/202203/22/6e724a72f84c6352d21555fd5fdd535f.?x-oss-process=style/scale1';
// $item->user->photo = 'https://image.fulllinkai.com/202203/22/6e724a72f84c6352d21555fd5fdd535f.?x-oss-process=style/scale1';
// }
// }
return $this->success('ok',$data);
}catch (\Exception $e) {
$this->getError($e);
return $this->failure();
}
}
public function aloneCsAdd(Request $request)
{
try {
$user = auth()->user();
$role_user_id = $request->input('role_user_id');
if(empty($role_user_id)) $this->failure('请选择专属客服');
$role_id = CrmRole::where('user_id',$role_user_id)->value('id');
if(empty($role_id)) $this->failure('客服不存在');
$crm_user = CrmUser::firstOrCreate(['user_id'=>$user->id]);
CrmUser::where('id', $crm_user->id)->update(['step'=>'pre_sale', 'status'=>1]);
CrmUserLog::create(['user_id'=>$crm_user->user_id, 'role_id'=>$role_id, 'role_user_id'=>$role_user_id, 'status'=>1]);
return $this->success('添加成功');
}catch (\Exception $e) {
$this->getError($e);
return $this->failure($e->getMessage());
}
}
/**
* 好友请求列表v2
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\View\View
*/
public function friendRequestLogsV2(Request $request)
{
try {
$type = $request->input('type'); // send 发出的好友请求 receive收到的好友请求
if(!in_array($type,['send','receive'])) return $this->failure('type error');
$user_id = auth()->user()->id;
// $list = new LinkingRequest;
switch ($type) {
case 'send':
$list = LinkingRequest::where('user_linking_id', $user_id)->with('receiveUser:id,nickname,sex,type,photo,app_avatar,circle_avatar,is_real_approved');
break;
case 'receive':
$list = LinkingRequest::where('user_id', $user_id)->with('otherUser:id,nickname,sex,type,photo,app_avatar,circle_avatar,is_real_approved');
break;
default:
return $this->success('ok');
}
$list = $list->orderBy('created_at', 'desc')->paginate();
$time = time();
$ids = [];
foreach ($list as $item) {
$ids[] = $item->id;
$item->refuse_tag = $item->refuse_tag ? json_decode($item->refuse_tag, true) : [];
//发送者
if ($type == 'receive' && $item->otherUser) {
if ($item->otherUser->type == 'single') {
$birthday = ProfileCourtship::where('user_id', $item->user_linking_id)->value('birthday');
} else {
$birthday = ProfileMarriage::where('user_id', $item->user_linking_id)->value('birthday');
}
$item->otherUser->age = $birthday ? $this->getAge($birthday) : 0;
$item->otherUser->is_super_rank = $item->otherUser->isSuperRank($item->otherUser->id);
}
//接收者
if ($type == 'send' && $item->receiveUser) {
if ($item->receiveUser->type == 'single') {
$birthday = ProfileCourtship::where('user_id', $item->user_id)->value('birthday');
} else {
$birthday = ProfileMarriage::where('user_id', $item->user_id)->value('birthday');
}
$item->receiveUser->age = $birthday ? $this->getAge($birthday) : 0;
$item->receiveUser->is_super_rank = $item->receiveUser->isSuperRank($item->receiveUser->id);
}
if ($item->status == 0 && date('d', $time - strtotime($item->created_at)) > 7) {
//状态 过期
$item->status = 2;
}
}
if($type == 'receive'){
LinkingRequest::where('user_id',$user_id)->update(['read_status' => 1]);
Notice::where('user_id',$user_id)->where('type','friend')->update(['status' => 1]);
}
return $this->success('ok', $list);
}catch (\Exception $e){
$this->getError($e);
return $this->failure($e->getMessage());
}
}
/**
* 处理好友请求v2
* @param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\View\View
*/
public function dealFriendRequestV2(Request $request)
{
try {
$user = auth()->user();
$user_id = $user->id;
$id = $request->input('id');
if (empty($user_id)) return $this->failure('参数错误');
$status = $request->input('status');
if (empty($status)) return $this->failure('参数错误');
$link_request = LinkingRequest::find($id);
if(!$link_request) return $this->failure('好友请求不存在');
if($link_request->status != 0) return $this->failure('好友请求已处理');
$send_user_id = $link_request->user_linking_id;
$send_user = User::find($send_user_id);
$result = [];
if ($status == 1) {
//添加好友
$linking = $this->userCon->setLinking($send_user_id, $user_id);
//添加网易好友
$result = $user->addIMFriend($send_user);
if ($result) {
$linking->is_im = 1;
$linking->save();
}
//发送IM消息
if (config('app.env') == 'production') {
$im_service = new IMService(env('IM_APP_KEY'), env('IM_APP_SECRET'));
$body = ['msg' => $link_request->message];
$option = ['push' => true, 'route' => true];
$result = $im_service->sendMsg($send_user_id, 0, auth()->id(), 0, $body, $option);
}
//发送好友处理消息
SendSubTemplateMsg::dispatch("deal_friend_request", $user, $send_user)->onQueue("template_message");
}elseif($status == -1){
//拒绝添加好友
$reply = $request->reply;
$refuse_tag = $request->refuse_tag;
if(is_array($refuse_tag)){
$link_request->refuse_tag = json_encode($refuse_tag);
}
$link_request->reply = $reply;
}
$link_request->status = $status;
$link_request->save();
return $this->success('ok',$result);
}catch (\Exception $e){
$this->getError($e);
return $this->failure($e->getMessage());
}
}
}