<?php


namespace App\Services;


use App\Http\Params\ProblemParam;
use App\Models\DynamicModel;
use App\Models\PaymentLogModel;
use App\Models\User;
use App\Models\UserBlacklistModel;
use App\Models\UserComment;
use App\Models\UserInfoModel;
use App\Models\UserInviteLog;
use App\Models\UserLookModel;
use App\Models\UserProblemModel;
use App\Models\UserVipLogModel;
use App\Models\VipModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Util\Exception;
use function Symfony\Component\Translation\t;

class UserService
{
    /**
     * 问题反馈
     */
    public function problem(ProblemParam $param){
        if(empty($param->content)){
            throw new Exception("请输入问题");
        }
        $ins = array();
        $ins['user_id'] = $param->user_id;
        $ins['content'] = htmlspecialchars($param->content);
        $ins['img_url'] = json_encode($param->img_url);
        $ins['status'] = $param->status;
        UserProblemModel::query()->create($ins);
        return true;
    }

    /**
     * 看过我
     */
    public function looked_me(){
        $user = auth('api')->user();

        //不看拉黑用户
        $black_list = UserBlacklistModel::query()
            ->where('user_id',$user->id)
            ->orWhere('black_id',$user->id)
            ->select(['black_id'])
            ->get()
            ->toArray();
        $ids = array_column($black_list,'black_id');
        $ids[]= $user->id;


        $res = UserLookModel::query()
            ->with(['user'=>function($query){
                $query->select('id','sex','is_vip','tencent_im_user_id');
            },'user_info'])
            ->where('look_id',$user->id)
            ->whereNotIn('user_id',$ids)
            ->whereHas("user",function($query){
                $query->where('is_distory',0)->select();
            })
            ->groupBy('user_id')
            ->orderByDesc('atime')
            ->paginate(request('perPage',20));
        $res = $res->toArray();
        //改变看过状态
        UserLookModel::query()->where(['user_id'=>$user->id])->update(['status'=>1]);
        foreach ($res['data'] as $k=>$v){
            $v_user = User::query()->where(['id'=>$v['user_id']])->first();
            if(!$v_user['latitude'] || !$v_user['longitude']){
                $distance = 0;
            }else{
                $distance = GetDistance($user->latitude,$user->longitude,$v_user['latitude'],$v_user['longitude']);
            }
            $res['data'][$k]['distance'] = $distance;
        }

        return $res;
    }

    /**
     * 购买vip
     */
    public function buy_vip($param){
        if($param['payment']!=1 && $param['payment']!=2){
            //throw new Exception("支付选择参数错误");
            $param['payment']=1;
        }
        if(empty($param['id'])){
            throw new Exception("参数错误");
        }
        if(!$vip_info = VipModel::query()->where('id',$param['id'])->first()){
            throw new Exception("VIP不存在");
        }
        $ins = array();
        $ins['order_no'] = create_order_number();
        $ins['user_id'] = $param['user_id'];
        $ins['price'] = $vip_info['price'];
        $ins['status'] = 0;
        $ins['content'] = json_encode($vip_info);
        $ins['type'] = 1;
        $ins['payment'] = $param['payment'];
        if(!PaymentLogModel::query()->create($ins)){
            throw new Exception("插入订单失败");
        }

        $pay_param = [
            'out_trade_no' => $ins['order_no'],
            'body' => '购买VIP',
            'total_fee' => $ins['price'],
            'payment' => $ins['payment'],
        ];

        return PayService::pay($pay_param);
    }


    /**
     * 黑名单
     */
    public function black_list(){
        $user = auth('api')->user();
        $res = UserBlacklistModel::query()
            ->leftJoin('users_info','users_blacklist.black_id','=','users_info.user_id')
            ->select(['users_blacklist.id','users_info.user_id','users_info.avatar','users_info.nickname'])
            ->where('users_blacklist.user_id','=',$user->id)
            ->paginate(request('prePage',20));
        return $res;
    }

    /**
     * 移除黑名单
     */
    public function del_black($id){
        if(empty($id)){
            throw new Exception("参数错误");
        }
        $user = auth('api')->user();
        if(!$black = UserBlacklistModel::query()->where(['id'=>$id,'user_id'=>$user->id])->first()){
            throw new Exception("对方不在你的黑名单中");
        }
        $black_user = User::query()->where('id',$black->black_id)->first();

        $tencentim = new TencentImFriendService();
        $tencentim->friend_black_del($user->tencent_im_user_id,$black_user->tencent_im_user_id);

        $black->delete();
        return true;
    }

    /**
     * 设置隐身和通知开关
     */
    public function online_status($request){
        $user = auth('api')->user();
        if(isset($request->online)){
            $user->online = $request->online;
            $user->save();
        }
        if(isset($request->notice_status)){
            $user->notice_status = $request->notice_status==1?0:1;
            $user->save();
        }
        return ['online'=>$user->online,'notice_status'=>$user->notice_status];
    }

