<?php

namespace Biz\Account\Repository;

use Biz\TokenManager;
use App\Commons\Model\Account_detailed;
/**
 * Created by PhpStorm.
 * User: wang
 * Date: 2017/6/13
 * Time: 9:23
 */
class AccountRepository {
    private $tokenManager;

    public function __construct() {
        $this->tokenManager = new TokenManager();
    }

    /**
     * 验证用户状态
     *
     * @param $userInfo
     * @return array
     */
    public function checkAccountStatus($userInfo) {
        $result = [];
        if ($userInfo->status == 0) {
            $result['status'] = -4001;
            $result['msg'] = lang()->get('sorry, this user does not exist');
        } elseif ($userInfo->status == -1) {
            $result['status'] = -4007;
            $result['msg'] = lang()->get('sorry, the account has been disabled');
        } elseif ($userInfo->status == -2) {
            $result['status'] = -4007;
            $result['msg'] = lang()->get('Sorry, the account is unusual');
        } elseif ($userInfo->status == 1) {
            $result = false;
        }
        return $result;
    }

    /**
     * 添加密码
     *
     * @param $password
     * @param $identity
     * @throws \Exception
     */
    public function addPassword($password, $identity) {
        $pwd = GenPassword($password);
        $accountPassword = [
            'account_identity' => $identity,
            'identity' => UUID(),
            'encryption' => $pwd['encryption'],
            'account_password' => $pwd['password'],
        ];
        $res = lm('account_password', 'Commons')->insert($accountPassword);
        if (!$res) {
            return -4113;
        }
        return 1;
    }

    /**
     * 验证两次密码是否一致
     *
     * @param $password
     * @param $againPassword
     * @return bool
     */
    public function checkPassword($password, $againPassword) {
        if ($password != $againPassword) {
            $result['status'] = -4006;
            $result['msg'] = lang()->get('the two password is different');
            return $result;
        } else {
            return false;
        }
    }

    /**
     * 添加用户详情
     *
     * @param $data
     * @param $identity
     * @throws \Exception
     */
    public function addAccountDetailed($data, $identity) {
        $invitation = isset($data['introduce_user']) ? $data['introduce_user'] : '';
        $email = isset($data['email']) ? $data['email'] : '';
        $qq = isset($data['qq']) ? $data['qq'] : '';
        $phone = isset($data['phone']) ? $data['phone'] : '';
        $wechat = isset($data['wechat']) ? $data['wechat'] : '';
        $name = isset($data['name']) ? $data['name'] : '';
        $open_invitation = isset($data['open_invitation']) ? $data['open_invitation'] : '';
        $parent_id = isset($data['parent_id']) ? $data['parent_id'] : '';
        $parent_path = isset($data['parent_path']) ? $data['parent_path'] : '';
        $level = isset($data['level']) ? $data['level'] : '';
        $wagent_name = isset($data['wagent_name']) ? $data['wagent_name'] : '';

        $accountDetailed = [
            'phone' => $phone,
            'invitation' => $invitation,
            'register_time' => date('Y-m-d H:i:s'),
            'register_ip' => GETIP(),
            'last_ip' => GETIP(),
            'account_identity' => $identity,
            'identity' => UUID(),
            'email' => $email,
            'wechat' => $wechat,
            'name' => $name,
            'qq' => $qq,
            'open_invitation' => $open_invitation,
            
        ];
        if (!empty($parent_id)) {
            $accountDetailed['parent_id'] = $parent_id;
        }
				
        if (!empty($parent_path)) {
            $accountDetailed['parent_path'] = $parent_path;
        }
        if (!empty($level)) {
            $accountDetailed['level'] = $level;
        }
		
		if (!empty($wagent_name)){
			$accountDetailed['wagent_name'] = $wagent_name;
		}
		
        $res = lm('account_detailed', 'Commons')->insert($accountDetailed);
        if (!$res) {
            return -30101;
        }
        return 1;
    }

