<?php

namespace Biz\Account;

use App\Commons\Model\Money_recharge;
use Biz\Account\Repository\AccountRepository;
use Biz\TokenManager;

/**
 * Created by PhpStorm.
 * User: wang
 * Date: 2017/6/12
 * Time: 10:05
 */
// ini_set('display_errors', 1);

// error_reporting(E_ALL);
class AccountManager {

    public function __construct() {
        $this->model = lm('account', 'Commons');
        $this->repository = new AccountRepository();
    }

    /**
     * 用户登录
     *
     * @param $account
     * @param $password
     * @return string
     */
    public function login($account, $password) {

        $password = trim($password);
        $account = strtolower(trim($account));
        define("OVERTIME", 1800);
        if (!$user = $this->getAccount($account)) {
            $result = ['status' => -4025, 'msg' => lang()->get('user does not exist')];
            return $result;
        } else {
            if ($this->checkPassword($user, $password)) {

                try {
                    //绑定用户
                    // lm('user_logs')->bindUser($user->identity,$user->account);
                    $token = new TokenManager();
                    $accountToken = lm('account_token', 'Commons')->where('account_identity', $user->identity)->first();


                    $effective_time = $accountToken->effective_time;
                    if (time() - $effective_time <= OVERTIME) {
                        $tokeninfo = lm('account_detailed', 'commons')
                            ->select('token')
                            ->where('account_identity', $user->identity)->first();
                        if (!$tokeninfo) {
                            return -4025;
                        }
                        if (empty($tokeninfo->token)) {
                            return -4025;
                        }
                        $str_token = $tokeninfo->token;
                    } else {
                        $str_token = $token->publish($user->identity);
                    }
                    $str_token = $token->publish($user->identity);
//                    $this->repository->publishAgentToken($user->identity, $str_token); //更新代理表token
                    $userInfo = $token->doLogin($str_token);
                    if (!$userInfo) {
                        $result = ['status' => -4025, 'msg' => lang()->get('user does not exist')];
                        return $result;
                    }
                    $this->insertLogLife($userInfo);
//                    $agentDetailed = $this->repository->getAgentInfo($user->identity);
//                    if (!empty($agentDetailed)) {
//                        $_SESSION['agent'] = $agentDetailed->toArray();
//                    }
                    $userInfo[0]['ip'] = GETIP();
                    $userInfo[0]['newdevice']['uuid'] = UUID();
                    $userInfo[0]['newdevice']['GetBrowser'] = $this->GetBrowser();
                    $userInfo[0]['newdevice']['device'] = $this->device();
                    $_SESSION['newdevice'] = $userInfo[0]['newdevice'];

                    if (empty($userInfo[0]['open_invitation'])) {

                        $userInfo[0]['open_invitation'] = $userInfo[0]['id'];
                        lm('account_detailed', 'commons')->where('account_identity', $userInfo[0]['account_identity'])->update(['open_invitation' => $userInfo[0]['id']]);

                    } else {
                        if (!is_numeric($userInfo[0]['open_invitation'])) {
                            lm('account_detailed', 'commons')->where('account_identity', $userInfo[0]['account_identity'])->update(['open_invitation' => $userInfo[0]['id']]);
                        }
                    }

                    //老账号添加到新代理表
//                    $nagent = lm('nagent_detailed', 'commons')->where('agent_identity', $userInfo[0]['account_identity'])->first();
//
//                    if (!$nagent) {
//                        $nagentData = [
//                            'agent_identity' => $userInfo[0]['account_identity'],
//                            'agent_user' => $userInfo[0]['account'],
//                            'invite' => $userInfo[0]['open_invitation']
//                        ];
//                        lm('nagent_detailed', 'commons')->where('agent_identity', $userInfo[0]['account_identity'])->insert($nagentData);
//                    } else {
//                        lm('nagent_detailed', 'commons')->where('agent_identity', $userInfo[0]['account_identity'])->update(['invite' => $userInfo[0]['open_invitation']]);
//                    }

                    $userInfo[0]['remark'] = str_replace("%","",$userInfo[0]['remark']);
                    $result = ['data' => $userInfo, 'status' => 1, 'msg' => lang()->get('login successful')];
                    return $result;
                } catch (Exception $e) {
                    $result = ['status' => -4003, 'msg' => lang()->get('login error, login again')];
                    return $result;
                }
            } else {
                $result = ['status' => -4002, 'msg' => lang()->get('password error')];
                return $result;
            };
        }
    }

