<?php


namespace App\Http\Controllers\Api;
use App\Exceptions\SmsException;
use App\Http\Params\ProblemParam;
use App\Models\SystemConfig;
use App\Models\User;
use App\Models\UserInfoModel;
use App\Models\UserInviteLog;
use App\Models\UserLookModel;
use App\Models\UserPhotoDestroy;
use App\Models\UserVipLimit;
use App\Models\UserVipLogModel;
use App\Models\VipConfig;
use App\Models\VipModel;
use App\Services\SmsService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Util\Exception;

class UserController extends Controller
{
    protected $userService;

    public function __construct(){
        $this->userService = new UserService();
    }

    /**
     * 设置密码
     */
    public function setpass(Request $request){
        $validator = Validator::make($request->all(), [
            'password' => 'required|string',
        ],[
            'password.required'=>"密码必须",
        ]);
        if ($validator->fails()) {
            return $this->response()->errorForbidden($validator->messages()->first());
        }
        $user = auth('api')->user();
        $user->password = $request->password;
        if($user->save()){
            return response()->json(['message'=>"设置成功"]);
        }else{
            return $this->response->errorForbidden("设置失败");
        }
    }

    /**
     * 选择性别
     */
    public function checksex(Request $request){
        $user = auth('api')->user();
        $validator = Validator::make($request->all(), [
            'sex' => 'required'
        ], [
            'mobile.required'=>"性别必须",
        ]);
        if ($validator->fails()) {
            return $this->response()->errorForbidden($validator->messages()->first());
        }
        //dd($user);
        $user->sex = $request->sex;
        if (!$user->save()) {
            return $this->response->errorForbidden('设置性别失败');
        }
        return response()->json(['message'=>"设置成功"]);
    }

    /**
     * 设置资料（初次登录）
     */
    public function setinfo(Request $request){
        $user = auth('api')->user();
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->all(), [
                'nickname' => 'required|between:2,10',
                'birthday' => 'required',
                'avatar' => 'required',
            ], [
                'nickname.required'=>"昵称不能为空",
                'nickname.between'=>"昵称长度必须在2~10之间",
                'birthday.required'=>"生日不能为空",
                'avatar.required'=>"头像不能为空",
            ]);
            if ($validator->fails()) {
                throw new Exception($validator->messages()->first());
            }
            if($user->sex==2 && empty($request->video)){
                throw new Exception("请上传视频");
            }

            if(UserInfoModel::query()->leftJoin('users','users_info.user_id','=','users.id')
                ->where(['users_info.nickname'=>$request->nickname,'users.is_distory'=>0])
                ->where('users_info.user_id', '!=' , $user->id)->first()){
                throw new Exception("昵称已被使用");
            }
            //邀请码设置
            $pid = 0;
            if(isset($request->ycode) && $request->ycode!=""){
                if(!$puser = User::where(['ycode'=>$request->ycode])->first()){
                    throw new Exception("邀请码不存在");
                }
                $pid = $puser->id;

                //赠送会员天数
                UserInviteLog::query()->create([
                    'user_id'=>$pid,
                    'invite_id'=>$user->id,
                    'day'=>1,
                    'status'=>0,
                ]);
            }