    /**
     * 用户注册数据验证
     *
     * @param $data
     * @return array|bool
     */
    public function checkRegisterData($data) {
        if (!$data['account']) {
            $result = ['status' => -4010, 'msg' => lang()->get('account cannot be empty')];
            return $result;
        }
        if (!$data['password']) {
            $result = ['status' => -4011, 'msg' => lang()->get('password cannot be empty')];
            return $result;
        }
        if (!$data['again_password']) {
            $result = ['status' => -4012, 'msg' => lang()->get('verify that the password is not empty')];
            return $result;
        }
        if (empty($data['name'])) {
            $result = ['status' => -4013, 'msg' => lang()->get('name is empty')];
            return $result;
        }
        if(empty($data['phone'])){
            $result = ['status' => -4300, 'msg' => lang()->get('phone is empty')];
            return $result;
        }else{
            
            $account_detailed = new Account_detailed();
            $where['phone'] = $data['phone'];
            $num = $account_detailed->getUsernum($where);
            if($num != 0){
                $result = ['status' => -4301, 'msg' => lang()->get('Existing mobile phone number')];
                return $result;
            }
        }
        return false;
    }

    /**
     * 登录是否过期验证
     *
     * @param $account
     * @return array
     * @throws \Exception
     */
    public function checkEffectiveTime($account, $effective = 1800) {
        $accountToken = lm('account_token', 'Commons')->where('account_identity', $account->account_identity)->first();
        if (strtotime('now') > ($accountToken->effective_time + $effective)) {
            return $this->updateToken($account->account_identity);
        } else {
            return $this->updateEffectiveTime($account->account_identity, $account->token);
        }
    }

    /**
     * 登录过期刷新token
     *
     * @param $accountIdentity
     * @return array
     * @throws \Exception
     */
    public function updateToken($accountIdentity) {
        $token = $this->tokenManager->getToken();
        lm('account_detailed', 'Commons')->where('account_identity', $accountIdentity)->update(['token' => $token]);
        lm('agent_detailed', 'Commons')->where('agent_identity', $accountIdentity)->update(['agent_token' => $token]);
        unset($_SESSION['uinfo']);
        unset($_SESSION['agent']);
        $result = ['status' => 1, 'msg' => lang()->get('success')];
        return $result;
    }

    /**
     * 更新登录过期时间
     *
     * @param $accountIdentity
     * @return array
     * @throws \Exception
     */
    public function updateEffectiveTime($accountIdentity, $token) {
        lm('account_token', 'Commons')->where('account_identity', $accountIdentity)->update(['effective_time' => strtotime('now'), 'last_time' => date('Y-m-d H:i:s')]);
        lm('account_detailed', 'Commons')->where('account_identity', $accountIdentity)->update(['last_time' => date('Y-m-d H:i:s')]);
        $userInfo = $this->tokenManager->getAccountInfo($token);
        if (!$userInfo)
            return ['data' => '', 'status' => '-4001', 'msg' => lang()->get('-4001')];
        $data = $_SESSION['uinfo'] = $userInfo->toArray();
        $result = ['data' => $data, 'status' => 1, 'msg' => lang()->get('success')];
        return $result;
    }

    /**
     * 修改支付密码，验证原密码
     *
     * @param $token
     * @param $oldPassword
     * @return array|bool
     * @throws \Exception
     */
    public function checkOldPayPassword($token, $oldPassword) {
        $accountDetailed = lm('account_detailed', 'Commons')->where('token', $token)->first();
        if (empty($accountDetailed)) {
            $result = ['status' => -4011, 'msg' => lang()->get('user error')];
            return $result;
        }
        $payPassword = lm('pay_password', 'Commons')->where('account_identity', $accountDetailed->account_identity)->first();
        if (empty($payPassword)) {
            $result = ['status' => -4012, 'msg' => lang()->get('no payment password, please set the payment password first')];
            return $result;
        }
        if ($payPassword->pay_password != md5(md5($payPassword->encryption . $oldPassword))) {
            $result = ['status' => -4013, 'msg' => lang()->get('old password error')];
            return $result;
        }
        return ['status' => 1, 'account_identity' => $accountDetailed->account_identity];
    }

