<?php

namespace App\Http\Controllers\H5;

use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LoginController;
use App\Http\Response\ResponseJson;
use App\Models\Coach;
use App\Models\Partner;
use App\Models\User;
use EasyWeChat\Kernel\Exceptions\Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

class PartnerController extends Controller
{
    use ResponseJson;

    public function partner(Request $request)
    {
        $wechat_user = session('wechat_user');
        $openid = $wechat_user['id']??null;
//        if (config('app.env') == 'production') {
            $auth_url = route('partner.official.auth');
            if (empty($openid)) return $this->success("微信授权失败", ['has_auth'=>false, 'auth_url'=>$auth_url]);
//        }else {
//            $openid = 'ojvHq5kvZai3mvwc18wx066uUjqk';
//        }

        //根据openid获取用户
        $user = app('App\Http\Controllers\H5\AuthController')->openidToUser(['openid'=>$openid]);

        $partner = Partner::where('openid', $openid)
            ->select(['openid', 'user_id', 'name','mobile','pic','intro','specialty','attach','status'])
            ->first();
        if (empty($partner)) {
            $partner = new Partner([
                'openid'=>$openid,
                'name'=>null,
                'mobile'=>null,
                'pic'=>null,
                'intro'=>null,
                'specialty'=>null,
                'attach'=>null,
                'status' => 3,
                'user_id'=>$user->id
            ]);
        }
        $partner->has_auth = true;
        return $this->success("ok", $partner);
    }

    /**
     * 合作伙伴申请
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function storePartner(Request $request)
    {
        try {
            $wechat_user = session('wechat_user');
            $openid = $wechat_user['id']??null;
//        if (config('app.env') == 'production') {
            if (empty($openid)) return $this->failure("微信授权失败");
//        }else {
//            $openid = 'ojvHq5kvZai3mvwc18wx066uUjqk';
//        }
            $pic = $request->input('pic');
            if (empty($pic)) return $this->failure("请输入头像");
            $name = $request->input('name');
            if (empty($name)) return $this->failure("请输入姓名");
            $mobile = $request->input("mobile");
            if (empty($mobile)) return $this->failure("请输入手机号");
            $intro = $request->input('intro');
//        if (empty($intro)) return $this->failure("请输入个人简介");
            $specialty = $request->input('specialty',[]);
            $attach = $request->input('attach');
//        $exist = Partner::where('mobile', $mobile)->exists();
//        if ($exist) return $this->failure("手机号已存在");

            $data = [
                'name'=>$name,
                'mobile'=>$mobile,
                'pic'=>$pic,
                'intro'=>$intro,
                'specialty'=>json_encode($specialty),
                'attach'=>$attach
            ];

            //获取用户角色
            $user = $this->checkUserRoles($openid);

            if (!$user->is_partner){
                $data['status'] = 0;
                //根据openid获取用户
                $user = app('App\Http\Controllers\H5\AuthController')->openidToUser(['openid'=>$openid]);
                $data['user_id'] = $user->id;
            }

            Partner::updateOrCreate(['openid'=>$openid],$data);
            return $this->success('ok');
        }catch (ModelNotFoundException ){
            return $this->jsonResponse(1,'未找到用户信息');
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    public function coach(Request $request)
    {
        try {
            $wechat_user = session('wechat_user');
            $openid = $wechat_user['id']??null;
//        if (config('app.env') == 'production') {
            $auth_url = route('coach.official.auth');
            if (empty($openid)) return $this->success("微信授权失败", ['has_auth'=>false, 'auth_url'=>$auth_url]);
//        }else {
//            $openid = 'ojvHq5kvZai3mvwc18wx066uUjqk';
//        }
            //获取用户角色
            $user = $this->checkUserRoles($openid);

            if ($user->is_coaches == 0 && $user->is_partner == 0){
                throw new \Exception('请先申请合作伙伴');
            }

            $coach = $user->coach;

            if (!$coach) {
                $coach = new  Coach([
                    'partner_id'=>$user->partner->id,
                    'openid'=>$openid,
                    'outlook'=>null,
                    'reason'=>null,
                    'think'=>null,
                    'status'=>$user->is_coaches?1:3
                ]);
            }
            $coach->has_auth = true;
            $coach->has_partner = true;
            return $this->success('ok', $coach);
        }catch (ModelNotFoundException ){
            return $this->jsonResponse(1,'未找到用户信息');
        }catch (\Exception $e){
            return $this->jsonResponse(1,$e->getMessage());
        }
    }

    public function storeCoach(Request $request)
    {
        $wechat_user = session('wechat_user');
        $openid = $wechat_user['id']??null;
//        if (config('app.env') == 'production') {
            if (empty($openid)) return $this->success("微信授权失败", ['has_auth'=>false]);
//        }else {
//            $openid = 'ojvHq5kvZai3mvwc18wx066uUjqk';
//        }
        $outlook = $request->input('outlook');
        if (empty($outlook)) return $this->failure("请输入你对副教练这个角色有什么看法");
        $reason = $request->input('reason');
        if (empty($reason)) return $this->failure("请输入申请副教练的原因");
        $think = $request->input("think");
        if (empty($think)) return $this->failure("请输入你认为副教练需要做什么工作");

//        $partner = Partner::where('openid', $openid)->where('status',1)->first();
        try {
            //获取用户角色
            $user = $this->checkUserRoles($openid);

            Coach::updateOrCreate(
                ['openid'=>$openid],
                [
                'partner_id'=>$user->partner->id,
                'outlook'=>$outlook,
                'reason'=>$reason,
                'think'=>$think,
                'status'=>$user->is_coaches
            ]);

            return $this->success('ok');

        }catch (ModelNotFoundException ){
            return $this->jsonResponse(3,'未找到用户信息');
        }catch (Exception $e){
            return $this->jsonResponse(2,$e->getMessage());
        }


    }

    private function checkUserRoles($openid)
    {
        //获取用户角色
        $user = User::with(['service_roles','partner','coach'])
            ->whereHas('officialWechat', function ($query) use ($openid) {
                $query->where('openid', $openid);
            })
            ->firstOrFail();

        $user->is_partner = 0;
        $user->is_coaches = 0;

        $user->service_roles()->each(function ($service_role) use ($user) {
            switch ($service_role->pivot->role_id){
                case 1://主教练
                    break;
                case 2://副教练
                    $user->is_coaches = 1;
                    break;
                case 3://客服
                    break;
                case 4://小伙伴
                    $user->is_partner = 1;
                    break;
            }
        });

        return $user;
    }
}