    /**
     * 获取邀请福利信息
     */
    public function invite_info(){
        $user = auth('api')->user();
        $res['ycode'] = $user->ycode;
        $res['code_url'] = "https://".$_SERVER['HTTP_HOST'].'/web/register.html?invoce='.$user->ycode;
        //总邀请用户
        $res['total_user'] =User::query()->where(['pid'=>$user->id])->count();
        //待领取天数
        $res['unclaimed'] = UserInviteLog::query()->where(['user_id'=>$user->id,'status'=>0])->sum('day');
        //累计领取天数
        $res['total_day'] = UserInviteLog::query()->where(['user_id'=>$user->id,'status'=>1])->sum('day');
        //奖励规则
        $res['rule'] = DB::table("document")->where(['id'=>4])->value('content');
        return $res;
    }

    /**
     * 获取邀请用户列表
     * @param $requset
     */
    public function get_invite_list(){
        $user = auth('api')->user();
        $list = User::query()
            ->where(['users.pid'=>$user->id])
            ->leftJoin('users_info','users.id','=','users_info.user_id')
            ->select(['users.id','users.created_at','users.is_vip','users_info.nickname'])
            ->orderBy('id','desc')
            ->paginate(request('prePage',10));
        $list = $list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['created_at'] = date('Y/m/d',strtotime($v['created_at']));
        }
        return $list;
    }

    /**
     * 领取会员天数
     */
    public function receive_day(){
        $user = auth('api')->user();
        $day = UserInviteLog::query()->where(['user_id'=>$user->id,'status'=>0])->sum('day');
        if($day>0){
            UserInviteLog::query()->where(['user_id'=>$user->id,'status'=>0])->update(['status'=>1]);
            if($user->is_vip==0){
                $user->is_vip = 1;
                $user->save();
            }
            //变更vip记录
            $user_vip_log = UserVipLogModel::query()->where(['user_id'=>$user->id])->first();
            if(!$user_vip_log){
                UserVipLogModel::query()->create([
                    'user_id'=>$user->id,
                    'status'=>1,
                    'day'=>$day,
                    'end_day'=> date("Y-m-d H:i:s",strtotime("+".$day." day")),
                ]);
            }elseif($user_vip_log->status==1){
                $user_vip_log->end_day = date("Y-m-d H:i:s",strtotime($user_vip_log->end_day."+".$day." day"));
                $user_vip_log->save();
            }elseif ($user_vip_log->status==0){
                $user_vip_log->end_day = date("Y-m-d H:i:s",strtotime("+".$day." day"));
                $user_vip_log->status = 1;
                $user_vip_log->save();
            }
        }else{
            throw new Exception("暂无可领取天数");
        }
        return true;
    }


    /**
     * 删除图片
     */
    public function del_file(Request $request){
        $user = auth('api')->user();
        $url = $request->post('url');
        if($url==''){
            throw new Exception("请选择要删除的图片");
        }
        $type = $request->post('type',1);
        $userinfo = UserInfoModel::query()->where('user_id',$user->id)->first();
        if($type==1){
            //删除相册
            $photo = json_decode($userinfo['photo'],true);
            if(count($photo)>0){
                $has = false;
                foreach ($photo as $k=>$v){
                    if($v['url']==$url){
                        $has = true;
                        del_file($v['url']);
                        unset($photo[$k]);
                        break;
                    }
                }
                if(!$has){
                    throw new Exception("删除错误");
                }else{
                    $upd['photo'] = array_values($photo);
                }
            }else{
                throw new Exception("删除错误");
            }
        }else{
            //删除视频
            $video = json_decode($userinfo['video'],true);
            if(count($video)>0){
                $has = false;
                foreach ($video as $k=>$v){
                    if($v['url']==$url){
                        $has = true;
                        del_file($v['url']);
                        unset($video[$k]);
                        break;
                    }
                }
                if(!$has){
                    throw new Exception("删除错误");
                }else{
                    $upd['video'] = array_values($video);
                }
            }else{
                throw new Exception("删除错误");
            }
        }
        UserInfoModel::query()->where('user_id',$user->id)->update($upd);
    }

    //注销用户
    public function distory_user(){
        $user = auth('api')->user();
        //修改用户
        User::query()->where('id',$user->id)->update(['is_distory'=>1]);
        //修改用户信息
        UserInfoModel::query()->where('user_id',$user->id)->update([
            'avatar'=>"https://zhengda.oss-cn-chengdu.aliyuncs.com/chengluApp/default.jpg",
            'nickname'=>"用户已注销",
        ]);
        //删除用户动态
        DynamicModel::query()->where('user_id',$user->id)->delete();
        return true;
    }


    //注销用户（彻底删除用户数据）
    public function delete_user(){
        $user = auth('api')->user();
        //删除用户
        User::query()->where('id',$user->id)->delete();
        //删除用户信息
        UserInfoModel::query()->where('user_id',$user->id)->delete();
        //删除用户黑名单
        UserBlacklistModel::query()->where('user_id',$user->id)->delete();
        //删除用户评价
        UserComment::query()->where('user_id',$user->id)->delete();
        //删除用户邀请记录
        UserInviteLog::query()->where('user_id',$user->id)->delete();
        //删除用户喜欢



        //删除用户动态


    }
}