    /*
     * 生成用户邀请码
     */
    public function setrandomcodes($account_identity) {
        if (empty($account_identity)) {
            return -4080;
        }
        $open_invitation = $this->getRandomString(8);
        $num = lm('account_detailed', 'commons')->where('open_invitation', $open_invitation)->count();
        if ($num == 0) {
            lm('account_detailed', 'commons')->where('account_identity', $account_identity)->update(['open_invitation' => $open_invitation]);
            return 1;
        } else {
            $this->setrandomcodes($account_identity);
        }

    }

    /**
     * 获取用户信息
     *
     * @param $user
     * @return \Sting
     */
    public function getAccount($account) {
        $result = $this->model->where(['account' => $account, 'status' => 1])->first();
        if (!$result) {
            $result = $this->model->where(['account' => $account, 'status' => 4])->first();
        }
        return $result;
    }

    /**
     * 检查登录密码
     *
     * @param $user
     * @param $password
     * @return bool
     */
    public function checkPassword($user, $password) {
        $accountPassword = lm('account_password', 'Commons')->where(['account_identity' => $user->identity, 'status' => 1])->first();
        $dataPassword = md5(md5($accountPassword->encryption . $password));
        return $dataPassword == $accountPassword->account_password ? true : false;
    }

    /**
     * 添加登录日志
     *
     * @param $userInfo
     * @throws \Exception
     */
    public function insertLogLife($userInfo) {
        $type = $this->CheckisMobile();
        if ($type) {
            $intype = "手机端";
            $device_number = $userInfo[0]['device_number'];
        } else {
            $intype = "电脑端";
            $device_number = $_SESSION['newdevice']['uuid'];
        }
        if ($userInfo) {
            $device = $this->device();
            $res = [
                'account_identity' => $userInfo[0]['account_identity'],
                'account' => $userInfo[0]['account'],
                'type' => $intype,
                'add_time' => date('Y-m-d H:i:s', time()),
                'url' => $_SERVER['HTTP_HOST'],
                'ip' => GETIP(),
                'browser' => $this->GetBrowser(),
                'device' => $device['name'],
                'device_model' => $device['sxid'],
                'device_number' => $device_number,
            ];
            lm('Logfile', 'Commons')->insert($res);

        }
    }

    /*移动端判断*/
    public function CheckisMobile() {
        return is_mobile();
    }

