<?php
namespace app\h5\controller;

use app\hander\HelpHander;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;
use think\Exception;

class WxHome extends Controller
{

    public function index(){
        $code = input('code','');
        if(!$code){
            $code = decodecookie('sn');
        }
        if(!$code){
            return $this->fetch('h5/msg_error',['msg'=>'请扫码二维码']);
        }
        $data = get_qrcode_arr($code);
        if(!$data || $data['ucode'] != config('app.ucode') || $data['type'] != 'dinner_address'){
            return $this->fetch('h5/msg_error',['msg'=>'二维码错误']);
        }

//        session('sn',$code);
        encodecookie('sn',$code,100*365*24*60*60);
        $info = Db::name('dinner_address')->where('id',$data['id'])->where('del',0)->where('enable',1)->find();
        if(!$info || !$info['org_id']){
            return $this->fetch('h5/msg_error',['msg'=>'二维码错误']);
        }
        $HospitalId = $info['org_id'];
//        session('HospitalId',$HospitalId);
        encodecookie('HospitalId',$HospitalId,100*365*24*60*60);

//        $user = Db::name('wxuser')->where('id',206)->find();
//        $user['HospitalName'] = "北京国天健宇物业管理发展有限公司";
//        session('userinfo',$user);
        $userId = dinner_is_login();
//        $userId = 205;
        if(!$userId){
            $this->redirect(url('WxHome/login'));
        }
        $user = Db::name('wxuser')->where('id',$userId)->find();
        if (empty($user)||empty($user['id'])) {
           $this->redirect(url('WxHome/login'));
        }

        if($user['curr_org_id'] != $HospitalId){
            Db::name('wxuser')->where('id',$user['id'])->update(['curr_org_id'=>$HospitalId]);
        }

        $org = Db::name('org')->where('id',$HospitalId)->where('del',0)->where('enable',1)->find();
        if(!$org){
            return $this->fetch('h5/msg_error',['msg'=>'二维码错误或已失效']);
        }
        $this->redirect(url('WxBookDinner/index'));

    }



    public function login() {
        $sn = decodecookie('sn');
        $orgId = decodecookie('HospitalId');
        if(!$sn||!$orgId){
            return $this->fetch('h5/msg_error',['msg'=>'请扫码二维码']);
        }

        session('user_auth',null);
        session('user_auth_sign',null);

        $currUrl = url("oauth",[],false,true).'?w='.$sn;
        $config = get_pay_wechat($orgId);
        $app = \EasyWeChat\Factory::officialAccount($config);
        $response = $app->oauth->scopes(['snsapi_userinfo'])->redirect($currUrl);
        $response->send();
        exit();
    }

    public function oauth() {
        $parameter = input('w');
        $data = get_qrcode_arr($parameter);
        if(!$data || $data['ucode'] != config('app.ucode') || $data['type'] != 'dinner_address'){
            return $this->fetch('h5/msg_error',['msg'=>'二维码错误']);
        }
        $info = Db::name('dinner_address')->where('id',$data['id'])->where('del',0)->where('enable',1)->find();
        if(!$info || !$info['org_id']){
            return $this->fetch('h5/msg_error',['msg'=>'二维码错误']);
        }

        $orgId = $info['org_id'];
        try {
            $config =get_pay_wechat($orgId);
            $userType = $config['user_type'];
            $app = \EasyWeChat\Factory::officialAccount($config);
            $user = $app->oauth->user();
            $openid = $user->id;
            $_data['curr_org_id'] = $orgId;
            $_data['img'] = $user->avatar;
            $_data['nickname'] = $user->nickname;
            $userId = 0;
            //查找数据库
            $user = Db::name('wxuser')
                ->where('openid', $openid)
                ->where('type', $userType)
                ->where('del',0)
                ->find();
            //不存在此用户
            if (empty($user)) {
                $_data['create_time'] = date('Y-m-d H:i:s');
                $_data['enable'] = 1;
                $_data['type'] = $userType;
                $_data['openid'] = $openid;
                $userId = Db::name('wxuser')->insertGetId($_data);
                if(!$userId){
                    \exception('登录失败');
                }
            }
            else { //存在此用户则更新信息
                $userId = $user['id'];
                if (trim($_data['img']) == trim($user['img'])) {
                    unset($_data['img']);
                }
                if (trim($_data['nickname']) == trim($user['nickname'])) {
                    unset($_data['nickname']);
                }
                if (!empty($_data)) {
                    Db::name('wxuser')->where('id', $user['id'])->update($_data);
                }
            }

            //查找用户信息
            $user = Db::name('wxuser')
                ->where('id', $userId)
                ->where('del',0)
                ->find();
            if (empty($user)) {
                return $this->fetch('h5/msg_error', ['msg' => '不存在此用户']);
            }

            /* 记录登录SESSION和COOKIES */
            $auth = array(
                'id'                => $user['id'],
                'nickname'           => $user['nickname'],
            );
            session('user_auth',$auth);
            session('user_auth_sign',data_auth_sign($auth));
            Db::name('dinner_cart')->where('user_id', $user['id'])->delete();
            $this->redirect(url('WxHome/index').'?code='.$parameter);
        } catch (Exception $e) {
            return $this->fetch('h5/msg_error', ['msg' => '登录失败' . $e->getMessage()]);
        }
    }


}