    /**
     * 销毁超过3天的免费试玩账号
     *
     * @param $account
     * @throws \Exception
     */
    public function destroyAccount($account) {
        $gameInfo = lm('game_type', 'Commons')->where('table_name', '<>', '-1')->get();
        $accountToken = lm('account_token', 'Commons');
        $accountDetailedModel = lm('account_detailed', 'Commons');
        $accountModel = lm('account', 'Commons');
        $accountPassword = lm('account_password', 'Commons');
        $moneyBuy = lm('money_buy', 'Commons');
        $moneyDetails = lm('money_details', 'Commons');
        $moneyPrize = lm('money_prize', 'Commons');
        $moneyReturn = lm('money_return', 'Commons');
        $moneyReward = lm('money_reward', 'Commons');
        $sixmoneyBuy = lm('sixMoney_buy', 'Commons');
        $sixmoneyPrize = lm('sixMoney_prize', 'Commons');
        $identitys = array();
        if (count($account) > 0) {
            foreach ($account as $key => $val) {
                $identitys[] = $val['account_identity'];
            }
            //$time = strtotime($val['register_time']) + 3 * 24 * 3600;
            //if (time() > $time) {
            $accountToken->whereIn('account_identity', $identitys)->delete();
            $accountDetailedModel->whereIn('account_identity', $identitys)->delete();
            $accountPassword->whereIn('account_identity', $identitys)->delete();
            $accountModel->whereIn('identity', $identitys)->delete();
            $moneyBuy->whereIn('account_identity', $identitys)->delete();
            $moneyDetails->whereIn('account_identity', $identitys)->delete();
            $moneyPrize->whereIn('account_identity', $identitys)->delete();
            $moneyReturn->whereIn('account_identity', $identitys)->delete();
            $moneyReward->whereIn('account_identity', $identitys)->delete();
            $sixmoneyBuy->whereIn('account_identity', $identitys)->delete();
            $sixmoneyPrize->whereIn('account_identity', $identitys)->delete();
            if (count($gameInfo) > 0) {
                foreach ($gameInfo as $k => $v) {
                    $cls = '\\App\\Commons\\Model\\' . ucfirst($v['table_name']) . '_buy';
                    if (class_exists($cls)) {
                        lm($v['table_name'] . '_buy', 'Commons')->whereIn('account_identity', $identitys)->delete();
                    }
                }
            }
            //}
        }
    }

    /**
     * 注册试玩用户
     *
     * @param $uname
     * @return array
     * @throws \Exception
     */
    public function demoAccount($uname, $pwd) {
        $id = UUID();
        $account = [
            'account' => $uname,
            'identity' => $id,
            'status' => 4,
        ];
        lm('account', 'Commons')->insert($account);
        $this->addPassword($pwd, $id);
        $tokenManager = new TokenManager();
        $token = $tokenManager->getToken();
        $accountDetailed = [
            'identity' => UUID(),
            'account_identity' => $id,
            'available_cash' => 2000,
            'token' => $token,
            'register_time' => date('Y-m-d H:i:s'),
            'register_ip' => GETIP(),
            'last_ip' => GETIP(),
            'grade' => 0,
            'cash' => 2000,
            'frozen_cash' => 0,
        ];
        lm('account_detailed', 'Commons')->insert($accountDetailed);
        return ['data' => $token, 'status' => 1, 'msg' => lang()->get('success')];
    }

    /**
     * 代理用户是否存在
     *
     * @param $agentUser
     * @return int
     * @throws \Exception
     */
    public function checkAgent($agentUser) {
        $agent = lm('agent_detailed', 'Commons')->where('invite', $agentUser)->first();
        if ($agent) {
            return 1;
        }
        return -4017;
    }

    /**
     * 代理用户登录
     *
     * @param $data
     * @return array|int
     * @throws \Exception
     */
    public function agentLogin($data) {
        if (!$agent = lm('agent_detailed', 'Commons')->where('agent_user', $data['agent_user'])->first()) {
            return -4017;
        }
        $row = $this->checkAgentPassword($data['agent_user'], $data['password']);
        if ($row != 1) {
            return $row;
        }
        $str_token = $this->tokenManager->getToken();
        $this->publishAgentToken($agent->agent_identity, $str_token);
        $agentDetailed = $this->getAgentDetailed($str_token);
        if (!$agentDetailed) {
            return -4017;
        }
        $_SESSION['agent'] = $agentDetailed->toArray();
        return $agentDetailed->toArray();
    }

