<?php

namespace app\controller;

use app\model\Account;
use app\service\wx\Wechat;
use think\response\Redirect;

class Login extends Base
{
    protected $noNeedLogin = ['index', 'temp'];

    public function index(): Redirect
    {
        if (env('app_dev', false)) {
            $this->temp();
            exit;
        }
        $code   = input('code/s', '');
        $wechat = Wechat::getInstance();
        if (empty($code)) {
            $redirectUrl = $wechat->oauth->scopes(['snsapi_userinfo'])->redirect(request()->domain().'/login/index');
            header('Location:'.$redirectUrl);
            exit;
        }

        $user = $wechat->oauth->userFromCode($code);

        if ($userInfo = $user->getRaw()) {
            unset($userInfo['privilege']);
            $field = 'id,openid,nickname,sex,headimgurl,unionid,business_id,phone_active,mobile';
            if (!$account = Account::field($field)->where('openid', $userInfo['openid'])->find()) {
                $userInfo['created_at'] = date('Y-m-d H:i:s');
                $create                 = Account::create($userInfo);
                $account                = [
                    'id'           => $create['id'],
                    'openid'       => $create['openid'],
                    'nickname'     => $create['nickname'],
                    'sex'          => $create['sex'],
                    'headimgurl'   => $create['headimgurl'],
                    'unionid'      => $create['unionid'],
                    'business_id'  => $create['business_id'],
                    'phone_active' => $create['phone_active'],
                ];
            }

            session('frontend_auth', $account);
        }
        return $this->redirect('/login/bind');
    }

    /**
     * 本地登录 模拟微信code
     *
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function temp(): Redirect
    {
        $openid = 'o3LH9jktzObHsQOK-Uu83D4tr_Tg';//拙言号

        $field   = ['id', 'openid', 'nickname', 'sex', 'headimgurl', 'unionid', 'business_id', 'phone_active', 'mobile'];
        $account = Account::field($field)->where('openid', $openid)->find();
        if (!$account) {
            $account = Account::findById(1, $field);
        }

        session('frontend_auth', $account->toArray());

        return $this->redirect('/coupon/game');
    }

    /**
     * 绑定手机
     *
     * @return \think\response\Redirect|\think\response\View|\think\response\Json
     */
    public function bind()
    {
        if ($this->auth && $this->auth['phone_active'] > 0) {
            if ($this->auth['business_id']) {
                // 是商户负责人时 再次检验身份 避免用户身份变更但缓存未更新
//                $businessId = Account::where('id', $this->authId)->value('business_id');
//                if ($businessId > 0) {
//                    if ($businessId != $this->authId) {
//                        $this->auth['business_id'] = $businessId;
//                        session('frontend_auth', $this->auth);
//                    }
//                }
                return $this->redirect('/business/my');
            }
            return $this->redirect('/coupon/index');
        }

        if ($this->request->isPost()) {
            $phone = input('phone/s', '');

            if (!checkMobile($phone)) {
                return $this->json(4000, '请填写正确的手机号');
            }

            $this->auth['mobile']       = $phone;
            $this->auth['phone_active'] = 1;
            session('frontend_auth', $this->auth);

            Account::where('id', $this->authId)->save(['phone_active' => 1, 'mobile' => $phone]);

            $url = $this->auth['business_id'] ? '/business/my' : '/coupon/index';
            return $this->json(0, 'success', ['url' => $url]);
        }

        return $this->view();
    }
}
