<?php

namespace App\Http\Controllers;

use App\Facades\ChatService;
use App\Facades\CommonService;
use App\Facades\UserService;
use App\Facades\WechatService;
use App\Http\Response\ResponseJson;
use App\Jobs\SyncSaasUser;
use App\Models\InviteUser;
use App\Models\TaskCategory;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Version;
use App\Models\Wechat;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoginController extends Controller
{
    use ResponseJson;
    /**
     * 小程序code 换取 openid
     * openid 获取登录信息
     */
    public function codeLogin(Request $request)
    {
        //wx.login 获取 code
        $code = $request->input('code');
        if (empty($code)) throw new \Exception("缺少参数code");
        $version = $request->input('version');
        //code to wx info
        $session = WechatService::codeToSession($code);
//        if (config('app.env') == "local") {
//            $session = [
//                'openid'=>'oVEaG5HV2UCpfPyVajZWClV6JiyQ',
//                'unionid'=>'oVMWos5gXJDG_XZJiHjkGpNui40Y',
//                'session_key'=>'qyXFsz8XBGNkOyAMftq2Sg==',
//            ];
//        }

        if (empty($session)) return $this->failure();
        //获取用户信息
        $user = $this->openidToUser($session);
        if (empty($user)) return $this->failure();
        $this->userToInfo($user);
        //登录token
//        $user = $this->userToken($user);
        $user->token = UserService::apiJwtToken($user);
        $user->makeVisible('api_token');
        $user->makeVisible('mobile');
        $user->wechat;
        //同步saas账号
//        SyncSaasUser::dispatch($user)->onQueue('health');
        //是否完善基本资料
        $user->is_complete_profile = $user->baseUserInfo();
        //绑定websocket
        $client_id = $request->input('client');
        if ($client_id) {
            ChatService::bindUid($client_id, $user->id);
            ChatService::sendNoticeNum($user);
        }
        $status = "NOORDER";
        $order = $user->payOrders()->whereIn('status', ['NOTSTART', 'STARTING','FINISHED'])->orderByDesc('id')->first();
        if ($order) {
            $status = $order->status;
        }
        $user->order_status = $status;
        $user->service_status = $order->service_status??'NOINFO';
        //是否是服务人员
        $user->is_servicer = $user->serviceUser?1:0;
        //测试
        if($user->id == 336){
            $user->is_servicer = 1;
        }
        $user->user_id = $user->id;
        $user->id = make_user_id($user->id);
        //加个判断,手机号设置了唯一,空字符串也不能存,只能是null,为了兼容客户端,处理成空字符串
        if(empty($user->mobile)){
            $user->mobile = "";
        }
        //判断用户信息
        $user->unit = get_user_unit($user->language,$user->unit);
        //查找版本号状态
        $user->version_status = Version::where('version',$version)->value('status');
        return $this->success('ok', $user);

    }

    public function userToInfo($user)
    {
        if (empty($user->userInfo)) {
            UserInfo::create([
                'user_id'=>$user->id,
            ]);
        }
        User::where('id',$user->id)->update(['ip'=>get_real_ip()]);
    }

    /**
     * 获取用户token
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getUserToken(Request $request){
        $id = $request->input('id');
        $secret = $request->input('secret');
        if($secret != 'krT$zQl$5LR6sZbExnhUoY%y'){
            return $this->failure('请求失败');
        }
        $user = User::where('id',$id)->first();
        $api_token = UserService::apiJwtToken($user);
//        $carbon_expire_at = Carbon::now()->addDays(30);
//        $expire_at = $carbon_expire_at->toDateTimeString();
//        $api_token = $user->createToken($user->id, ['*'], $carbon_expire_at)->plainTextToken;
//        User::where('id',$user->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
//        $user->api_token = $api_token;
        return $this->success('ok',$api_token);
    }

    public function userToken($user)
    {
        if (!$user->expire_at || $user->expire_at < date('Y-m-d H:i:s')){
            $carbon_expire_at = Carbon::now()->addDays(30);
            $expire_at = $carbon_expire_at->toDateTimeString();
            $api_token = $user->createToken($user->id, ['*'], $carbon_expire_at)->plainTextToken;
            User::where('id',$user->id)->update(['api_token'=>$api_token, 'expire_at'=>$expire_at]);
            $user->api_token = $api_token;
        }
        return $user;
    }


    public function openidToUser($session)
    {
        try {
            $param = ['openid'=>$session['openid'], 'unionid'=>$session['unionid']??null];
            $wechat = Wechat::where('openid', $session['openid'])->first();
            if ($wechat) {
                if (isset($session['unionid'])){
                    Wechat::where('id', $wechat->id)->update(['unionid'=>$session['unionid']]);
                }
                if ($wechat->user) return $wechat->user;
            }else {
                DB::beginTransaction();
                $wechat = Wechat::create($param);
            }
            $user = User::create(['name'=>null, 'avatar'=>null, 'mobile'=>null,'sex'=>null, 'birthday'=>null, 'stature'=>null, 'unit'=>'斤','source'=>User::SOURCE_MP]);
            $wechat->user_id = $user->id;
            $wechat->save();
            if (request()->from_user_id){
                $user->shareUserLog()->create(['share_user_id'=>request()->from_user_id, 'channel'=>'MP']);
            }
            DB::commit();
            return $user;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e);
        }
    }
}