    /**
     * 验证代理用户登录密码
     *
     * @param $user
     * @param $password
     * @return int
     * @throws \Exception
     */
    public function checkAgentPassword($user, $password) {
        if ($agentDetailed = lm('agent_detailed', 'Commons')->where(['agent_user' => $user, 'status' => 1])->first()) {
            $dataPassword = md5(md5($agentDetailed->encryption . $password));
            return $dataPassword == $agentDetailed->password ? 1 : -4021;
        } else {
            return -4017;
        };
    }

    /**
     * 更新代理用户token有效时间
     *
     * @param $agentIdentity
     * @param $token
     * @throws \Exception
     */
    public function publishAgentToken($agentIdentity, $token) {

        lm('agent_detailed', 'Commons')->where('agent_identity', $agentIdentity)->update(array('agent_token' => $token));

}

    /**
     * @param $accountIdentity 检测是否是代理用户
     */
    public function IsAgent($accountIdentity) {
        $data = lm('agent_detailed', 'Commons')->where('agent_identity', $accountIdentity)->first();
        if (empty($data)) {
            return -321;
        }
        return 1;
    }

    /**
     * token获取代理用户信息
     *
     * @param $token
     * @return mixed
     * @throws \Exception
     */
    public function getAgentDetailed($token) {
        return lm('agent_detailed', 'Commons')->where('agent_token', $token)->first();
    }

    public function getAgentInfo($agent_identity) {
        return lm('agent_detailed', 'Commons')->where('agent_identity', $agent_identity)->first();
    }

    /**
     * 代理用户token是否过期
     *
     * @param $agentTokenOverdue
     * @return array|int
     * @throws \Exception
     */
    public function agentTokenOverdue($agentTokenOverdue) {
        $accountToken = lm('account_token', 'Commons')->where('account_identity', $agentTokenOverdue->agent_identity)->first();
        if (!$accountToken) {
            return -4019;
        }
        if (strtotime('now') > $accountToken->effective_time) {
            return $this->updateAgentToken($agentTokenOverdue->agent_identity);
        } else {
            return $this->updateAgentEffectiveTime($agentTokenOverdue->agent_identity, $agentTokenOverdue->agent_token);
        }
    }

    /**
     * 更新代理用户登录token
     *
     * @param $agentIdentity
     * @return int
     * @throws \Exception
     */
    public function updateAgentToken($agentIdentity) {
        $token = $this->tokenManager->getToken();
        lm('agent_detailed', 'Commons')->where('agent_identity', $agentIdentity)->update(['agent_token' => $token]);
        unset($_SESSION['agent']);
        return -4019;
    }

    /**
     * 更新代理用户登录过期时间
     *
     * @param $accountIdentity
     * @return array
     * @throws \Exception
     */
    public function updateAgentEffectiveTime($accountIdentity, $token) {
        lm('account_token', 'Commons')->where('account_identity', $accountIdentity)->update(['effective_time' => strtotime('now') + 1200]);
        //lm('account_token', 'Commons')->where('account_identity', $accountIdentity)->update(['effective_time' => strtotime('now')]);
        $agentDetailed = $this->getAgentDetailed($token);
        $_SESSION['agent'] = $agentDetailed->toArray();
        return $agentDetailed->toArray();
    }

    /**
     * 注册添加代理用户
     *
     * @param $data
     * @throws \Exception
     */
    public function addAgentDetailed($data) {
        $pwd = GenPassword($data['password']);
        $invite = substr(uniqid(md5($data['agent_user'])), 0, 32);
        $insertData = [
            'agent_identity' => $data['agent_identity'],
            'agent_user' => $data['agent_user'],

            'phone' => $data['phone'],

            'start_time' => date('Y-m-d H:i:s'),
            'invite' => $invite,
            'email' => $data['email'],
            'bank_number' => $data['bank_number'],

            'type' => $data['type'],
        ];
        $res = lm('agent_detailed', 'Commons')->insert($insertData);
        if (!$res) {
            return -141313;
        }
        return 1;
    }