    /*获取浏览器*/
    public function GetBrowser() {
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
            $br = $_SERVER['HTTP_USER_AGENT'];
            if (preg_match('/MSIE/i', $br)) {
                $br = 'MSIE';
            } elseif (preg_match('/Firefox/i', $br)) {
                $br = 'Firefox';
            } elseif (preg_match('/Chrome/i', $br)) {
                $br = 'Chrome';
            } elseif (preg_match('/Safari/i', $br)) {
                $br = 'Safari';
            } elseif (preg_match('/Opera/i', $br)) {
                $br = 'Opera';
            } else {
                $br = 'Other';
            }
            return $br;
        } else {
            return "获取浏览器信息失败！";
        }
    }

    /*获取设备*/
    public function device() {
        foreach ($_SERVER as $name => $value) {

            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }

        //截取()之内的数据
        $sname = substr($headers['User-Agent'], strlen('(') + strpos($headers['User-Agent'], '('), (strlen($headers['User-Agent']) - strpos($headers['User-Agent'], ')')) * (-1));
        //遍历数据
        $snameInfo = explode(';', $sname);
        //判断设备型号类型
        if ($snameInfo[0] == 'iPhone') {
            //设备系统：0为Windows系统
            $update['stype'] = 2;
            $update['name'] = 'ios';
            //设备序列号
            $update['sxid'] = $snameInfo[1];
        } elseif ($snameInfo[0] == 'ios') {
            //设备系统：2为IOS系统
            $update['stype'] = 2;
            $update['name'] = 'ios';
            //设备序列号
            $update['sxid'] = $snameInfo[1];
        } elseif ($snameInfo[0] == 'iPad') {
            //设备系统：2为IOS系统
            $update['stype'] = 2;
            $update['name'] = 'ios';
            //设备序列号
            $update['sxid'] = $snameInfo[1];
        } elseif ($snameInfo[0] == 'Linux') {
            //设备系统：1为安卓系统
            $update['stype'] = 1;
            $update['name'] = 'Android';
            //设备序列号
            $update['sxid'] = $snameInfo[2];
        } else {
            //设备系统：1为安卓系统
            $update['stype'] = 0;
            $update['name'] = 'pc';
            //设备序列号
            $update['sxid'] = $snameInfo[2];
        }

        return $update;
    }

    /**
     * 刷新token
     *
     * @return int
     */
    public function refreshToken() {
        $str_token = $_POST['token'] ? trim($_POST['token']) : '';
        $token = new TokenManager();
        $userInfo = $token->getAccountInfo($str_token);
        if (count($userInfo) > 0) {
            $result = ['data' => $userInfo->toArray(), 'status' => 1, 'msg' => lang()->get('success')];
            return $result;
        } else {
            $result = ['status' => -4008, 'msg' => lang()->get('user does not exist')];
            return $result;
        }
    }

    /**
     * 刷新状态
     * @param  [type] $token [description]
     * @return [type]        [description]
     */
    public function refreshStatus($str_token) {

        $token = new TokenManager();
        if (empty($str_token)) {
            return -4001;
        }

        $userInfo = $token->getAccountInfo($str_token);

        $agentInfo = $token->getAgentInfo($str_token);

        if (count($userInfo) > 0) {
            $user = $userInfo->toArray();
            $this->repository->updateEffectiveTime($user['account_identity'], $str_token);
            $_SESSION['uinfo'] = $user;
            if (count($agentInfo) > 0) {
                $_SESSION['agent'] = $agentInfo->toArray();
//                $str_token = $token->getToken();
                //                $this->repository->publishAgentToken($_SESSION['agent']['agent_identity'], $str_token);
            }

            return $user;
        }

        return -4001;

    }

    /**
     * 修改用户密码
     *
     * @access public
     * @param mixed oldPassword旧密码
     * @param mixed newPassword新密码
     * @return array JsonString
     * @throws \Exception
     */
    public function savePassword($post) {
        $userInfo = $this -> getCurrentUser();
        // 判断用户登录
        if (empty($userInfo)) {
            $result = ['status' => -4001, 'msg' => lang() -> get('user does not exist')];
            return $result;
        }
        // 验证用户状态
        if ($row = $this -> repository -> checkAccountStatus($userInfo)) {
            return $row;
        };
        $oldPassword = strip_tags($post['oldPassword']);
        $newPassword = strip_tags($post['newPassword']);
        // 验证两次密码是否一致
        /*if ($r = $this->repository->checkPassword($newPassword, $againPassword)) {
            return $r;
        }*/
        // 验证密码
        if ($this -> checkPassword($userInfo, $oldPassword)) {
            // 密码加密
            $pwdData = GenPassword($newPassword);
            lm('account_password', 'Commons') -> updatePassword($userInfo -> identity, $pwdData);
            $result = ['status' => 1, 'msg' => lang()->get('update successful')];
            return $result;
        } else {
            $result = ['status' => -4009, 'msg' => lang()->get('old password error')];
            return $result;
        };

    }

    /**
     * 修改用户支付密码
     *
     * @access public
     * @param mixed oldPassword旧密码
     * @param mixed newPassword新密码
     * @return array JsonString
     * @throws \Exception
     */
    public function savePayPassword() {
        $userInfo = $this -> getCurrentUser();
        // 判断用户登录
        if (empty($userInfo)) {
            $result = ['status' => -4001, 'msg' => lang() -> get('user does not exist')];
            return $result;
        }
        // 验证用户状态
        if ($row = $this -> repository -> checkAccountStatus($userInfo)) {
            return $row;
        };
        $oldPayPassword = strip_tags($_POST['oldPayPassword']);
        $newPayPassword = strip_tags($_POST['newPayPassword']);
        // 验证两次密码是否一致
        /*if ($r = $this->repository->checkPassword($newPassword, $againPassword)) {
            return $r;
        }*/
        // 验证交易密码
        $this -> verifyPayPwd($userInfo['identity'], $oldPayPassword);
        // 获取新支付密码加密
        $pwdData = GenPassword($newPayPassword);
        // 修改支付密码
        $upPayPwdWhere['account_identity'] = $userInfo['identity'];
        $upPayPwdData['pay_password'] = $pwdData['password'];
        $upPayPwdData['encryption'] = $pwdData['encryption'];
        lm('pay_password', 'Commons') -> updatePayPassword($upPayPwdWhere, $upPayPwdData);
        $result = ['status' => 1, 'msg' => lang()->get('update successful')];

        return $result;
    }

    /**
     * 验证交易密码
     *
     * @access public
     * @param mixed $identity 用户id
     * @param mixed $payPassword 支付密码
     * @return String
     * @throws \Exception
     */
    public function verifyPayPwd($identity, $payPassword) {
        $payPasswordWhere['account_identity'] = $identity;
        $payPasswordSelect = ['encryption'];
        $payPasswordMd = lm('pay_password', "commons");
        // 获取加密盐值
        $accountPwdInfo = $payPasswordMd -> payPassword($payPasswordSelect, $payPasswordWhere);
        $encryptionPwd = md5(md5($accountPwdInfo["encryption"] . $payPassword));
        $verifyPayPwdWhere['account_identity'] = $identity;
        $verifyPayPwdWhere['pay_password'] = $encryptionPwd;
        $verifyPayPwdSelect = ['id'];
        // 验证支付密码
        $verifyPayPwd = $payPasswordMd -> payPassword($verifyPayPwdSelect, $verifyPayPwdWhere);
        if (!$verifyPayPwd['id']) {
            Render([], '2020', lang('Common','Api') -> get('payment password error'));
        }
        return 1;
    }


    /**
     * 修改用户交易密码
     *
     * @return array
     * @throws \Exception
     */
    public function updatePayPassword($post) {
        $checkPassword = $this->repository->checkOldPayPassword($post['token'], strip_tags($post['oldPassword']));
        if ($checkPassword['status'] != 1) {
            return $checkPassword;
        };
        $payPassword = GenPassword(strip_tags($post['pay_password']));
        lm('pay_password', 'Commons')->where('account_identity', $checkPassword['account_identity'])->update(['pay_password' => $payPassword['password'], 'encryption' => $payPassword['encryption']]);
        $result = ['status' => 1, 'msg' => lang()->get('update successful')];
        return $result;
    }

    public function chHeadImg($imgUrl, $imgId) {
        $userInfo = $this->getCurrentUser();
        $uuid = $userInfo->account_identity;
        if (!$uuid) return -4001;
        $lm = lm('AccountDetail', 'Api');
        $ret = $lm->where('account_identity', $uuid)->update(['img_url' => $imgUrl, 'img_id' => $imgId]);
        return $ret;
    }

    /**
     * 获取当前用户信息
     *
     * @return mixed
     * @throws \Exception
     */
    public function getCurrentUser() {
        $token = $_POST['token'];
        $token = trim($token, "\"");

        $token = trim($token, "'");

        $userInfo = lm('account_detailed', 'Commons')->join('account', 'account_detailed.account_identity', '=', 'account.identity')->where('account_detailed.token', $token)->first();
        if (empty($userInfo)) {
            return false;
        }
//        $userInfo->identity = $userInfo->account_identity;
        return $userInfo;
    }

    /**
     * 用户注册
     *
     * @return array
     */
    public function register($post) {

        if ($check = $this->repository->checkRegisterData($post)) {
            return $check;
        };
        foreach ($post as $k => $v) {
            $post[$k] = strip_tags($v);
        }
        $post['account'] = strtolower($post['account']);
        //$post['open_invitation'] = $this->getRandomString (8);
        $account = $this->model->where("account", $post['account'])->first();
        if (!empty($account)) {
            $result = ['status' => -4004, 'msg' => lang()->get('the user already exists. Please change it')];
            return $result;
        }
        if ($row = $this->repository->checkPassword($post['password'], $post['again_password'])) {
            return $row;
        }
        //添加新代理关系,$post['invita'] //前台提交的邀请码
//        if (isset($post['invita']) && !empty($post['invita'])) {
//            $data = $this->repository->checkInvitation($post['invita']);
//            if ($data < 0) {
//                $result = ['status' => -4004, 'msg' => lang()->get('invitation code error')];
//                return $result;
//            }
//            $post['parent_id'] = $data['account_identity']; //父级ID
//            $post['parent_path'] = !empty($data['parent_path']) ? $data['parent_path'] . ',' . $data['account_identity'] : $data['account_identity'];
//            $post['level'] = intval($data['level']) + 1;
//            //父级代理
//            $dataAgent['agent_identity'] = $data['account_identity'];
//            $dataAgent['agent_name'] = $data['account'];
//            //新代理父级
//            $newAgent['parent_id'] = $data['account_identity']; //父级ID
//            $newAgent['parent_path'] = !empty($data['parent_path']) ? $data['parent_path'] . ',' . $data['account_identity'] : $data['account_identity'];
//
//        } else {
            //为空默认父级代理为root
//            $root = $this->repository->getRoot();
//            if ($root < 0) {
//                $result = ['status' => -4004, 'msg' => lang()->get('root does not exist')];
//                return $result;
//            }
//            $post['parent_id'] = $root['account_identity']; //父级ID
//            $post['parent_path'] = $root['account_identity']; //父级路径
//            $post['level'] = intval($root['level']) + 1;  //等级
//            //父级代理
//            $dataAgent['agent_identity'] = $root['account_identity'];
//            $dataAgent['agent_name'] = $root['account'];
//            //新代理父级
//            $newAgent['parent_id'] = $root['account_identity']; //父级ID
//            $newAgent['parent_path'] = $root['account_identity']; //父级路径
//        }
        try {
            _beginTransaction();
            $accountData = [
                'identity' => UUID(),
                'account' => $post['account'],
            ];
            $res = $this->model->insert($accountData);
            if (!$res) {
                _rollBack();
                $result = ['status' => -4015, 'msg' => lang()->get('add fail')];
                return $result;
            }

            $res = $this->repository->addPassword($post['password'], $accountData['identity']);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -4113, 'msg' => lang()->get('passsword fail')];
                return $result;
            }
            $res = $this->repository->addAccountDetailed($post, $accountData['identity']);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -30101, 'msg' => lang()->get('add user fail')];
                return $result;
            }
            //新代理上下级关系信息
