<?php


namespace App\Http\Controllers\Api;


use App\Enums\ApiEnum;
use App\Exceptions\AuthException;
use App\Exceptions\VipException;
use App\Http\Params\UserCommentParam;
use App\Http\Params\UserLikeParam;
use App\Models\SystemConfig;
use App\Models\UserPhotoDestroy;
use App\Services\DynamicService;
use App\Services\HomeService;
use App\Services\RedisService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use PHPUnit\Util\Exception;

class HomeController extends Controller
{
    public $homeService;
    public function __construct()
    {
        $this->homeService = new HomeService();
    }

    /**
     * 获取位置信息,经纬度
     */
    public function get_location(Request $request){
        try {
            if(!isset($request->latitude) || $request->latitude==""){
                throw new Exception("参数错误");
            }
            if(!isset($request->longitude) || $request->longitude==""){
                throw new Exception("参数错误");
            }
//            if(!isset($request->uniqueID) || $request->uniqueID==""){
//                throw new Exception("参数错误");
//            }
            $user = auth('api')->user();
            if(!$user){
                RedisService::redis()->SETEX('user_location_' . $request->uniqueID, 600, json_encode(['latitude' => $request->latitude, 'longitude' => $request->longitude]));
            }else{
                $user->latitude = $request->latitude;
                $user->longitude = $request->longitude;
                $user->save();
            }
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>"请求成功"]);
    }

    public function get_fx(){
        $res = SystemConfig::query()->where('id',2)->value("value");
        $set = SystemConfig::query()->where('id',4)->value("value");

        $user = auth('api')->user();
        if($user){
            $user_info['sex'] = $user->sex;
            $user_info['password'] = $user->password;
        }else{
            $user_info = [];
        }

        return response()->json(['data'=>$res,'setting'=>$set,'user_info'=>$user_info]);
    }

    /**
     * 返回首页信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function home(Request $request){
        try {
            $param['keyword'] = $request->post('keyword','');//关键词，昵称，标签
            $param['nearby'] = $request->post('nearby',1);//附近
            $param['online'] = $request->post('online',1);//在线
            $param['new'] = $request->post('new',1);//新人
            $param['latitude'] = $request->post('latitude');//纬度
            $param['longitude'] = $request->post('longitude');//经度

            $user = auth('api')->user();
            if($user){
                $user->latitude = $request->latitude;
                $user->longitude = $request->longitude;
                $user->save();
            }else{
                RedisService::redis()->SETEX('user_location_' . $request->uniqueID, 600, json_encode(['latitude' => $request->latitude, 'longitude' => $request->longitude]));
            }
            $res = $this->homeService->get_list($param);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }


    /**
     * 用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function user_detail(Request $request){
        try {
            $param['user_id'] = $request->user_id;
            $param['tencent_im_user_id'] = $request->tencent_im_user_id;
            $res = $this->homeService->user_detail($param);
        }catch (VipException $exception){
            return response()->json(['message'=>$exception->getMessage()])->setStatusCode(410);
        }catch (AuthException $exception){
            return $this->response->errorUnauthorized($exception->getMessage());
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 用户动态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function user_dynamic(Request $request){
        try {
            $where = array();
            $where['type'] = $request->post('type',1); //类型  type 1全部  2关注  3附近
            $where['look_type'] =$request->post('look_type',3);//查看类型  type 1只看男士  2只看女士  3全部
            $where['tag_id'] =$request->post('tag_id',0); //话题标签
            $where['user_id'] =$request->user_id;
            $dynamicService = new DynamicService();
            $res = $dynamicService->dynamic_list($where);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }

    /**
     * 用户喜欢
     */
    public function do_like(Request $request){
        DB::beginTransaction();
        try {
            $user = auth('api')->user();
            $UserLikeParam = new UserLikeParam();
            $UserLikeParam->user_id = $user->id;
            $UserLikeParam->like_id = $request->user_id;
            $is_like = $this->homeService->do_like($UserLikeParam);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>$is_like==1?"已喜欢":"取消喜欢",'is_like'=>$is_like]);
    }

    /**
     * 用户评价
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function do_comment(Request $request){
        try {
            $user = auth('api')->user();
            $UserComment = new UserCommentParam();
            $UserComment->user_id = $user->id;
            $UserComment->comment_id = $request->user_id;
            $UserComment->con1 = $request->con1;
            $UserComment->con2 = $request->con2;
            $UserComment->con3 = $request->con3;
            $UserComment->con4 = $request->con4;
            $is_like = $this->homeService->do_comment($UserComment);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'评价成功']);
    }

    /**
     * 解锁微信
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function get_weixin(Request $request){
        try {
            $res = $this->homeService->get_weixin($request->user_id);
        }catch (VipException $exception){
            return response()->json(['message'=>$exception->getMessage()])->setStatusCode(410);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['weixin'=>$res]);
    }

    /**
     * 阅后即焚
     */
    public function photo_destroy(Request $request){
        try {
            if(empty($request->url)){
                throw new Exception("参数错误");
            }
            $user = auth('api')->user();
            $cache_eq_id = $request->header('uniqueID','');//获取设备码
            $lock = Cache::lock(ApiEnum::PHOTO_DESTROY_LOCK.$cache_eq_id, 1);

            if ($lock->get()) {
                if(!$user){
                    if(!Redis::get(ApiEnum::PHOTO_DESTROY_URL.$cache_eq_id.md5($request->url))){
                        Redis::setex(ApiEnum::PHOTO_DESTROY_URL.$cache_eq_id.md5($request->url),86400*365,$request->url);
                    }
                }else{
                    if(!UserPhotoDestroy::query()->where(['user_id'=>$user->id,'url'=>$request->url])->first()){
                        UserPhotoDestroy::query()->create(['user_id'=>$user->id,'url'=>$request->url,'atime'=>date("Y-m-d H:i:s")]);
                    }
                }
                $lock->release();
            }else{
                throw new Exception("请求太频繁");
            }
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'已销毁']);
    }

    //拉黑用户
    public function lahei(Request $request){
        try {
            $param['user_id'] = $request->user_id;
            $param['tencent_im_user_id'] = $request->tencent_im_user_id;
            $this->homeService->lahei($param);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json(['message'=>'已拉黑']);
    }

    /**
     * 用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function user_detail_h5(Request $request){
        try {
            $param['user_id'] = $request->user_id;
            $res = $this->homeService->user_detail_h5($param);
        }catch (\Exception $exception){
            return $this->response->errorForbidden($exception->getMessage());
        }
        return response()->json($res);
    }


}
