<?php
/**
 *------Create thems Controller------
 *------SCWPHP  Version 1.0.0------
 *------Dev Model Jions------
 *------Create Time 2017-06-08 10:07:19------
 */

namespace App\Api\Controller;

use App\Api\Model\Lottery_money;
use App\Api\Model\Lottery_money_log;

use Biz\Account\AccountManager;
use Biz\Common\Common;
use Biz\Game\GameList;
use System\Lang;
use App\Api\Model\AccountDetail;
use App\Api\Model\AccountNews;


class Account extends BaseController {
    private $accountManager;

    public function init() {
        $this->accountManager = new AccountManager();
    }

    /**
     * 验证用户资金密码
     */
    public function checkPayPass() {
        $payPass = $_POST['payPass'];
        $token = $_GET['token'] ?? '';
        if (empty($token)) {
            Render('5555', '-4010', lang('errors')->get('-4010'));
        }
        $status = \App\Api\Model\Account::checkPayPwd($token, $payPass);
        $data = new \stdClass();
        Render($data, $status);
    }

    /**
     * 用户登录
     */
    public function Login() {
        $result = $this->accountManager->login($_POST['account'], $_POST['password']);

        //$result = $this->accountManager->login('x0053', '123456');

        /*if ($result['status'] == 1) {
            $this->UserUpgrade();
        }*/
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 用户修改密码
     */
    public function resetPassword() {
        $result = $this -> accountManager -> savePassword($_POST);
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 用户修改支付密码
     */
    public function resetPayPassword() {
        $result = $this -> accountManager -> savePayPassword();
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 用户注册
     */
    public function enroll() {
        $account_name = $_POST['account'];
//        if (stripos($_POST['account_name'],'guest') === false){
////                var_dump($v['account_name']);
//            Render('',-4101);
//        }
        $result = $this->accountManager->register($_POST);
        if ($result['status'] == 1) {
            $settings = lm('settings', 'Commons')->first();
            $result['data']['0']['success_tip'] = $settings->success_tip;
        }

        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 直接开户
     */
    public function directAccount() {
        $result = $this->accountManager->directAccountOpening($_POST);
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * token获取用户详情
     */
    public function getAccount() {
        if ($_REQUEST['dbg'] == 1) dd($_SESSION);
        $checkToken = $this->accountManager->checkEffectiveTime();
        if ($checkToken['status'] != 1) {
            Render($checkToken['data'], $checkToken['status'], $checkToken['msg']);
        };
        $result = $this->accountManager->refreshToken();
        //删除不需要的字段
        unset($result['data']['token']);
        unset($result['data']['finance_cash']);
        unset($result['data']['parent_id']);
        unset($result['data']['parent_path']);
        unset($result['data']['hand_pass']);
        if (!empty($result)) {
            $find_name = lm('dc_user_grade', 'commons')->where('grade', $result['data']['grade'])->first();
            if (!empty($find_name)) {
                $res = $find_name->toArray();
                $result['data']['vname'] = $res['name'];

            }
        }
        $result['data']['qq'] = trim($result['data']['qq']);
        if (!$result['data']['img_url']) {
            $result['data']['img_url'] = $result['data']['img_id'] ? "/Public/themes/default/static/img/{$result['data']['img_url']}.png" : "/Public/themes/default/static/img/0.png";
        }
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 用户退出登录
     */
    public function Logout() {
        $account = $this->accountManager->getCurrentUser();

        if ($account) {
            $result = $this->accountManager->logout($account->account_identity);
            Render($result['data'], $result['status'], $result['msg']);
        } else {
            Render('', -1);
        }
    }

    /**
     * 试玩用户注册
     */
    public function Playtest() {
        $ip = GETIP();

        $time = lm('Setinfo', 'commons')->select('infocontent')->where('status', 1)->where('infotype', '2000')->first();
        $time = $time->toArray();
        // $limit_time = date ('Y-m-d H:i:s', strtotime ('-3day'));
        $limit_time = date('Y-m-d H:i:s', strtotime('-' . $time['infocontent'] . 'hour'));

        $res = lm('account_detailed', 'commons')->join('account', 'account.identity', 'account_detailed.account_identity')->where('account.status', 4)->where('register_ip', $ip)->where('register_time', '>', $limit_time)->first();
        if ($res) {
            Render('', -4025);
        }
        $result = $this->accountManager->demoAccount();
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 判断是否已绑定银行卡
     */
    public function Iscard() {
        $result = $this->accountManager->Iscard();
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 申请代理用户
     */
    public function applyAgent() {
        $result = $this->accountManager->applyAgent($_POST);
        Render('', $result, lang('errors')->get($result));
    }

    /**
     * 代理用户登录
     */
    public function agentLogin() {
        $result = $this->accountManager->agentLogin($_POST);
        if ($result < 0) {
            Render('', $result);
        } else {
            Render($result, 1, lang('errors')->get(1));
        }
    }

    /**
     * 代理用户token是否过期
     */
    public function agentTokenOverdue() {

        $token = isset($_GET['token']) ? $_GET['token'] : '';
        $result = $this->accountManager->agentTokenOverdue($token);
        if ($result < 0) {
            Render('', $result, lang('errors')->get($result));
        } else {
            Render($result, 1, lang('errors')->get(1));
        }
    }

    /**
     *登录添加登录区域日志
     */
    public function areaLog() {
        $result = $this->accountManager->areaLog($_GET['ip'], $_GET['accountIdentity']);
        if ($result == 1) {
            Render('', $result, '成功');
        } else {
            Render('', $result, '添加登录日志区域错误');
        }
    }

    /**
     * 获取用户信息
     */
    function getAccountInfo() {
        $data = array();
        $data = $_SESSION['uinfo'];
        $bankInfo = lm('account_bank', 'commons')->where('account_identity', $_SESSION['uinfo']['account_identity'])->first();
        if (empty($bankInfo)) {
            Render('', -40451);
        }
        $bankInfo = $bankInfo->toArray();
        $data['bank_name'] = $bankInfo['bank_name'];
        $data['bank_address'] = $bankInfo['bank_address'];
        $data['bank_number'] = $bankInfo['bank_number'];
        Render($data, 1);
    }

    /**
     * token获取用户详情
     */
    public function getAgent() {
        $checkToken = $this->accountManager->checkEffectiveTime();

        if ($checkToken['status'] != 1) {
            Render($checkToken['data'], $checkToken['status'], lang('commons')->get('user does login'));
        };

        $result = $this->accountManager->refreshToken();
        Render($result['data'], $result['status'], $result['msg']);
    }

    /**
     * 等级升级申请
     * @return [type] [description]
     */
    public function UserUpgrade(int $total_flow = 0) {

        $uinfo = $this->accountManager->getCurrentUser();
        if (!$uinfo) {
            return '-50003';
        }
        $result['data'] = $uinfo->toArray();
        if ($result['data']['grade'] == 0 || $result['data']['grade'] == -1) {
            return '-50019';
        }
        $res = lm('UserGrade', 'Api')->upgrade($result['data'], $total_flow);
        if ($res == 1) {
            return 1;
        } else {
            return $res;
        }

    }

    /**
     * 活动升级彩金公用接口
     * @return [type] [description]
     */
    public function Promotiongold() {
        $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : "";
        if (empty($id)) {
            Render('', "-50009");
        }
        $wherel['id'] = $id;
        $Promotiong = lm('lottery_money', 'Api')->where($wherel)->first();
        if (empty($Promotiong)) {
            Render('', "-50010");
        }

        $Promotiong = $Promotiong->toArray();
        if ($Promotiong['type'] == 'upgrade') {
            $this->rank($id);
        } elseif ($Promotiong['type'] == 'first_save') {
            $utype = $_REQUEST['per_key'];
            if (!$utype) {
                Render('', -50025);
            }
            $this->firstRecharge($id, $utype);
        }
    }

    //晋级彩金
    public function rank($id) {
        $uinfo = $this->accountManager->getCurrentUser();
        if (!$uinfo) {
            return '-50003';
        }
        $result['data'] = $uinfo->toArray();
        if ($result['data']['grade'] == 0 || $result['data']['grade'] == '-1') {
            return Render('', '-50035');
        }
        $res = lm('UserGrade', 'Api')->gold($result['data'], $id);
        if ($res == 1) {
            return Render('', 1);
        } else {
            return Render('', $res);
        }

    }

    protected function firstRecharge($active_id, $utype = '') {
        $uinfo = $this->accountManager->getCurrentUser();
        if (!$uinfo) {
            Render('', -50011);
        }
        $userinfo = $uinfo->toArray();
        //$userinfo = lm ('AccountDetail', 'Api')->where ('account_identity', $uinfo['account_identity'])->first ();
        $account = $userinfo['account'];
        $account_identity = $userinfo['account_identity'];
        $lm = new Lottery_money();
        $type = 'first_save';
        $data = $lm->where('id', $active_id)->first()->toArray();
        if (!$data)
            Render('', -50016);
        $money = 0;
        //todo:首充检查并返回金额
        $content = json_decode($data['conent'], 1);
        $ftype = $content['fr_type'];
        $f = \App\Api\Model\Account::chkFirstRecharge($account_identity, $active_id, $ftype);
        $order_id = $f->order_id;
        $activeName = Lottery_money::where('id', $active_id)->first(['name'])->name ?? '';
        $Lottery_log = new Lottery_money_log();
        //查询申请记录
        $where = [
            ['account_identity', $account_identity],
            ['order_id', $order_id],
            ['status', '<>', 2]
        ];
        //需要逻辑：查询当前用户当前订单号是否有参与当前活动
        $active = $Lottery_log->where($where)->first();
        if ($active) {
            Render('', -50034);
        }
        $money = $f->money;
        $ranges = json_decode($data['conent'], 1)['ranges'];
        $sel = (function ($param, $num, $type) {
            foreach ($param as $k => $v) {
                if ($v[5] == $type && $num >= $v[0])
                    return $v;
            }
            return [];
        })($ranges, $money, $utype);
        if (!$sel)
            Render('', -50016);//无活动数据
        $giftMoney = $money * ($sel[2] / 100);
        if ($giftMoney > (float)$sel[3])
            $giftMoney = $sel[3];
        $totalMoney = $giftMoney + $money;
        $rate = $sel[2];
        $frate = $sel[4];
        $needMoney = $totalMoney * $frate;
        $newremark = ['gift_money' => $giftMoney, 'money' => $money, 'needBettingMoney' => $needMoney, 'frate' => $sel[2] / 100, 'rate' => $sel[4]];
        $tpl = lang('money')->get('first');
        $grade = $sel[5];
        $newremark['selected'] = $grade;
        $detail = sprintf($tpl, $account, $activeName, $money, $rate, $giftMoney, $grade, $frate, $order_id);
        $newremark = json_encode($newremark);
        if (!$active) {
            {
                $data = [];
                $data['account_identity'] = $account_identity;
                $data['grade'] = $userinfo["grade"];
                $data['lottery_money_type'] = $type;
                $data['lottery_money_id'] = $active_id;
                $data['money'] = $giftMoney;
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['status'] = 0;
                $data['detail'] = $detail ?? '无';
                $data['account_name'] = $account;
                $data['lottery_money_name'] = $activeName;
                $data['flow_record'] = $newremark ?? '';
                $data['order_id'] = $order_id;
                $res = lm('lottery_money_log', 'Api')->insert($data);
            }
            if ($res) Render('', 1);
        }
        Render('', -30018);
    }

    public function analysis($str = '', $arr = array()) {
        if (empty($str)) {
            return -51055;
        }
        if (empty($arr)) {
            return -51055;
        }
        foreach ($arr as $key => $value) {
            $str = str_replace("#" . $key . "#", $value, $str);
        }

        return $str;
    }


    //申请vip
    public function ApplyVip() {
        $result = $this->accountManager->refreshToken();
        if ($result['status'] < 0) {
            Render('', "-50011");
        }
        if ($result['data']['grade'] > 0) {
            Render('', "-50028");
        }
        if ($result['data']['grade'] != 0) {
            Render('', "-50028");
        }

        //试玩账号 --2019/1/15 17/14 blues
        if (isset($result['data']['status']) && $result['data']['status'] == 4) {
            Render('', -4026);
        }
        $num = lm('User_vip', 'Api')->where('account_identity', $result['data']['account_identity'])->count();
        if ($num == 0) {
            $data['account_name'] = $result['data']['account'];
            $data['account_identity'] = $result['data']['account_identity'];
            $data['addtime'] = date('Y-m-d H:i:s');
            $data['status'] = 1;
            $res = lm('User_vip', 'Api')->insert($data);
            if ($res) {
                lm('AccountDetail', 'Api')->where('account_identity', $result['data']['account_identity'])->update(['grade' => -1]);
                Render('', '1');
            } else {
                Render('', "-50026");
            }
        } else {
            if ($result['data']['grade'] == 0) {
                lm('User_vip', 'Api')->where('account_identity', $result['data']['account_identity'])->update(['status' => 1]);
                lm('AccountDetail', 'Api')->where('account_identity', $result['data']['account_identity'])->update(['grade' => -1]);
                Render('', '1');
            } else {
                Render('', "-50036");
            }
        }


    }

    //开新用户
    public function households() {

        if (empty($_POST['account'])) {
            Render('', "-50060", '缺少用户名称');
        }
        if (empty($_POST['name'])) {
            Render('', "-50061", '缺少真实用户名称');
        }
        if (empty($_POST['password'])) {
            Render('', "-50062", '缺少密码');
        }
        if (empty($_POST['again_password'])) {
            Render('', "-50063", '缺少确定密码');
        }
        if ($_POST['password'] != $_POST['again_password']) {
            Render('', "-50064", '确定密码不一致');
        }
        if (empty($_POST['phone'])) {
            Render('', "-50065", '缺少手机号码');
        }
        $this->checkLogin();
        $uinfo = $this->accountManager->getCurrentUser();
        if (empty($uinfo->account_identity)) {
            Render('', "-50066", '用户未登录');
        }
        $_POST['parent_identity'] = $uinfo->account_identity;
        $result = $this->accountManager->newhouseholds($_POST);
        Render($result['data'], $result['status'], $result['msg']);
    }

    protected function checkLogin() {
        $checkToken = $this->accountManager->checkEffectiveTime();
        if ($checkToken['status'] != 1) {
            Render($checkToken['data'], $checkToken['status'], $checkToken['msg']);
        };
        $this->accountManager->refreshToken();
    }

    public function checkHandPass() {
        $hand_pass = $_REQUEST['hand_pass'];
        $this->checkLogin();
        $uinfo = $this->accountManager->getCurrentUser();
        $uuid = $uinfo->account_identity;
        if ($uuid) {
            $ret = lm('UserSetting', 'api')->getUserSetting($uuid);
            //dd($ret);
            if ($ret && isset($ret['hand_pass']) && $ret['hand_pass']) {
                if (!$ret['hand_lock'])
                    Render('' - 60002);//未开启手势密码
                if ($ret['hand_pass'] === md5($hand_pass))
                    Render('', 1);
                Render('', -60000);//手势密码不匹配
            } else
                Render('', -60001);//未设置手势密码
        }
        Render('', -51017);//用户不存在
    }

    public function getUserSetting() {
        $this->checkLogin();
        $uinfo = $this->accountManager->getCurrentUser();
        $uuid = $uinfo->account_identity;
        $ret = lm('UserSetting', 'api')->getUserSetting($uuid);
        if ($_REQUEST['devicetype'] === 'android' || $_REQUEST['devicetype'] === 'ios') {
            $ret['fav_info'] = json_decode($ret['fav_info'], 1) ?? [];
            $ret['cart_info'] = json_decode($ret['cart_info'], 1) ?? [];
        }
        Render($ret, 1);
    }

    public function setUserSetting() {
        $this->checkLogin();
        $uinfo = $this->accountManager->getCurrentUser();
        //if ($uinfo && $uinfo->account_identity)
        $uuid = $uinfo->account_identity;
        if (isset($_POST['hand_pass']) && $_POST['hand_pass'] != '') $data ['hand_pass'] = md5($_POST['hand_pass']);
        if (isset($_POST['hand_lock']) && $_POST['hand_lock'] != '') $data ['hand_lock'] = $_POST['hand_lock'];
        if (isset($_POST['sound']) && $_POST['sound'] != '') $data ['sound'] = $_POST['sound'];
        if (isset($_POST['shake_rand']) && $_POST['shake_rand'] != '') $data ['shake_rand'] = $_POST['shake_rand'];
        if (isset($_POST['prize_ani']) && $_POST['prize_ani'] != '') $data ['prize_ani'] = $_POST['prize_ani'];
        if (isset($_POST['prize_all']) && $_POST['prize_all'] != '') $data ['prize_all'] = $_POST['prize_all'];
        if (isset($_POST['win_games']) && $_POST['win_games'] != '') $data ['win_games'] = $_POST['win_games'];
        if (isset($_POST['prize_games']) && $_POST['prize_games'] != '') $data ['prize_games'] = $_POST['prize_games'];
        if (isset($_POST['fav_info']) && $_POST['fav_info'] != '') $data ['fav_info'] = ($_POST['fav_info']);
        if (isset($_POST['cart_info']) && $_POST['cart_info'] != '') $data ['cart_info'] = ($_POST['cart_info']);
        if (isset($_POST['device_state']) && $_POST['device_state'] != '') $data ['device_state'] = ($_POST['device_state']);
        if (isset($_POST['device_number']) && $_POST['device_number'] != '') $data ['device_number'] = ($_POST['device_number']);
        if ($data['prize_games'] == -1) $data['prize_games'] = '';
        $lm = lm('UserSetting', 'api');
        $favs = json_decode($data['fav_info'], 1);
        $favs = array_unique($favs);
        $data['fav_info'] = json_encode($favs);
        $ret = $lm->setUserSettings($uuid, $data);
        Render('', 1);
    }

    public function setUserSet() {
        $this->checkLogin();
        $uinfo = $this->accountManager->getCurrentUser();
        //if ($uinfo && $uinfo->account_identity)
        $uuid = $uinfo->account_identity;
        // $data ['hand_pass'] = md5 ($_POST['hand_pass']);
        // $data ['win_games'] = $_POST['win_games'];

        $data = array(
            'prize_all' => isset($_POST['prize_all']) ? 1 : 0,
            'win_games' => isset($_POST['win_games']) ? 1 : 0,
        );
        if (empty($data)) {
            return -909090;
        }
        $ret = lm('UserSetting', 'api')->where('account_identity', $uuid)->update($data);
        if ($ret == 1) {
            return Render('', 1);
        } else {
            return Render('', 0);
        }

    }

    public function setHeadImg() {
        //$imgUrl = $_REQUEST['imgUrl'];
        $imgId = $_REQUEST['imgId'] ?? 0;
        $accountMan = new AccountManager();
//        if ($_POST['dd'] == 1)
//            dd ($imgUrl);
//        if (!$imgUrl) {
//            $arr = json_decode (file_get_contents ('php://input'), 1);
//            if (isset($arr['imgUrl']) && $arr['imgUrl']) {
//                $imgUrl = $arr['imgUrl'];
//            }
//        }

        $ret = null;
        $imgUrl = "/Public/themes/default/static/img/{$imgId}.png";
        if ($imgUrl) $ret = $accountMan->chHeadImg($imgUrl, $imgId);
        if ($ret < 1) {
            Render('', $ret);
        }
        Render($ret, 1);
    }

    public function setDetail() {
        $phone = $_POST['phone'] ? strip_tags(trim($_POST['phone'])) : '';
        $qq = $_POST['qq'] ? strip_tags(trim($_POST['qq'])) : '';
        $email = $_POST['email'] ? strip_tags(trim($_POST['email'])) : '';
        $wechat = $_POST['wechat'] ? strip_tags(trim($_POST['wechat'])) : '';

        if (!$phone && !$qq && !$email && !$wechat) {
            Render('', -40256);//数据不能全为空
        }
        $data = [];
        if ($phone) {
            $data['phone'] = $phone;
        }
        if ($qq) {
            $data['qq'] = $qq;
        }
        if ($email) {
            $data['email'] = $email;
        }
        if ($wechat) {
            $data['wechat'] = $wechat;
        }
        $accountMan = new AccountManager();
        $uinfo = $accountMan->getCurrentUser();
        $uuid = $uinfo->account_identity ?? null;
        if (!$uuid) {
            Render('', -4001);//用户未找到
        }
        $ret = lm('AccountDetail', 'Api')->where('account_identity', $uuid)->update($data);
        if ($ret) {
            Render('', 1);
        } else {
            Render('', -40254);
        }
    }

    //获取当前用户安全等级
    public function safetygrade() {
        //if($_REQUEST['dbg']==1)dd($_SESSION);
        $checkToken = $this->accountManager->checkEffectiveTime();
        if ($checkToken['status'] != 1) {
            Render($checkToken['data'], $checkToken['status'], $checkToken['msg']);
        };
        $result = $this->accountManager->refreshToken();
        if (!empty($result)) {
            $bankstate = lm('account_bank', 'commons')->where('account_identity', $result['data']['account_identity'])->count();
            $paypasswordstate = lm('pay_password', 'commons')->where('account_identity', $result['data']['account_identity'])->count();
            if ($bankstate != 0 && $paypasswordstate != 0 && $result['data']['email'] != '' && $result['data']['qq'] != '') {
                $safetystate = '高';
            } elseif ($bankstate != 0 && $paypasswordstate != 0) {
                $safetystate = '中';
            } else {
                $safetystate = '低';
            }
            Render($safetystate, 1);
        } else {
            Render('', $result['status'], $result['msg']);
        }
    }

    //检查用户是否已注册
    public function isRegistered() {
        $an = $_REQUEST['account_name'];
        $ret = (new \App\Api\Model\Account())->where('account', $an)->exists();
        Render(null, $ret ? -40040 : 1);
    }

    /**
     *错误码列表接口
     */
    public function getErrLangs() {
        $lang = Lang('Errors', 'Api');
        $langs = $lang->getAll();
        $newLangs = [];
        foreach ($langs as $k => $v) {
            $k = trim($k, 'error');
            $newLangs["$k"] = $v;
        }
        Render($newLangs, 1);
    }

    /**
     * 玩法语言包总列表接口
     */
    public function getGameLangs() {
        if (C()->get('cache')->has('totalGameLangs')) {
            $data = C()->get('cache')->get('totalGameLangs');
//            C()->get('cache')->delete('totalGameLangs');
        } else {
            $cls = new Common();
            $data = $cls->getGameLangs();
            C()->get('cache')->set('totalGameLangs', $data, 86400 * 7);
        }
        Render($data, 1);
    }

    /**
     * 修改用户基本信息
     *
     * @access public
     * @return array JsonString
     */
    public function updateUserInfo() {
        $code = 0;
        $msg = lang('Common','Api') -> get('error');
        try{
            $accountDetailClass = new AccountDetail();
            // 修改用户基本信息
            $result = $accountDetailClass -> updateUserInfo();
            if ($result) {
                $code = 1;
                $msg = lang('Index','Api') -> get('success');

                Render($result, $code, $msg);
            } else {
                Render([], $code, $msg);
            }
        } catch (Exception $e) {
            Render([], $code, $msg);
        }
    }

    /**
     * 用户消息
     *
     * @access public
     * @return array JsonString
     */
    public function userNews() {
        $code = 0;
        $msg = lang('Common','Api') -> get('error');
        try{
            $accountDetailClass = new AccountNews();
            // 获取用户消息
            $result = $accountDetailClass -> userNews();
            $code = 1;
            $msg = lang('Index','Api') -> get('success');

            Render($result, $code, $msg);
        } catch (Exception $e) {
            Render([], $code, $msg);
        }
    }

    /**
     * 上传用户头像
     *
     * @access public
     * @return array JsonString
     */
    public function updateHeader() {
        $code = 0;
        $msg = lang('Common','Api') -> get('error');
        try{
            $accountDetailClass = new AccountDetail();
            // 修改用户基本信息
            $result = $accountDetailClass -> updateHeader();
            $code = 1;
            $msg = lang('Index', 'Api')->get('success');

            Render($result, $code, $msg);
        } catch (Exception $e) {
            Render([], $code, $msg);
        }
    }
}