//            $dataAgent['account_identity'] = $accountData['identity'];
//            $dataAgent['account_name'] = $post['account'];
//
//            $res = $this->repository->addNewAgent($dataAgent);
//            if ($res < 0) {
//                _rollBack();
//                $result = ['status' => -30101, 'msg' => lang()->get('add agent parent error')];
//                return $result;
//            }
//            $account = lm('account_detailed', 'Commons')->where('account_identity', $accountData['identity'])->first();
            //新代理数据封装
//            $newAgent['agent_identity'] = $accountData['identity'];
//            $newAgent['agent_user'] = $post['account'];
//            $newAgent['invite'] = $account->id;
//            $newAgent['register_time'] = date('Y-m-d H:i:s', time());
//            //添加新代理到代理详情表
//            $res = $this->repository->addNewAgentDetail($newAgent);
//            if ($res < 0) {
//                _rollBack();
//                $result = ['status' => -30101, 'msg' => lang()->get('add new agent error')];
//                return $result;
//            }


            $result = $this->login($post['account'], $post['password']);

            if ($post['introduce_user']) {
                $res = $this->repository->addParent($post['introduce_user'], $accountData);
                if ($res < 0) {
                    _rollBack();
                    $result = ['status' => $res, 'msg' => lang()->get('empty introduce_user')];
                    lm("message", 'commons')->updateMessage('admin', $post['account'], '欢迎', '欢迎欢迎欢迎', 2);
                    return $result;
                }
            }
            _commit();

            return $result;
        } catch (\Exception $e) {
            $result = ['status' => -4005, 'msg' => lang()->get('registration failed. please re-registration'),'data'=>$e->getMessage()];
            return $result;
        }
    }

    /*
     * 随机生成
     */
    public function getRandomString($len, $chars = null) {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    /*
     * 用户开新户
     */
    public function newhouseholds($post) {
        if ($check = $this->repository->checkRegisterData($post)) {
            return $check;
        };
        $post['account'] = strtolower($post['account']);
        //$post['open_invitation'] = $this->getRandomString (8);
        $account = $this->model->where("account", $post['account'])->first();
        if (!empty($account)) {
            $result = ['status' => -4004, 'msg' => lang()->get('the user already exists. Please change it')];
            return $result;
        }
        if ($row = $this->repository->checkPassword($post['password'], $post['again_password'])) {
            return $row;
        }
        $parentinfo = lm('account_detailed', 'commons')->where('account_identity', $post['parent_identity'])->first();
        if (empty($parentinfo)) {
            return -500500;
        }
        $parentinfo = $parentinfo->toArray();
        $parentinfo['invitation'] = explode(',', $parentinfo['invitation']);
        $post['parent_id'] = $post['parent_identity'];
        if (empty($parentinfo['parent_path'][0])) {
            $post['parent_path'] = '2,' . $parentinfo['id'];
        } else {
            $post['parent_path'] = ($parentinfo['invitation'][0] + 1) . ',' . $parentinfo['id'];;
        }
        //unset($post['parent_identity']);
        try {
            _beginTransaction();
            $accountData = [
                'identity' => UUID(),
                'account' => $post['account'],
            ];
            $res = $this->model->insert($accountData);
            if (!$res) {
                _rollBack();
                $result = ['status' => -4015, 'msg' => lang()->get('add fail')];
                return $result;
            }
            $res = $this->repository->addPassword($post['password'], $accountData['identity']);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -4113, 'msg' => lang()->get('passsword fail')];
                return $result;
            }
            $res = $this->repository->addAccountDetailed($post, $accountData['identity']);
            $newaccountdetailed = lm('account_detailed', 'Commons')->where('account_identity', $accountData['identity'])->first();
            if (!empty($newaccountdetailed)) {
                $newaccountdetailed = $newaccountdetailed->toArray();
                lm('account_detailed', 'Commons')->where('account_identity', $accountData['identity'])->update(['open_invitation' => $newaccountdetailed['id']]);
            }
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -30101, 'msg' => lang()->get('add user fail')];
                return $result;
            }
            $result = ['status' => $res, 'msg' => lang()->get('empty introduce_user')];
            _commit();
            return $result;
        } catch (\Exception $e) {
            $result = ['status' => -4005, 'msg' => lang()->get('registration failed. please re-registration'),'data'=>$e->getMessage()];
            return $result;
        }
    }


    /*
     * 手机端直接开户  Anton Liu
     */
    public function directAccountOpening($post) {
        if ($check = $this->repository->checkRegisterData($post)) {
            return $check;
        };
        $post['account'] = strtolower($post['account']);
        //$post['open_invitation'] = $this->getRandomString (8);
        $account = $this->model->where("account", $post['account'])->first();
        if (!empty($account)) {
            $result = ['status' => -4004, 'msg' => lang()->get('the user already exists. Please change it')];
            return $result;
        }
        if ($row = $this->repository->checkPassword($post['password'], $post['again_password'])) {
            return $row;
        }
        //添加新代理关系,$post['invita'] //前台提交的邀请码
        if (isset($post['invita']) && !empty($post['invita'])) {
            $data = $this->repository->checkInvitation($post['invita']);
            if ($data < 0) {
                $result = ['status' => -4004, 'msg' => lang()->get('invitation code error')];
                return $result;
            }
            $post['parent_id'] = $data['account_identity']; //父级ID
            $post['parent_path'] = !empty($data['parent_path']) ? $data['parent_path'] . ',' . $data['account_identity'] : $data['account_identity'];
            $post['level'] = intval($data['level']) + 1;
            //父级代理
            $dataAgent['agent_identity'] = $data['account_identity'];
            $dataAgent['agent_name'] = $data['account'];
            //新代理父级
            $newAgent['parent_id'] = $data['account_identity']; //父级ID
            $newAgent['parent_path'] = !empty($data['parent_path']) ? $data['parent_path'] . ',' . $data['account_identity'] : $data['account_identity'];

        } else {
            //为空默认父级代理为root
            $root = $this->repository->getRoot();
            if ($root < 0) {
                $result = ['status' => -4004, 'msg' => lang()->get('root does not exist')];
                return $result;
            }
            $post['parent_id'] = $root['account_identity']; //父级ID
            $post['parent_path'] = $root['account_identity']; //父级路径
            $post['level'] = intval($root['level']) + 1;  //等级
            //父级代理
            $dataAgent['agent_identity'] = $root['account_identity'];
            $dataAgent['agent_name'] = $root['account'];
            //新代理父级
            $newAgent['parent_id'] = $root['account_identity']; //父级ID
            $newAgent['parent_path'] = $root['account_identity']; //父级路径
        }
        try {
            _beginTransaction();
            $accountData = [
                'identity' => UUID(),
                'account' => $post['account'],
            ];
            $res = $this->model->insert($accountData);
            if (!$res) {
                _rollBack();
                $result = ['status' => -4015, 'msg' => lang()->get('add fail')];
                return $result;
            }

            $res = $this->repository->addPassword($post['password'], $accountData['identity']);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -4113, 'msg' => lang()->get('passsword fail')];
                return $result;
            }
            $res = $this->repository->addAccountDetailed($post, $accountData['identity']);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -30101, 'msg' => lang()->get('add user fail')];
                return $result;
            }
            //新代理上下级关系信息
            $dataAgent['account_identity'] = $accountData['identity'];
            $dataAgent['account_name'] = $post['account'];

            $res = $this->repository->addNewAgent($dataAgent);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -30101, 'msg' => lang()->get('add agent parent error')];
                return $result;
            }
            $account = lm('account_detailed', 'Commons')->where('account_identity', $accountData['identity'])->first();
            //新代理数据封装
            $newAgent['agent_identity'] = $accountData['identity'];
            $newAgent['agent_user'] = $post['account'];
            $newAgent['invite'] = $account->id;
            $newAgent['register_time'] = date('Y-m-d H:i:s', time());
            //添加新代理到代理详情表
            $res = $this->repository->addNewAgentDetail($newAgent);
            if ($res < 0) {
                _rollBack();
                $result = ['status' => -30101, 'msg' => lang()->get('add new agent error')];
                return $result;
            }
            _commit();
            if ($res > 0) {
                $result = ['status' => 1, 'msg' => lang()->get('register success')];
                return $result;
            }
        } catch (\Exception $e) {
            $result = ['status' => -4005, 'msg' => lang()->get('registration failed. please re-registration'),'data'=>$e->getMessage()];
            return $result;
        }
    }

    /**
     * 检查登录是否过期
     *
     * @return array
     */
    public function checkEffectiveTime() {
        //重写此方法  by xmj
        define("OVERTIME", 1800);

        if (isCheckToken()) {

            $account = $this->getCurrentUser();
            // $identity = $account->account_identity;

            if ($account) {
                // $accountToken = lm('account_token', 'Commons')->where('account_identity', $identity)->first();
                // $effective_time = $accountToken->effective_time;
                // if ($effective_time > time() - OVERTIME) {
                //     lm('account_token', 'Commons')->where('account_identity', $identity)->update(['effective_time' => strtotime('now')]);
                // } else {
                //     $result = ['status' => -4008, 'msg' => lang()->get('user does not exist')];
                // }

                $result = $this->repository->checkEffectiveTime($account, OVERTIME);
            } else {
                $result = ['status' => -4001, 'msg' => lang()->get('user does not exist')];
            }
            return $result;
        }
        return ['status' => 1];
    }

    /**
     * 用户退出
     *
     * @param $accountIdentity
     * @return array
     */
    public function logout($accountIdentity) {
        $result = $this->repository->updateToken($accountIdentity);
        return $result;
    }

    /**
     * 销毁超过3天免费试玩玩家
     *
     * @return mixed
     */
    public function getAccountId() {
        $threebefore = date('Y-m-d H:i:s', time() - 3 * 24 * 3600);
        //$account = $this->model->join('account_detailed', 'account.identity', '=', 'account_detailed.account_identity')->where('account.status', 4)->get();
        $account = $this->model->select('logfile.account_identity')->join('logfile', 'account.identity', '=', 'logfile.account_identity')->where('account.status', 4)->where('logfile.add_time', '<', $threebefore)->groupBy('logfile.account_identity')->get();
        //echo '<pre>';print_r($account);echo '</pre>';
        $this->repository->destroyAccount($account->toArray());
        $num = $this->model->select('id')->count();
        return $num + 1;
    }

    /**
     * 注册免费试玩用户
     *
     * @return mixed
     */
    public function demoAccount()
    {
        $uname = isset($_POST['account']) ? $_POST['account'] : 'gust'.($this->getAccountId() + 1); //由ikeke修改于2019-01-08主要增加默认密码便于登录
        $uname = strtolower($uname);
        $num = $this->getAccountId();
        $name = 'gust' . ($num + 1);

        $account = $this->model->where("account", $uname)->first();

        if (!empty($account) || ($uname != $name))
        {
            $result = ['status' => -4022, 'msg' => '试玩账号有误'];
            return $result;
        }

        $pwd = isset($_POST['password']) ? $_POST['password'] : '123456'; //由ikeke修改于2019-01-08主要增加默认密码便于登录

        if (!$pwd)
        {
            return ['status' => 400, 'msg' => '没有密码'];
        }

        $result = $this->repository->demoAccount($uname, $pwd);
        $userInfo = lm('account_detailed', 'Commons')->join('account', 'account_detailed.account_identity', '=', 'account.identity')->where('account_detailed.token', $result['data'])->first();
        $account = $this->login($uname, $pwd);
        isset($result['data']) ? $result['data'] = $account['data'][0]['token'] : '';
        $_SESSION['uinfo'] = $userInfo->toArray();

        $result['data'] = $_SESSION;  //由ikeke修改于2019-01-08主要增加添加登录后的用户信息便于APP端调用

        return $result;
    }

    /**
     *
     * 判断是否已绑定银行卡
     * @return array
     * @throws \Exception
     */
    public function Iscard() {
        //获取用户ID并验证
        $uidentity = isset($_SESSION['uinfo']['identity']) ? $_SESSION['uinfo']['account_identity'] : '';
        if ($uidentity == '') {
            return ['data' => '', 'status' => -4020, 'msg' => lang()->get('Failed to obtain user information. Please refresh retry')];
        }
        $accountBank = lm('account_bank', 'Commons')->where('account_identity', $uidentity)->first();
        if ($accountBank) {
            $result = ['data' => '', 'status' => 200, 'msg' => ''];
        } else {
            $result = ['data' => '', 'status' => 1, 'msg' => lang()->get('Please bind the bank card')];
        }
        return $result;
    }

    /**
     * 获取用户信息
     *
     * @param $identity
     * @return array
     */
    public function getAccountDetailed($token) {
        $result = ['data' => '', '-4001', 'msg' => lang()->get('user does not exist')];
        $account = lm('account_detailed', 'Commons')->join('account', 'account_detailed.account_identity', '=', 'account.identity')->where('account_detailed.token', $token)->first();
        if ($account) {
            $result = ['data' => $account, 'status' => 1, 'msg' => lang()->get('success')];
        }
        return $result;
    }

    /**
     * 申请代理用户
     *
     * @param $data
     * @return int
     */
    public function applyAgent($data) {
//        try {
        $row = $this->repository->checkAgent($data['agent_user']);
        if ($row == 1) {
            return -4014;
        }
        $res = $this->repository->addAgentDetailed($data);
        return $res;
//        } catch (\Exception $e) {
        //            return -4015;
        //        }
    }

    /**
     * 代理人与用户关联
     *
     * @param $data
     * @return int
     */
    public function agentAccount($data) {
        try {
            lm('agent_child', 'Commons')->insert($data);
            return 1;
        } catch (\Exception $e) {
            return -4016;
        }
    }

    /**
     * 代理用户登录
     *
     * @param $data
     * @return array|int
     */
    public function agentLogin($data) {
        try {
            return $this->repository->agentLogin($data);
        } catch (\Exception $e) {
            return -4018;
        }
    }

    /**
     * 代理退出
     *
     * @param $accountIdentity
     * @return array
     */
    public function agentlogout($agentIdentity) {
        $result = $this->repository->updateAgentToken($agentIdentity);
        return $result;
    }

    /**
     * 检查代理用户token是否过期
     *
     * @param $token
     * @return array|int
     */
    public function agentTokenOverdue($token) {
        if (!$token) {
            return -4017;
        }
        if (isCheckToken()) {
            $agentDetailed = $this->repository->getAgentDetailed($token);
            if ($agentDetailed) {
                return $this->repository->agentTokenOverdue($agentDetailed);
            } else {
                return -4017;
            }
        }
        return 1;
    }

    /**
     * 记录登录区域
     */
    public function areaLog($ip, $accountIdentity) {
        try {
            $ipget = C()->get('IP');
            $location = $ipget->getlocation($ip);
            $address = $ipget->trunUtf8($location['country'] . $location['area']);
//            $url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
            //            $result = file_get_contents($url);
            //            $row = json_decode($result, true);
            $logFile = lm('logfile', 'Commons')->where('account_identity', $accountIdentity)->orderBy('id', 'desc')->first();
            lm('logfile', 'Commons')->where('id', $logFile->id)->update(['area' => $address]);
            return 1;
        } catch (\Exception $e) {
            return -4022;
        }
    }

    /**
     * 设置游戏分类
     *
     * @param $data
     * @return array
     */
    public function getSetOdds($data) {
        try {
            $result = [];
            foreach ($data as $key => $val) {
                $result = $this->repository->getResult($key, $val, $result);
            }
            return ['data' => $result, 'status' => 1];
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * 设置倍率获取需要数据格式
     *
     * @param $data
     * @return array
     */
    public function getNeedData($data) {
        $lang = $data['lang'];
        $item = $data['data'];
        $result = [];
        foreach ($item as $k => $v) {
            if ($v['type'] == 0) {
                $name = $this->getGameName($k);
                $v['lang'] = $lang[$k];
                $result[$name][] = $v;
            }
        }
        return $result;
    }

    /**
     * 获取设置倍率的游戏类
     *
     * @param $k
     * @return string
     */
    public function getGameName($k) {
        substr($k, 0, 5) == 'chain' ? $parent = 'chain' : '';
        substr($k, 0, 6) == 'dragon' ? $parent = 'dragon' : '';
        substr($k, 0, 8) == 'head_one' ? $parent = 'head_one' : '';
        substr($k, 0, 8) == 'head_two' ? $parent = 'head_two' : '';
        substr($k, 0, 10) == 'head_three' ? $parent = 'head_three' : '';
        substr($k, 0, 7) == 'poscode' ? $parent = 'poscode' : '';
        substr($k, 0, 5) == 'color' ? $parent = 'color' : '';
        substr($k, 0, 3) == 'mix' ? $parent = 'mix' : '';
        substr($k, 0, 4) == 'size' ? $parent = 'size' : '';
        substr($k, 0, 11) == 'specialCode' ? $parent = 'specialCode' : '';
        return $parent;
    }

}
