<?php

namespace App\Http\Controllers\H5;

use App\Events\OrderServeStartedEvent;
use App\Facades\UploadService;
use App\Facades\UserService;
use App\Facades\WechatService;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\Collaborator;
use App\Models\ErrorLog;
use App\Models\FinancialStaff;
use App\Models\InviteUser;
use App\Models\Office;
use App\Models\Order;
use App\Models\Partner;
use App\Models\PartnerCommission;
use App\Models\ServiceUser;
use App\Models\Station;
use App\Models\User;
use App\Models\UserIntroduceLog;
use App\Models\Version;
use App\Models\Wechat;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class AuthController extends Controller
{
    use ResponseJson;
    //

    public function login(Request $request)
    {
        $wechat_user = session('wechat_user');
        $invite_user_id = $request->input('invite_user_id', '');
        $from_user_id = $request->input('from_user_id');
        $openid = $wechat_user['id'] ?? null;

        if (config('app.env') == 'production') {
            //            if (empty($openid)) return $this->jsonResponse(3,"微信授权失败");
            //如果session里面拿不到openid,使用前端传过来的,如果前端也没有,那么返回授权失败
            if (empty($openid)) {
                $openid = $request->input('open_id');
                if (empty($openid))
                    return $this->jsonResponse(3, "微信授权失败");
                $openid = explode("?", $openid)[0];
            }
        } else {
            $openid = 'o1by95wyeY3tBVWbtQSF8yJGCzi8';
        }

        try {
            $this->openidToUser(['openid' => $openid], $invite_user_id, $wechat_user, $from_user_id);
            $user = User::with(['wallets', 'service_roles', 'partner:id,name,pic,user_id,birthday,mobile'])
                ->whereHas('officialWechat', function ($query) use ($openid) {
                    $query->where('openid', $openid);
                })
                //                ->whereHas('service_roles')
                ->firstOrFail();
            $user->openid = $user->officialWechat->openid;
            if (!$user->wallets) {
                $user->wallets()->create([
                    'balance' => 0,
                    'frozen_amount' => 0,
                    'withdrawn_amount' => 0,
                ]);
                $user->load('wallets');
            }

            $user->is_main_coaches = 0;
            $user->is_coaches = 0;
            $user->is_customer_service_user = 0;
            $user->is_partner = 0;
            $user->is_chef_user = 0;
            $user->collaborator = $user->collaborator()->where('status', Collaborator::STATUS_PASS)->first();
            //查询办公室
            if (!empty($user->collaborator)) {
                $station = Station::where('user_id', $user->id)->first();
                if ($station) {
                    $office = Office::where('id', $station->office_id)->first();
                }
                $user->collaborator->office_id = $office->id ?? '';
                $user->collaborator->office_name = $office->office_name ?? '';
            }
            $user->is_collaborator = !empty($user->collaborator) ? 1 : 0;
            //是否申请主持人
            $user->is_moderator = $user->isModerator();
            $user->service_roles()->each(function ($service_role) use ($user) {
                switch ($service_role->pivot->role_id) {
                    case 1://主教练
                        $user->is_main_coaches = 1;
                        break;
                    case 2://副教练
                        $user->is_coaches = 1;
                        break;
                    case 3://客服
                        $user->is_customer_service_user = 1;
                        break;
                    case 4://小伙伴
                        $user->is_partner = 1;
                        break;
                    case 6://餐饮人员
                        $user->is_chef_user = 1;
                        break;
                }
            });
            $user->is_servier = ($user->is_main_coaches || $user->is_coaches || $user->is_customer_service_user || $user->is_chef_user) ? 1 : 0;
            //            $user->token = UserService::apiToken($user);
            $user->token = UserService::apiJwtToken($user);
            //获取邀请二维码
            $user->qrcode = $this->getUserInviteQrcode($user);
            //经销商
            $agent = $user->isAgent();
            $user->is_agent = $agent['is_agent'] ?? 0;
            $user->can_restaurant = $agent['can_restaurant'] ?? 0;
            //没有手机号用户和没有注册批发商的用户需要注册
            //经销商是否需要注册
            $user->agent_register = ($agent['agent_register'] && $user->mobile && $user->name) ? 1 : 0;

            User::where('id', $user->id)->update(['ip' => get_real_ip()]);
            return $this->success('ok', $user);
        } catch (ModelNotFoundException) {
            return $this->jsonResponse(1, '未找到用户信息');
        }
    }

    /**
     * 企业微信登录
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     * @throws Exception
     */
    public function wechatWorkLogin(Request $request)
    {
        try {
            $first = $request->input('first');
            if ($first == 1) {
                return $this->jsonResponse(3, "企业微信授权失败");
            }
            $service_user_id = $request->input('service_user_id');

            if (!empty($service_user_id)) {
                $work_id = ServiceUser::where('user_id', $service_user_id)->value('work_user_id');
                //如果work_id不存在，则获取h5用户open_id
                if (empty($work_id)) {
                    $work_id = Wechat::where('user_id', $service_user_id)->where('type', Wechat::TYPE_OFFICIAL)->value('openid');
                    $user = User::whereHas('officialWechat', function ($query) use ($work_id) {
                        $query->where('openid', $work_id);
                    })
                        ->firstOrFail();
                } else {
                    $this->workIdToUser($work_id);
                    $user = User::whereHas('workWechat', function ($query) use ($work_id) {
                        $query->where('openid', $work_id);
                    })
                        ->firstOrFail();
                }
            } else {
                $work_user = session('work_wechat_user');
                $work_id = $work_user['raw']['userid'] ?? null;

                if (config('app.env') == 'production') {
                    if (empty($work_id)) {
                        $work_id = $request->input('work_id');
                    }
                    if (empty($work_id))
                        return $this->jsonResponse(3, "企业微信授权失败");
                    $work_id = explode("?", $work_id)[0];
                } else {
                    $work_id = 'hankin';
                }

                $this->workIdToUser($work_id);
                $user = User::whereHas('workWechat', function ($query) use ($work_id) {
                    $query->where('openid', $work_id);
                })
                    ->firstOrFail();
            }

            $url = $request->input('url', config('app.url'));
            $work_config = WechatService::workJsSdkConfig($url, 'work');
            $app_config = WechatService::workJsSdkConfig($url, 'app');

            $version = Version::where('type', Version::TYPE_WECOM)->orderBydesc('id')->value('version');

            //如果有服务人员信息,返回信息
            $service_user = ServiceUser::where('user_id', $user->id)->first();
            if (!empty($service_user)) {
                $user->name = $service_user->name;
                $user->mobile = $service_user->mobile;
            }
            $user->work_id = $work_id;
            //            $user->token = UserService::apiToken($user);
            //jwt token
            $user->token = UserService::apiJwtToken($user);

            User::where('id', $user->id)->update(['ip' => get_real_ip()]);
            return $this->success('ok', compact('user', 'work_config', 'app_config', 'version'));
        } catch (\Exception $e) {
            AddErrorLog::dispatch('wechatWorkLogin file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage())->onQueue('health');
            return $this->failure('登录失败');
        }
    }

    public function workIdToUser($work_id)
    {
        DB::beginTransaction();
        try {
            //查看是否存在服务人员及用户信息
            $service_user = ServiceUser::where('work_user_id', $work_id)->first();
            $wechat = Wechat::where('openid', $work_id)->first();
            if ($service_user) {
                if (!$wechat) {
                    Wechat::create([
                        'user_id' => $service_user->user_id,
                        'openid' => $work_id,
                        'unionid' => null,
                        'type' => 'work'
                    ]);
                }
            } else {
                if (!$wechat) {
                    $wechat = Wechat::create([
                        'openid' => $work_id,
                        'unionid' => null,
                        'type' => 'work'
                    ]);
                }
                if (!$wechat->user) {
                    $user = User::create([
                        'name' => null,
                        'avatar' => null,
                        'mobile' => null,
                        'sex' => null,
                        'birthday' => null,
                        'stature' => null,
                        'source' => User::SOURCE_WORK
                    ]);
                    ServiceUser::create([
                        'user_id' => $user->id,
                        'name' => null,
                        'mobile' => null,
                        'work_user_id' => $work_id,
                    ]);
                    $wechat->user_id = $user->id;
                    $wechat->save();
                }
                if ($wechat->user && !$service_user) {
                    ServiceUser::create([
                        'user_id' => $wechat->user->id,
                        'name' => null,
                        'mobile' => null,
                        'work_user_id' => $work_id,
                    ]);
                }
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw new Exception($e);
        }
    }

    /**
     * 获取用户小程序二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getUserInviteQrcode($user)
    {
        try {
            $url = config('app.url') . '/api/h5/wechat/user/auth?target_path=welcome?invite_user_id=' . $user->id;
            $redis = Redis::client();
            //            $invite_qrcode = $redis->get('invite_qrcode_'.$user->id);
            $invite_qrcode = "";
            $pic = '';
            if ($invite_qrcode) {
                $pic = $invite_qrcode;
            } else {
                $path = storage_path('qrcode/' . $user->id . '_invite_qrcode.svg');
                QrCode::generate($url, $path);

                if (file_exists($path)) {
                    $pic = UploadService::uploadFile($path);
                    $redis->set('invite_qrcode_' . $user->id, $pic);
                    @unlink($path);
                }
            }
            return $pic;
        } catch (\Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }
    }

    public function finance(Request $request)
    {
        $wechat_user = session('wechat_user');
        $openid = $wechat_user['id'] ?? null;
        if (empty($openid))
            return $this->jsonResponse(3, "微信授权失败");

        FinancialStaff::where('open_id', $openid)->firstOrCreate([
            'open_id' => $openid
        ]);

        return $this->success("ok");
    }


    public function openidToUser($session, $invite_user_id = '', $wechat_user = [], $from_user_id = '')
    {
        try {
            $inviteModel = new InviteUser();
            $wechat = Wechat::where('openid', $session['openid'])->first();
            DB::beginTransaction();
            if ($wechat) {
                if (isset($session['unionid']) && $wechat->unionid !== $session['unionid']) {
                    $wechat->update(['unionid' => $session['unionid']]);
                }

                if ($wechat->user) {
                    //如果存在邀请人用户id,则做以下操作
                    $inviteModel->insertInviteData($invite_user_id, $wechat->user_id);

                    DB::commit();
                    return $wechat->user;
                }
            } else {
                $wechat = Wechat::create([
                    'openid' => $session['openid'],
                    'unionid' => $session['unionid'] ?? null,
                    'type' => 'official'
                ]);
            }
            if (!$wechat->user) {
                $user = User::create([
                    'name' => $wechat_user['nickname'] ?? null,
                    'avatar' => $wechat_user['avatar'] ?? null,
                    'mobile' => null,
                    'sex' => null,
                    'birthday' => null,
                    'stature' => null,
                    'source' => User::SOURCE_H5
                ]);
                $wechat->user_id = $user->id;
                $wechat->save();
                if (request()->from_user_id) {
                    $user->shareUserLog()->create(['share_user_id' => request()->from_user_id, 'channel' => 'H5']);
                }
            }
            //如果存在邀请人用户id,则做以下操作
            $inviteModel->insertInviteData($invite_user_id, $wechat->user_id);

            DB::commit();
            return $user;
        } catch (Exception $e) {
            DB::rollBack();
            throw new Exception($e);
        }
    }

    public function syncUser()
    {
        try {
            $partners = Partner::has('wechat')->whereNull('user_id')->with('wechat')->get();
            foreach ($partners as $partner) {
                if ($partner->wechat->user_id) {
                    $partner->user_id = $partner->wechat->user_id;
                    $partner->save();
                }
            }
            return $this->success('ok');
        } catch (Exception $e) {
            return $this->jsonResponse(1, $e->getMessage());
        }

    }

    /**
     * 客户端错误上报
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function reportErrorData(Request $request)
    {
        try {
            $data = $request->input('data');
            $message = '客户端错误上报 ' . $data;
            ErrorLog::create(['message' => $message, 'status' => 0]);
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('reportData:' . $e->getMessage());
            return $this->failure('上传失败');
        }
    }

}
