<?php
/**
 * 用户中心注册管理Model
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/01
 * Time: 14:50
 */

namespace JinDouYun\Model\UserCenter;

use JinDouYun\Model\Customer\MCustomer;
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;

class MUserCenterRegister
{
    private $objDUserBindEnterprise;
    private $objDUserCenter;

    public function __construct()
    {
        $this->objDUserCenter = new DUserCenter('default');
        $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
    }

    /**
     * 后台注册 用户中心添加
     * @param $params
     * @return ResultWrapper
     */
    public function addUserCenter($params)
    {
        $params['isCustomer'] = StatusCode::$customerType['user'];
        $params['createTime'] = $params['updateTime'];
        //查询账号是否存在
        $dbResult = $this->objDUserCenter->get(['mobile'=>$params['mobile'], 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        $userCenter = $dbResult;
        unset($dbResult);
        if(empty($userCenter)){
            $dbResult = $this->objDUserCenter->insert($params);
        }else{
            if($userCenter['isCustomer'] == StatusCode::$customerType['user']){
                return ResultWrapper::fail('手机号已被注册', ErrorCode::$paramError);
            }
            $update = [
                'isCustomer' => StatusCode::$customerType['user'],
                'password' => $params['password'],
                'updateTime' => time()
            ];
            $dbResult = $this->objDUserCenter->update($update, ['id' => $userCenter['id']]);
        }
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 修改手机号(账号)
     * @param $params
     * @return ResultWrapper
     */
    public function updateUserMobile($params)
    {
        //有些表存的手机号无法修改
        $where['id'] = $params['userCenterId'];
        $dbResult = $this->objDUserCenter->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        $user = $dbResult;
        unset($dbResult);
        if(empty($user)){
            return ResultWrapper::fail('用户不存在', ErrorCode::$paramError);
        }

        //判断密码是否正确
        if(password_verify($params['password'], $user['password'] ) !== true){
            return ResultWrapper::fail('密码错误', ErrorCode::$accountfail);
        }

        if($params['mobile'] == $user['mobile']){
            return ResultWrapper::success('修改成功');
        }

        $dbResult = $this->objDUserCenter->update(['mobile' => $params['mobile'], 'updateTime' => time()], $where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success('修改成功');
    }

    /**
     * 用户中心删除
     * @param $id
     * @return ResultWrapper
     */
    public function deleteUserCenter($id)
    {
        $params = [
            'deleteStatus' => StatusCode::$delete,
            'updateTime' => time(),
        ];
        $dbResult = $this->objDUserCenter->update($params, $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 用户中心修改
     * @param $params
     * @param $id
     * @return ResultWrapper
     */
    public function updateUserCenter($params, $id)
    {
        $dbResult = $this->objDUserCenter->update($params, $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 用户中心忘记密码
     * @param $password
     * @param $where
     * @return ResultWrapper
     */
    public function updateUserCenterPassword($password, $where)
    {
        $update = [
            'password' => $password
        ];

        $dbResult = $this->objDUserCenter->update($update, $where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 用户中心列表
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAllUserCenter($selectParams)
    {

        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $selectParams['deleteStatus'] = StatusCode::$standard;

        $dbResult = $this->objDUserCenter->select($selectParams, '*', 'createTime desc', $limit, $offset);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }

        $total = $this->objDUserCenter->count($selectParams);

        $return = [
            'data' => $dbResult,
            'total' => ($total) ? intval($total) : 0,
        ];

        if ($return === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($return);
        }
    }

    /**
     * 用户中心详情
     * @param $params
     * @return ResultWrapper
     */
    public function getUserCenterInfo($params)
    {
        $dbResult = $this->objDUserCenter->get($params);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 判断是否注册
     * @param $mobile
     * @param $enterpriseId // null:查询是否有userCenter数据 其他:查询手机号与该企业的绑定数据
     * @param $isStaff // true:查询后台是否绑定  false 查询前台是否绑定
     * @return bool
     */
    public function mobileIsRegister($mobile, $enterpriseId = null, $isStaff = false) {
       $userCenterId = false;
       if($enterpriseId) {
           $roleType = $isStaff ? StatusCode::$roleType['admin'].','.StatusCode::$roleType['staff'] : StatusCode::$roleType['customer'];

           $sql = "select u.id from ".$this->objDUserCenter->get_Table()." as u join ".$this->objDUserBindEnterprise->get_Table() ." as e on u.Id=e.userCenterId where u.mobile=". $mobile ." and e.roleType in (".$roleType.") and e.enterpriseId = ".$enterpriseId.' LIMIT 1';
           $dbResult = $this->objDUserCenter->query($sql);
           if($dbResult) {
               $dbResult = array_shift($dbResult);
               $userCenterId = isset($dbResult['id']) ? $dbResult['id'] : false;
           }
       } else {
           //后台判断是否注册
           $where = [
               'mobile' => $mobile,
               'isCustomer' => StatusCode::$delete
           ];
           $dbResult = $this->objDUserCenter->get($where);
           $userCenterId = $dbResult ? $dbResult['id'] : false;
       }
       return $userCenterId;
    }

    /**
     * 手机号在指定企业是否存在角色(后台专用)
     * @param $mobile
     * @param $enterpriseId
     * @param int $roleType
     * @return ResultWrapper
     */
    public function mobileBindStatus($mobile, $enterpriseId, $roleType = 1)
    {
        //查询userCenter
        $dbResult = $this->objDUserCenter->get(['mobile' => $mobile]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        $userCenter = $dbResult;
        unset($dbResult);
        //判断客户 还是用户
        if(empty($userCenter)){
            return ResultWrapper::success(0);
        }
        //如果是客户 则为用户不存在
        if($userCenter['isCustomer'] == StatusCode::$customerType['customer']){
            return ResultWrapper::success(0);
        }
        //查询绑定表
        $dbResult = $this->objDUserBindEnterprise->get(['userCenterId' => $userCenter['id'], 'enterpriseId' => $enterpriseId, 'roleType' => $roleType]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        $bind = $dbResult;
        unset($dbResult);
        //判断是否有绑定数据
        if(empty($bind)){
            return ResultWrapper::success(0);
        }
        return ResultWrapper::success($userCenter['id']);
    }

    /**
     * 指定企业指定角色添加用户
     * @param $mobile
     * @param $roleType
     * @param $enterpriseId
     * @param bool $shopId
     * @return ResultWrapper
     */
    public function addUser($mobile, $roleType, $enterpriseId, $shopId = false)
    {
        //1.查询手机号是否注册
        $dbResult = $this->objDUserCenter->get(['mobile' => $mobile]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        $userCenterData = $dbResult;
        unset($dbResult);

        //2.未注册手机号进行注册
        if(empty($userCenterData)){
            //添加userCenter
            $password = '88888888';
            $userCenterAddData['mobile'] = $mobile;
            $userCenterAddData['password'] = password_hash($password, PASSWORD_DEFAULT );
            $userCenterAddData['deleteStatus'] = StatusCode::$standard;
            $userCenterAddData['source'] = StatusCode::$source['manage'];
            $userCenterAddData['isCustomer'] = StatusCode::$customerType['user'];
            $userCenterAddData['createTime'] = time();
            $userCenterAddData['updateTime'] = time();
            $dbResult = $this->objDUserCenter->insert($userCenterAddData);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
            }
            $returnData['userCenterId'] = $dbResult;
            unset($dbResult);
            $returnData['title'] = '该手机号未注册, 已自动创建账号, 初始密码'.$password;
        }else{
            $returnData['userCenterId'] = $userCenterData['id'];
            $returnData['title'] = '该手机号号已注册, 绑定成功';
        }

        //3.判断绑定表  没有绑定角色类型的新增绑定
        $where = [
            'userCenterId' => $returnData['userCenterId'],
            'enterpriseId' => $enterpriseId,
            'roleType' => $roleType,
        ];
        if($shopId){
            $where['shopId'] = $shopId;
        }
        $result = $this->objDUserBindEnterprise->get($where);
        if($result === false){
            return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
        }
        if(empty($result)){
            $bindData['userCenterId'] = $returnData['userCenterId'];
            $bindData['enterpriseId'] = $enterpriseId;
            $bindData['roleType'] = $roleType;
            $bindData['updateTime'] = time();
            $bindData['createTime'] = time();
            if($shopId){
                $bindData['shopId'] = $shopId;
            }
            $dbResult = $this->objDUserBindEnterprise->insert($bindData);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
            }
            unset($dbResult);
        }
        return ResultWrapper::success($returnData);
    }

}