<?php
use Business\User\LoginV2Model;
use Error\ErrorModel;
use Error\CodeConfigModel;
use Our\NameConst;
use Our\Common;
use Business\User\MemberServiceModel;
class UserController extends \Our\Controller_AbstractIndex {
    public $memberService;

    public function init(){
        parent::init();
        $this->memberService=MemberServiceModel::getInstance();

    }

    private function indexAction() {
        $login=LoginV2Model::getInstance();
        echo $login->login();
    }

    /**
     * 用户登录
     *
     * @ccw
     */
    public function loginAction(){
        if(parent::isLogin()){
           ErrorModel::throwException(CodeConfigModel::isLogin);
        }else{
            $data=$this->req['data'];
            $sellerName=$data['sellerName'];
            $password=$data[NameConst::password];
            $shopKeeperServvice=\Business\Store\ShopkeeperServiceModel::getInstance();
            $seller=$shopKeeperServvice->sellerLogin($sellerName);
            if(!empty($seller)){
                $mobile=$seller['memberMobile'];
            }else{
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::errorUsernameOrPassword);
            }
            if($this->memberService->checkUserNamePassWord($mobile,$password)){
                $member= $this->memberService->getOneByMobileAndPassword($mobile,$password);
//                //第二步保存扫码会员信息
//                $result = $this->memberService->saveStoreMembers($member['member_id']);
//                if(!$result){
//                    \Error\ErrorModel::throwException(\Error\CodeConfigModel::saveStoreMemberFailed);
//                }
//                /**
//                 * 合并第三方授权信息
//                 */
//                if($member){
//                    $result = $this->memberService->saveLoginMapping($member,$data);
//                    if(!$result['status']){
//                        \Error\ErrorModel::throwException(\Error\CodeConfigModel::loginBindUserInfoFailed);
//                    }
//                        if(isset($result['member'])&&$member){
//                        $member = array_merge($member,$result['member']);
//                    }
//                }
              //  $userToken=$this->memberService->findMbUserTokenByMemberId($shopKeeperServvice['token']);
                if($member){
                    //$this->memberService->clearKey($this->key);
                    $this->key=Common::bulidToken($mobile,$password);
                    session_id($this->key);
                    $this->sess['member_id']=(int)$member['member_id'];
                    $this->sess['store_id']=(int)$seller['storeId'];
                    $this->sess['seller_name']=$seller['sellerName'];
                    $this->sess['seller_id']=$seller['sellerId'];
                    $this->sess[NameConst::sessionKey]=$this->key;
                    $member[NameConst::sessionKey]=$this->key;
                    $member['store_id']=$seller['storeId'];
                    $member['seller_id']=$seller['sellerId'];
                    $member['seller_name']=$seller['sellerName'];
                    //通知退出
                    $push=\Our\Push::getInstance();
                    $push->addOneToClient(array('storeId'=>$member['store_id'],'type'=>\Our\ApiConst::messageOtherLogin,'op'=>NameConst::logOut,'num'=>0,'params'=>array('c'=>'member','m'=>'logOut')));
                    $push->sendTcpMessage();
                    $this->memberService->saveMember($member,'seller');
                    $this->success(array('key'=>$this->key,'memberName'=>$member['member_name'],'memberMobile'=>$member['member_mobile'],'memberAvatar'=>$member['memberAvatarUrl'],'memberId'=>(int)$member['member_id'],'storeId'=>(int)$seller['storeId']));
                }else{
                    ErrorModel::throwException(CodeConfigModel::errorUsernameOrPassword);
                }
            }
        }
        ErrorModel::throwException(CodeConfigModel::noLogin);

    }

    
    public function loginWithWechatInfoAction(){
        if(parent::isLogin()){
            ErrorModel::throwException(CodeConfigModel::isLogin);
        }else {
            $data = $this->req['data'];
            $authInfo = $this->sess->get('wxAuthInfo');
            $data['deviceType'] = \Our\ApiConst::wechatDeviceType;
            $data['userType'] = \Our\ApiConst::wechatUserType;
            $member= $this->memberService->loginWithWechatInfo($data,$authInfo);
            if($member){
                /*$userToken=$this->memberService->findMbUserTokenByMemberId($member['member_id']);
                $this->memberService->clearKey($userToken['token']);*/
                $userToken=$this->memberService->getWxUserToken($member['member_id']);
                if(!empty($userToken)){
                    $this->updateOldLoginKey($userToken);
                }
                $this->memberService->clearKey($this->key);
                $this->key=Common::bulidToken('', '', '', \Our\ApiConst::wechatDeviceType);
                $this->memberService->saveWxUserToken($this->key,$member['member_id']);
                session_id($this->key);
                $this->sess['member_id'] = $member['member_id'];
                $this->sess['user_type'] = \Our\ApiConst::wechatUserType;
                $this->sess[NameConst::sessionKey]=$this->key;
                $member[NameConst::sessionKey]=$this->key;
                //$this->memberService->saveMember($member);
                $this->success(array('key'=>$this->key,'memberName'=>$member['member_name'],'memberAvatar'=>$member['memberAvatarUrl']));
            }

            ErrorModel::throwException(CodeConfigModel::wxAuthInfoLoginFailed);
        }
    }


    /**
     * 用户信息注册
     */
    public function registerAction(){
        $where = $this->req['data'];
        $member = $this->memberService->saveRegisterInfo($where);
        if($member){
            $userToken=$this->memberService->findMbUserTokenByMemberId($member['member_id']);
            $this->memberService->clearKey($userToken['token']);
            $this->memberService->clearKey($this->key);
            $this->key=Common::bulidToken('', '', '', \Our\ApiConst::wechatDeviceType);
            session_id($this->key);
            $this->sess['member_id']=$member['member_id'];
            $this->sess[NameConst::sessionKey]=$this->key;
            $member[NameConst::sessionKey]=$this->key;
            $this->memberService->saveMember($member);
            $this->success(array('key'=>$this->key,'memberName'=>$member['member_name'],'memberAvatar'=>$member['memberAvatarUrl'],'memberId'=>$member['member_id']));
        }
        ErrorModel::throwException(CodeConfigModel::registerMemberFailed);
    }


    public function loginWithThirdPlatformInfoAction(){
        $where = $this->req['data'];
        $member = $this->memberService->loginWithThirdPlatformInfo($where);
        if($member){
            $userToken=$this->memberService->findMbUserTokenByMemberId($member['member_id']);
            if(!empty($userToken['token'])){
                $this->updateOldLoginKey($userToken['token']);
            }
            //第二步保存扫码会员信息
            $result = $this->memberService->saveStoreMembers($member['member_id']);
            if(!$result){
                \Error\ErrorModel::throwException(\Error\CodeConfigModel::saveStoreMemberFailed);
            }
            $this->memberService->clearKey($this->key);
            $this->key=Common::bulidToken('', '', '', \Our\ApiConst::wechatDeviceType);
            session_id($this->key);
            $this->sess['member_id']=$member['member_id'];
            $this->sess['user_type'] = $where['userType'];
            $this->sess[NameConst::sessionKey]=$this->key;
            $member[NameConst::sessionKey]=$this->key;
            $member['login_time']=TIMESTAMP;
            $this->memberService->saveMember($member);
            $this->success(array('userFlag'=>\Our\ApiConst::one,'key'=>$this->key,'memberName'=>$member['member_name'],'memberAvatar'=>$member['memberAvatarUrl'],'memberId'=>(int)$member['member_id']));
        }else{
            $this->success(array('userFlag'=>\Our\ApiConst::zero));
        }
    }

    public function isLoginAction(){
        $isLogin = \Our\ApiConst::zero;
        if(parent::isLogin()){
            $isLogin = \Our\ApiConst::one;
        }
        $this->success(array('isLogin'=>$isLogin));
    }
}