    /**
     * 获取游戏分类
     *
     * @param $key
     * @param $val
     * @param $result
     * @return mixed
     */
    public function getResult($key, $val, $result) {
        substr($key, 0, 5) == 'chain' ? $parent = 'chain' : '';
        substr($key, 0, 6) == 'dragon' ? $parent = 'dragon' : '';
        substr($key, 0, 8) == 'head_one' ? $parent = 'head_one' : '';
        substr($key, 0, 8) == 'head_two' ? $parent = 'head_two' : '';
        substr($key, 0, 10) == 'head_three' ? $parent = 'head_three' : '';
        substr($key, 0, 7) == 'poscode' ? $parent = 'poscode' : '';
        substr($key, 0, 5) == 'color' ? $parent = 'color' : '';
        substr($key, 0, 3) == 'mix' ? $parent = 'mix' : '';
        substr($key, 0, 4) == 'size' ? $parent = 'size' : '';
        substr($key, 0, 11) == 'specialCode' ? $parent = 'specialCode' : '';
        $str = explode(':', $key);
        $result[$str[0]] = $this->getArray($key, $val, $parent, $result[$str[0]]);
        return $result;
    }

    /**
     * 单个游戏分类组装数据
     *
     * @param $name
     * @param $val
     * @param $parent
     * @param $result
     * @return mixed
     */
    public function getArray($name, $val, $parent, $result) {
        $str = explode(':', $name);
        $result['parent'] = $parent;
        $result['name'] = $str[0];
        $result['type'] = 0;
        if ($str[1] == 'max' || $str[1] == 'min') {
            $result['settings']['multiple'][$str[1]] = $val;
        } elseif ($str[1] == 'back') {
            $result['settings'][$str[1]] = $val;
        } elseif ($str[1] = 'multiple') {
            $result['settings'][$str[1]] = $val;
        }
        return $result;
    }

    /**
     * 增加用户上下级关系
     * @param [type] $invitation   邀请码
     * @param [type] $account_name 用户名
     * @param [type] $user_id      用户id
     */
    public function addParent($invitation, $arr) {
        $agent = $this->getAgent($invitation);
        if ($agent < 0) {
            return $agent;
        }
        $data = array(
            'agent_identity' => $agent['agent_identity'],
            'agent_name' => $agent['agent_user'],
            'account_name' => $arr['account'],
            'account_identity' => $arr['identity'],
        );
        $res = lm('agent_child', 'Commons')->insert($data);
    }

    /**
     * 根据邀请码获取代理信息
     * @param  [type] $invite 邀请码
     * @return [type]         [description]
     */
    public function getAgent($invite) {
        $res = lm('agent_detailed', 'Commons')->where('id', $invite)->first();
        if (!$res) {
            return -4017;
        }
        return $res->toArray();
    }

    //检测邀请码是否存在
    public function checkInvitation($invitation) {
        $res = lm('account_detailed', 'Commons')
            ->leftJoin('account', 'account.identity', '=', 'account_detailed.account_identity')
            ->where('account_detailed.open_invitation', $invitation)
            ->first();
        if (!$res) {
            return -4017;
        }
        return $res->toArray();
    }

    //添加代理人,代理下级
    public function addNewAgent($data) {
        $res = lm('nagent_child', 'Commons')->insert($data);
        if (!$res) {
            return -141313;
        }
        return 1;
    }

    //添加代理人
    public function addNewAgentDetail($data) {
        $res = lm('nagent_detailed', 'Commons')->insert($data);
        if (!$res) {
            return -141313;
        }
        return 1;
    }

    //获取root用户
    public function getRoot() {
        $root = lm('account', 'Commons')
            ->leftJoin('account_detailed', 'account.identity', '=', 'account_detailed.account_identity')
            ->where('account.id', 83632)
            ->first();
        if (!$root) {
            return -4107;
        }
        return $root->toArray();
    }
}