            UserInfoModel::query()->where('user_id',$user->id)->update([
                'avatar' =>$request->avatar,
                'nickname' =>htmlspecialchars($request->nickname),
                'birthday' =>$request->birthday,
                'video' => !empty($request->video)?json_encode(['url'=>$request->video]) :[],
            ]);
            if($pid!=0){
                $user->pid = $pid;
                $user->save();
            }
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response()->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>"设置成功"]);
    }

    /**
     * 获取个人资料
     */
    public function getinfo(){
        $user = auth('api')->user();
        $userinfo = UserInfoModel::query()->where('user_id', $user->id)->first();

        //dd($userinfo);
        $userinfo['hobby'] = !empty($userinfo['hobby'])?explode(',',$userinfo['hobby']):[];
        $userinfo['photo'] = !empty($userinfo['photo'])?json_decode($userinfo['photo'],true):[];
        $video_info = !empty($userinfo['video'])?json_decode($userinfo['video'],true):[];
        $userinfo['video'] = array_column($video_info,'url');
        $userinfo['like_num'] = $user->like_num;
        $userinfo['like_me_num'] = $user->like_me_num;
        $userinfo['look_num'] = $user->look_num;
        $userinfo['look_num_red'] = UserLookModel::query()->where(['user_id'=>$user->id,'status'=>0])->count();;
        $userinfo['sex'] = $user->sex;
        $userinfo['mobile'] = $user->mobile;
        $userinfo['is_auth'] = $user->is_auth;
        $userinfo['is_vip'] = $user->is_vip;
        $userinfo['ycode'] = $user->ycode;
        $userinfo['notice_status'] = $user->notice_status;
        $userinfo['update_num'] = UserVipLimit::query()->where('user_id',$user->id)->value('user_info');
        $userinfo['see_user_num'] = UserVipLimit::query()->where('user_id',$user->id)->value("user_detail");
        return response()->json($userinfo);
    }

    /**
     * 获取个人资料--兴趣标签
     */
    public function getinfo_tag(){
        $res = SystemConfig::query()->where('id',3)->value("value");
        $res = !empty($res)?explode(',',$res):[];
        return response()->json(['data'=>$res]);
    }


    /**
     * 修改个人资料
     */
    public function updateinfo(Request $request){
        $user = auth('api')->user();


        $validator = Validator::make($request->all(), [
            'nickname' => 'required',
            'birthday' => 'required',
            'avatar' => 'required',
            'height' => 'integer',
            'weight' => 'integer',
        ], [
            'nickname.required'=>"昵称必须",
            'birthday.required'=>"请选择生日",
            'avatar.required'=>"请上传头像",
            'height.integer'=>"身高为整数",
            'weight.integer'=>"体重为整数",
        ]);
        if ($validator->fails()) {
            return $this->response()->errorForbidden($validator->messages()->first());
        }
        $userinfo = UserInfoModel::where('user_id', $user->id)->first();
        if($request->nickname!=$userinfo->nickname){
            if(UserInfoModel::query()->leftJoin('users','users_info.user_id','=','users.id')
                ->where(['users_info.nickname'=>$request->nickname,'users.is_distory'=>0])
                ->where('users_info.user_id', '!=' , $user->id)->first()){
                return $this->response->errorForbidden('昵称已被使用');
            }
        }
//        if(UserVipLimit::query()->where('user_id',$user->id)->value('user_info')==1){
//            return $this->response->errorForbidden("每天只能修改一次");
//        }

//        $upd = array();
//        if(isset($request->nickname)&&!empty($request->nickname)){
//            $upd['nickname'] = $request->nickname;
//        }
//        if(isset($request->nickname)&&!empty($request->nickname)){
//            $upd['nickname'] = $request->nickname;
//        }


        if(UserInfoModel::where('user_id', $user->id)->update($request->input())){
            UserVipLimit::query()->where('user_id',$user->id)->increment('user_info',1);
            return response()->json(['message'=>"修改成功"]);
        }else{
            return $this->response->errorForbidden("修改失败");
        }
    }

    /**
     * 修改个人更多介绍
     */
    public function updateext(Request $request){
        $user = auth('api')->user();
        if(UserInfoModel::where('user_id', $user->id)->update($request->input())){
            return response()->json(['message'=>"修改成功"]);
        }else{
            return $this->response->errorForbidden("修改失败");
        }
    }

    /**
     * 获取照片和视频
     */
    public function get_photo(){
        try {
            $user = auth('api')->user();
            $userinfo = DB::table('users_info')->where(['user_id'=>$user->id])->select('photo','video')->first();
            $userinfo->photo = !empty($userinfo->photo)?json_decode($userinfo->photo,true):[];

            $video_info = !empty($userinfo->video)?json_decode($userinfo->video,true):[];

            $userinfo->video = array_column($video_info,'url');
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($userinfo);
    }

    /**
     * 上传照片或者视频
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
        public function upload_file(Request $request){
        try {
            if($request->post('url')==''){
                throw new Exception("请选择上传内容");
            }
            $user = auth('api')->user();
            $userinfo = UserInfoModel::query()->where('user_id',$user->id)->first();
            if($request->type==1){
                $new_arr = [
                    "url"=>$request->post('url'),
                    "state"=>$request->post('state',0)
                ];
                //图片
                $user_photo = json_decode($userinfo->photo,true);
                $user_photo []= $new_arr;
                $userinfo->photo = json_encode($user_photo);
            }else{
                //视频
                $user_video = json_decode($userinfo->video,true);
                $user_video []= ['url'=>$request->post('url')];
                $userinfo->video = json_encode($user_video);
            }
            $userinfo->save();
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'上传成功']);
    }

    /**
     * 删除图片或者视频
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function del_file(Request $request){
        try {
            $this->userService->del_file($request);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'删除成功']);
    }


    /**
     * 获取VIP
     */
    public function get_vip(){
        try {
            $res['list'] = VipModel::query()->orderBy('id','asc')->get();
            $res['rights'] = json_decode(VipConfig::query()->where(['id'=>2])->value('rights'),true);
            $config = config("filesystems.disks.oss");
            foreach ($res['rights'] as $k=>$v){
                $res['rights'][$k]['img_url'] = "https://".$config['bucket'].'.'.$config['endpoint'].'/'.$v['img_url'];
                $res['rights'][$k]['big_img'] = "https://".$config['bucket'].'.'.$config['endpoint'].'/'.$v['big_img'];
            }
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 获取当前vip信息
     */
    public function get_vip_info(){
        try {
            $user = auth('api')->user();

            $user_info = UserInfoModel::query()->where('user_id',$user->id)->first();
            $res['avatar'] = $user_info->avatar;
            $res['nickname'] = $user_info->nickname;
            $res['is_vip'] = $user->is_vip;

            if($user->is_vip>0){
                $info = UserVipLogModel::query()->where(['user_id'=>$user->id])->first();

                $end_day = floor((strtotime($info['end_day'])-time())/86400);
//                if($end_day<=7){
//                    $res['end_day'] = "您的会员还有".$end_day."天到期，请及时续费";
//                }else{
                    $res['end_day'] = date("Y/m/d",strtotime($info['end_day']));
//                }

            }else{
                $res['end_day'] = "";
            }

        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 购买/续费vip
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function buy_vip(Request $request){
        try {
            $user = auth('api')->user();
            $param['id'] = $request->id;  //vip id
            $param['user_id'] = $user->id;
            $param['payment'] = $request->post('payment',1); //支付方式 1微信  2支付宝
            $res = $this->userService->buy_vip($param);
            //throw new Exception(json_encode($res));
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }


    /**
     * 问题反馈
     * @param Request $request
     * @return \Dingo\Api\Http\Response|void
     */
    public function problem(Request $request){
        try {
            $user = auth('api')->user();
            $param = new ProblemParam();
            $param->user_id = $user->id;
            $param->content = $request->post('content');
            $param->img_url = $request->post('img_url');
            $param->status = 0;
            $this->userService->problem($param);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>"提交成功"]);
    }

    /**
     * 看过我
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function looked_me(Request $request){
        try {
            $res =$this->userService->looked_me();
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 认证中心
     */
    public function auth_center(Request $request){
        try {
            if(empty($request->avatar)){
                throw new Exception("请上传头像");
            }
            if(empty($request->photo)){
                throw new Exception("请上传生活照");
            }
            $user = auth('api')->user();

            $userinfo = UserInfoModel::query()->where('user_id',$user->id)->first();
            //图片
            $user_photo = json_decode($userinfo->photo,true);


            $photo = $request->post('photo');
            if(is_array($photo) && count($photo)>0){
                foreach ($photo as $k=>$v){
                    $new_arr = [
                        "url"   => $v,
                        "state" => 0
                    ];
                    $user_photo []= $new_arr;
                }
            }
            $userinfo->photo = json_encode($user_photo);
            $userinfo->avatar =$request->avatar;
            $userinfo->save();

        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>"提交成功"]);
    }

    /**
     * 人脸对比
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function check_auth(Request $request){
        $apiFace = new \AipFace(env('BAI_DU_YUN_APP_ID'),env('BAI_DU_YUN_API_KEY'),env('BAI_DU_YUN_SECRET_KEY'));
        try {
            $user = auth('api')->user();
            $userinfo = UserInfoModel::query()->where('user_id',$user->id)->first();
            if(empty($request->auth_pic)){
                throw new Exception("参数错误");
            }

            $images = array(
                array(
                    'image' => base64_encode(file_get_contents($userinfo->avatar)),
//                    'image' => base64_encode(file_get_contents("https://zhengda.oss-accelerate.aliyuncs.com/tinymce/images/dcdc14c5987ebbb233a6232264bb80e260f4f496e12ba.jpg")),
                    'image_type' => 'BASE64',
                    'liveness_control'=>'NORMAL',
                ),
                array(
                    'image' => $request->auth_pic,
//                    'image' => base64_encode(file_get_contents($request->auth_pic)),
//                    'image' => base64_encode(file_get_contents("https://zhengda.oss-accelerate.aliyuncs.com/tinymce/images/cea206a2046b895f253445f35794226860f4f4df1d786.jpg")),
                    'image_type' => 'BASE64',
                    //'liveness_control'=>'NORMAL',
                ),
            );
            //throw new Exception(json_encode($images));
            $result = $apiFace->match($images);
//            $result = json_decode($result,true);
            if($result['error_code']==0){
                if($result['result']['score']>80){
                    $user->is_auth = 1;
                    $user->save();
                }else{
                    throw new Exception("人脸检测不通过");
                }
            }else{
                throw new Exception($result['error_msg']);
            }
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>"认证成功"]);
    }

    /**
     * 黑名单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function black_list(Request $request){
        try {
            $res = $this->userService->black_list();
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 移除黑名单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function del_black(Request $request){
        try {
            $this->userService->del_black($request->id);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'操作成功']);
    }

    /**
     * 设置在线状态和通知开关
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function online_status(Request $request){
        try {
            if($request->type=='get'){
                $user = auth('api')->user();
                $res = User::query()->find($user->id,['online','notice_status']);
                $res['notice_status'] = $res['notice_status']==1?0:1;
            }else{
                $res=$this->userService->online_status($request);
            }

        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'操作成功','data'=>$res]);
    }

    /**
     * 获取邀请福利信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function invite_info(Request $request){
        try {
            $res=$this->userService->invite_info($request);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 获取邀请人员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function get_invite_list(){
        try {
            $res=$this->userService->get_invite_list();
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 领取会员天数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function receive_day(){
        DB::beginTransaction();
        try {
            $this->userService->receive_day();
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'操作成功']);
    }

    /**
     * 设置手势锁
     */
    public function lock_pass(){

    }

    /**
     * 注销账户
     */
    public function distory_user(){
        try {
            DB::beginTransaction();
            $this->userService->distory_user();
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response->errorForbidden($exception->getMessage());
        }
        return $this->response->errorUnauthorized("注销成功");
    }


    //分享用户
    public function share(Request $request){
        $user = auth('api')->user();
//        if(isset($request->user_id)){
//
//        }
        $url = "https://".$_SERVER['HTTP_HOST'].'/web/register.html?invoce='.$user->ycode;
        $res['appid'] = env("WEIXIN_OPEN_APPID");
        $res['url'] = $url;

        return response()->json($res);
    }

    /**
     * 忘记密码
     */
    public function reset_password(Request $request){
        $user = auth('api')->user();
        try {
            $validator = Validator::make($request->all(), [
                'verifyKey' => 'bail|required|string',
                'smsCode' => 'bail|required',
                'password' => 'bail|required',
            ],[
                'verifyKey.required'=>"验证码必须",
                'smsCode.required'=>"短信验证码必须",
                'password.required'=>"密码必须",
            ]);
            if ($validator->fails()) {
                throw new Exception($validator->messages()->first());
            }
            //验证短信验证码
            SmsService::checkSmsCodeByVerifyKey($request->verifyKey, $request->smsCode);

            $user->password =$request->password;// Hash::make($request->password);
            if(!$user->save()){
                throw new Exception("设置失败");
            }
            $res = ['message'=>"修改成功"];
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        } catch (SmsException $e) {
            return $this->response->errorForbidden($e->getMessage());
        }
        return response()->json($res);
    }


}
