<?php
/**
 * 前台注册登录模型
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/11/20
 * Time: 9:12
 */

namespace JinDouYun\Model\UserCenter;

use Exception;
use JinDouYun\Dao\Enterprise\DEnterprise;
use JinDouYun\Dao\Shop\DShop;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\System\MCustomerSource;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Dao\Enterprise\DUserBindEnterprise;
use JinDouYun\Dao\Customer\DCustomer;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\UserCenter\MUserCenterRegister;
use JinDouYun\Model\System\MBasicSetup;

use Mall\Framework\Core\Jwt;
use Util\Common\ChineseCharacter;

class MApiUserCenter extends MBaseModel
{
    private $objDUserCenter;
    private $objDCustomer;
    private $objMCustomer;
    private $objMUserCenterRegister;
    private $objDUserBindEnterprise;
    private $enterpriseId;//企业id
    private $userCenterId;

    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objDUserCenter = new DUserCenter('default');
        $this->objDCustomer = new DCustomer('default');
        $this->objMCustomer = new MCustomer($enterpriseId, $this->userCenterId);
        $this->objMUserCenterRegister = new MUserCenterRegister();
        $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
    }

    /**
     * 前台注册  userCenter添加，需要与customer关联，与企业关联
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function register($params)
    {
        $this->objDUserCenter->beginTransaction();
        $unionId = isset($params['unionId']) ? $params['unionId'] : '';
        $openId = isset($params['openId']) ? $params['openId'] : '';
        $byteOpenId = '';
        if($params['source'] == StatusCode::$source['ByteProgram']){
            $byteOpenId = $openId;
            $openId = '';
        }
        //如果是微信绑定 判断是否有openId 和 unionId 如果是抖音绑定 把openId赋值给byteOpenId
        $avatar = isset($params['avatar']) ? $params['avatar'] : '';
        $name = isset($params['name']) ? $params['name'] : '';
        $salesManId = isset($params['salesManId']) ? $params['salesManId'] : '';
        unset($params['salesManId']);
        unset($params['unionId']);
        unset($params['openId']);
        unset($params['avatar']);
        unset($params['name']);
        //判断userCenter是否已经存在
        $dbResult = $this->objDUserCenter->get(['mobile' => $params['mobile'], 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        $userCenterData = $dbResult;
        unset($dbResult);
        if(empty($userCenterData)){
            //不存在
            //添加userCenter
            $dbResult = $this->objDUserCenter->insert($params);
            if ($dbResult === false) {
                $this->objDUserCenter->rollBack();
                return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
            }
            $userCenterId = $dbResult;
            unset($dbResult);
        }else{
            $userCenterId = $userCenterData['id'];
        }

        //状态 为已审核
        $status = StatusCode::$auditStatus['auditPass'];
        //查询系统设置
        $objMBasicSetup = new MBasicSetup($this->enterpriseId);
        $modelResult = $objMBasicSetup->getBasicSetup();
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $system = $modelResult->getData();
        //判断系统设置审核
        if (isset($system['basicData']) && isset($system['basicData']['personnelReview']) && $system['basicData']['personnelReview'] == StatusCode::$standard) {
            //如果开启客户审核 把状态待补全
            $status = StatusCode::$auditStatus['completion'];
        }
        //查询业务员
        $salesManData = [];
        if(!empty($salesManId)){
            $sql = 'select id,staffCode,staffName from qianniao_staff_'.$this->enterpriseId.' where id = '.$salesManId.' and deleteStatus = '.StatusCode::$standard;
            $dbResult = $this->objDCustomer->query($sql);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
            }
            $salesManResult = $dbResult;
            unset($dbResult);
            if(!empty($salesManResult)){
                $salesManData = array_shift($salesManResult);
            }
        }


        $objChineseCharacter = new ChineseCharacter();
        $condition = $objChineseCharacter->getInitials(trim($name));

        $customerType = 0;
        $shopId = 0;

        //默认店铺信息
        $objDEnterprise = new DEnterprise();
        $objDEnterprise->setTable('qianniao_enterprise_1');
        $objDShop = new DShop();
        $objDShop->setTable('qianniao_shop_1');
        $enterpriseDate = $objDEnterprise->get(['id'=>$this->enterpriseId]);
        if ($enterpriseDate === false) {
            return ResultWrapper::fail($objDShop->error(), ErrorCode::$dberror);
        }

        // 判断是否是单店铺 单店铺
        if($enterpriseDate['scope'] == StatusCode::$delete){
            $shopDate = $objDShop->get(['enterpriseId'=>$this->enterpriseId]);
            if ($shopDate === false) {
                return ResultWrapper::fail($objDShop->error(), ErrorCode::$dberror);
            }
            $shopId = $shopDate['id'];
        }

        // 默认客户类型
        $objMCustomerSource = new MCustomerSource($this->enterpriseId);
        $defaultType = $objMCustomerSource->getCustomerSourceList();
        if (!$defaultType->isSuccess()) {
            return ResultWrapper::fail($defaultType->getData(), $defaultType->getErrorCode());
        }

        foreach ($defaultType->getData() as $typeKey => $typeVal){
            if($typeVal['defaultStatus'] == StatusCode::$standard){//默认客户类型
                $customerType = $typeVal['id'];
            }
        }

        //添加customer
        $customerData = [
            'userCenterId' => $userCenterId,
            'enterpriseId' => $this->enterpriseId,
            'status'       => $status,
            'name'         => $name,
            'condition'    => $condition,
            'avatar'       => $avatar,
            'enableStatus' => StatusCode::$standard,//启用状态
            'openId'       => $openId,
            'unionId'      => $unionId,
            'shopId'        =>$shopId,
            'type'          =>$customerType,
        ];
        if(!empty($salesManData)){
            $customerData['salesManId'] = $salesManData['id'];
            $customerData['salesManCode'] = $salesManData['staffCode'];
            $customerData['salesManName'] = $salesManData['staffName'];
        }
        $byteOpenId && $customerData['byteOpenId'] = $byteOpenId;
        $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, 1);
        $this->objDCustomer->setTable($tableName);
        $customerId = $this->objDCustomer->insert($customerData);
        if ($customerId === false) {
            $this->objDUserCenter->rollBack();
            return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
        }

        //添加企业和userCenter的关联关系
        $userBindEnterpriseData = [
            'userCenterId' => $userCenterId,
            'roleType'     => StatusCode::$roleType['customer'],
            'enterpriseId' => $this->enterpriseId,
            'updateTime'   => time(),
            'createTime'   => time(),
        ];
        $dbResult = $this->objDUserBindEnterprise->insert($userBindEnterpriseData);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        $this->objDUserCenter->commit();
        parent::coupon([
            'userCenterId' => $userCenterId,
            'customerId'   => $customerId,
            'enterpriseId' => $this->enterpriseId,
        ], 'MRegisterCoupon');

        parent::saveLoginLog([
            'userCenterId'  => $userCenterId,
            'enterpriseId'  => $this->enterpriseId,
            'mobile'        => $params['mobile'],
            'createTime'    => time(),
            'source'        => self::getSource($params['source']), // 来源:
            'actionType'    => '注册', // 操作类型：登录/注册
            'operationData' => $params
        ]);
        //$this->objMCustomer->updateEsData($customerId);
        return ResultWrapper::success($userCenterId);

    }

    /**
     * 短信验证码登录
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
     public function smsLogin($params)
     {
         //查询在该企业是否有绑定数据
         $sql = "SELECT u.id,u.mobile FROM " . $this->objDUserCenter->get_Table() . " AS u JOIN " . $this->objDUserBindEnterprise->get_Table() . " AS e ON u.Id=e.userCenterId WHERE u.mobile=" . $params['mobile'] . " AND e.roleType IN (" . StatusCode::$roleType['customer'] . ") AND e.enterpriseId=" . $this->enterpriseId;
         $result = $this->objDUserCenter->query($sql);
         if ($result === false) {
             return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
         }

         $userInfo = [];
         if(!empty($result)){
             $userInfo = array_shift($result);
             if(empty($userInfo)) $result = [];
         }
         //判断绑定数据
         if(!empty($result)){
             //存在
             $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, 1);
             $this->objDCustomer->setTable($tableName);
             $statusResult = $this->objDCustomer->get(['userCenterId' => $userInfo['id']]);
             if($statusResult === false){
                 return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
             }
             if(empty($statusResult)){
                $result = [];
             }else{
                 if (isset($statusResult['enableStatus']) && (int)$statusResult['enableStatus'] != StatusCode::$standard) {
                     return ResultWrapper::fail('账号被禁用', ErrorCode::$accountfail);
                 }
             }
         }

         //没有客户数据
         if(empty($result)){
             //不存在
             //去注册
             $insertData = [
                 'mobile' => $params['mobile'],
                 'source' => $params['source'],
                 'salesManId' => $params['salesManId'],
                 'isCustomer' => StatusCode::$customerType['customer'],
                 'createTime' => time(),
                 'updateTime' => time(),
             ];
             $modelResult = self::register($insertData);
             if(!$modelResult->isSuccess()){
                 return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
             }
             $userInfo = [
                 'id' => $modelResult->getData(),
                 'mobile' => $params['mobile'],
             ];
         }

         parent::saveLoginLog([
             'userCenterId'  => $userInfo['id'],
             'enterpriseId'  => $this->enterpriseId,
             'mobile'        => $userInfo['mobile'],
             'createTime'    => time(),
             'source'        => self::getSource($params['source']), // 来源:
             'actionType'    => '登录', // 操作类型：登录/注册
             'operationData' => $params
         ]);
         parent::coupon([
             'userCenterId' => $userInfo['id'],
             'customerId'   => isset($statusResult['id']) ? $statusResult['id'] : '',
             'enterpriseId' => $this->enterpriseId,
         ], 'MGrantCoupon');
         $returnData = self::createToken($userInfo);
         return ResultWrapper::success($returnData);
     }

    /**
     * 前台登陆 判断用户是否在当前企业已注册
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function login($params)
    {
        $sql = "SELECT u.id,u.mobile,u.password FROM " . $this->objDUserCenter->get_Table() . " AS u JOIN " . $this->objDUserBindEnterprise->get_Table() . " AS e ON u.Id=e.userCenterId WHERE u.mobile=" . $params['mobile'] . " AND e.roleType IN (" . StatusCode::$roleType['customer'] . ") AND e.enterpriseId=" . $this->enterpriseId;
        $result = $this->objDUserCenter->query($sql);
        if ($result === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }

        if (empty($result)) {
            return ResultWrapper::fail('账号不存在', ErrorCode::$userNotFount);
        }
        $userInfo = array_shift($result);

        if (password_verify($params['password'], $userInfo['password']) === false) {
            return ResultWrapper::fail('账号密码错误', ErrorCode::$accountfail);
        }

        //判断该账号是否是启用状态
        $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, 1);
        $this->objDCustomer->setTable($tableName);
        $statusResult = $this->objDCustomer->get_by('userCenterId', $userInfo['id']);
        if (isset($statusResult['enableStatus']) && (int)$statusResult['enableStatus'] != StatusCode::$standard) {
            return ResultWrapper::fail('账号被禁用', ErrorCode::$accountfail);
        }

        parent::saveLoginLog([
            'userCenterId'  => $userInfo['id'],
            'enterpriseId'  => $this->enterpriseId,
            'mobile'        => $userInfo['mobile'],
            'createTime'    => time(),
            'source'        => self::getSource($params['source']), // 来源:
            'actionType'    => '登录', // 操作类型：登录/注册
            'operationData' => $params
        ]);
        parent::coupon([
            'userCenterId' => $userInfo['id'],
            'customerId'   => isset($statusResult['id']) ? $statusResult['id'] : '',
            'enterpriseId' => $this->enterpriseId,
        ], 'MGrantCoupon');
        $returnData = self::createToken($userInfo);
        return ResultWrapper::success($returnData);
    }

    public function getSource($sourceValue)
    {
        foreach (StatusCode::$source as $key => $source) {
            if ($sourceValue == $source) {
                return $key;
            }
        }
    }

    /**
     * 修改用户在当前企业的密码
     * @param $params
     * @param $where
     * @return ResultWrapper
     */
    public function changePassword($params, $where)
    {
        $dbResult = $this->objDUserCenter->update($params, $where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 创建token
     * @param $userInfo
     * @return array
     */
    public function createToken($userInfo)
    {
        //jwt过期时间
        $expireTime = time() + 7200;

        $payload = array(
            'uid'        => $userInfo['id'],
            'expireTime' => $expireTime,
        );
        $encoded = JWT::encode($payload, SITE_SECRET);

        return [
            'expireTime' => $expireTime,
            'token'      => $encoded,
        ];

    }

    /**
     * 检查是否绑定
     * @param $postData
     * @return ResultWrapper
     */
    public function checkBind($postData)
    {
        $source = $postData['source'];
        unset($postData['source']);
        $userCenterId = $this->objMCustomer->getUserCenterIdByOpenIdOrUnionId($postData,$source);
        if(!$userCenterId->isSuccess()){
            return ResultWrapper::fail($userCenterId->getData(), $userCenterId->getErrorCode());
        }
        //返回绑定数据
        $userCenterData = $userCenterId->getData();
        if(!empty($userCenterData)){

            $userData = array_shift($userCenterData);
            //有绑定数据
            $updateData = [];
            if($source == StatusCode::$source['miniProgram']){
                //如果是小程序检查是否绑定 不需要修改openId
                //判断openid是否为空 如果为空 覆盖
                if(isset($userData['openId']) && !empty($postData['openId'])){
                    $updateData['openId'] = $postData['openId'];
                }
                //判断unionId是否为空 如果为空 覆盖
                if(isset($userData['unionId']) && !empty($postData['unionId'])){
                    $updateData['unionId'] = $postData['unionId'];
                }
                if(!empty($updateData)){
                    $modelResult = $this->objMCustomer->setCustomerData(['id' => $userData['id']], $updateData);
                    if(!$modelResult->isSuccess()){
                        return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
                    }
                }
            }
            $userCenterId = $userData['userCenterId'];
        }else{
            //没有绑定
            return ResultWrapper::success(['status' => false]);
        }

        $returnData = self::createToken(['id' => $userCenterId]);
        return ResultWrapper::success($returnData);
    }


    /**
     * 绑定openid和mobile
     * @param $source
     * @param $mobile
     * @param $openId
     * @param $unionId
     * @param $enterpriseId
     * @param string $avatar
     * @param string $name
     * @return ResultWrapper
     */
    public function bindMobileAndOpenId($source, $mobile, $openId, $unionId,$enterpriseId, $avatar = '', $name = '')
    {
        //查询手机号是否注册过
        $userCenterId = $this->objMUserCenterRegister->mobileIsRegister($mobile, $enterpriseId);
        if(!$userCenterId){
            //未注册
            return ResultWrapper::fail('手机号未注册', ErrorCode::$paramError);
        }
        //手机号已注册，则绑定完openid返回token
        $modelResult = $this->objMCustomer->bindOpenIdAndMobile($source, $userCenterId, $openId, $unionId, $avatar, $name);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $returnData = self::createToken(['id' => $userCenterId]);
        return ResultWrapper::success($returnData);
    }
}