<?php
namespace Biz\Money;

/**
 * 资金操作相关类
 */
class MoneyHandle
{
    /**
     * 资金明细表
     * @var string
     */
    private $money_table = 'fund_detailed';
    /**
     * 用户详情表
     * @var string
     */
    private $account_detailed = 'account_detailed';
    /**
     * 用户银行绑定记录表
     * @var string
     */
    private $bank_table = 'account_bank';
    /**
     * 用户表
     * @var string
     */
    private $account_table = 'account';
    /**
     * 交易密码表
     * @var string
     */
    private $pay_password = 'pay_password';
    /**
     * 代理信息表
     * @var string
     */
    private $agent = 'agent_detailed';
    /**
     * 代理资金表
     * @var string
     */
    private $agent_money = 'agent_money';
    /**
     * 佣金记录表
     * @var string
     */
    private $money_reward = 'money_reward';
    /**
     * 资金明细表
     * @var string
     */
    private $money_details = 'money_details';
    /**
     * 中奖记录表
     * @var string
     */
    private $prize_table = 'money_prize';
    /**
     * 提现记录表
     * @var string
     */
    private $money_take = 'money_take';
    /**
     * 充值记录
     * @var string
     */
    private $money_recharge = 'money_recharge';
    /**
     * 反水记录表
     * @var string
     */
    private $money_back = 'money_back';
    /**
     * 回水记录表
     * @var string
     */
    private $money_return = 'money_return';
    /**
     * 投注记录影子表
     * @var string
     */
    private $money_buy = 'money_buy';

    private $account_list = 'AccountList';

    private $sixMoney_buy='SixMoney_buy';

    private $sixPrize_table='sixMoney_prize';
    //private $game;
    public function init()
    {

    }

    /**
     * 绑定银行卡
     * @param  [type] $account_identity 用户id
     * @param  [type] $bank_address     开户银行地址
     * @param  [type] $bank_name        银行名称
     * @param  [type] $bank_no          银行卡号
     * @param  [type] $bank_user        银行卡用户
     * @param  [type] $pay_pwd          支付密码
     * @param  [type] $sure_pwd         确认密码
     * @return [type]                   [description]
     */
    public function bind_bank($account_identity, $bank_address, $bank_name, $bank_no, $bank_user, $pay_pwd, $sure_pwd,$bank_code)
    {
        //判断重要参数是否为空

        //var_dump($account_identity,$bank_address,$bank_name,$bank_no,$bank_user,$pay_pwd,$sure_pwd);

        //return $bank_address;

        if (empty($account_identity)) {
            //Render('null','-2001',lang()->get('user not login'));
            return '-2001';
        }

        if (empty($bank_address)) {

            //Render('null','-2002',lang()->get('bank_address missing'));
            // return $bank_address;
            return '-2002';
        }
        if (empty($bank_name)) {

            //Render('null','-2003',lang()->get('bank_name missing'));
            return '-2003';
        }
        /*if(empty($bank_code)){
            return '-2003';
        }*/
        if (empty($bank_no)) {

            //Render('null','-2004',lang()->get('bank_number missing'));
            return '-2004';
        }
        if (empty($bank_user)) {

            //Render('null','-2005',lang()->get('bank_user missing'));
            return '-2005';
        }
        if (empty($pay_pwd) || empty($sure_pwd)) {

            //Render('null','-2006',lang()->get('password missing'));
            return '-2006';
        }
        //判断两次交易密码是否一致
        if ($pay_pwd != $sure_pwd) {

            //Render('null','-2007',lang()->get('two password not equal'));
            return '-2007';
        }

        $this->setPayPwd($account_identity, $pay_pwd, $sure_pwd);
        //验证用户是否已经绑定了该银行卡
        $res = lm($this->bank_table, 'commons')->where(['account_identity' => $account_identity])->first();

        //return $res;
        if ($res) {
            return '-2033';
        }
        //检测该银行卡是否已经绑定
        $res2 = lm($this->bank_table, 'commons')->where('bank_number', $bank_no)->first();
        if ($res2) {
            return '-2136';
        }

        //检测开户人姓名是否与用户真实姓名相同
        $userName = lm($this->account_detailed, 'commons')->select('name')->where('account_identity', $account_identity)->first();
        if ($userName) {
            if (!empty($userName->name) && $userName->name != $bank_user) {
                return '-3311';
            }
        } else {
            return '-4001';
        }

        //为用户绑定银行卡

        $data = array(
            'identity' => UUID(),
            'account_identity' => $account_identity,
            'bank_address' => $bank_address,
            'bank_name' => $bank_name,
            'account_name' => $bank_user,
            'bank_number' => $bank_no,
            'band_time' => date('Y-m-d H:i:s', time()),
            'bank_code' => $bank_code
        );

        $res = lm($this->bank_table, 'commons')->insert($data);
        $resd = lm($this->account_detailed, 'commons')->select('name')->where('account_identity', $account_identity)->first();

        if (empty($resd->name)) {
            lm($this->account_detailed, 'commons')->where('account_identity', $account_identity)->update(['name' => $bank_user]);
        }
        if ($res) {
            //Render('null','1',lang()->get('success'));
            return 1;
        } else {
            //Render('null','-2009',lang()->get('fail'));
            return '-2009';
        }
    }
    /**
     * 设置默认银行卡或者解绑银行卡
     * @param  [type] $account_identity 用户id
     * @param  [type] $bank_no          银行卡号
     * @param  [type] $pay_pwd          交易密码
     * @param  [type] $type             类型 1.设置默认银行卡，-1，解除该银行卡绑定
     * @return [type]                   [description]
     */
    public function bankStatus($account_identity, $bank_no, $pay_pwd, $type)
    {
        if ($type == 1) {
            $type = 2;
        }
        if (!$this->verifyPayPwd($account_identity, $pay_pwd)) {
            return '-2020';
        }
        $res = lm($this->bank_table, 'commons')->where(['account_identity' => $account_identity, 'bank_number' => $bank_no])->update(['status' => $type]);
        if ($res) {
            return '1';
        } else {
            return '-2016';
        }
    }

    /**
     * 设置交易密码
     * @param [type] $account_identity 用户id
     * @param [type] $pay_pwd             密码
     * @param [type] $sure_pwd         确认密码
     */
    public function setPayPwd($account_identity, $pay_pwd, $sure_pwd)
    {
        //判断重要参数是否为空
        if (empty($account_identity)) {
            //Render('null','-2010',lang()->get('user not login'));
            return '-2001';
        }
        if (empty($pay_pwd) || empty($sure_pwd)) {
            //Render('null','-2011',lang()->get('password missing'));
            return '-2006';
        }
        //判断两次交易密码是否一致
        if ($pay_pwd != $sure_pwd) {
            //Render('null','-2012',lang()->get('two password not equal'));
            return '-2007';
        }
        //检查用户是否已经设置密码
        $judge = lm($this->pay_password, 'commons')->where(['account_identity' => $account_identity])->first();

        //为用户设置交易密码
        $pwd = GenPassword($pay_pwd);
        $data = array(
            'identity' => UUID(),
            'pay_password' => $pwd['password'],
            'encryption' => $pwd['encryption'],
            'account_identity' => $account_identity,
        );
        if ($judge) {
            $res = lm($this->pay_password, 'commons')->where(['account_identity' => $account_identity])->update($data);
        } else {
            $res = lm($this->pay_password, 'commons')->insert($data);
        }
        if ($res) {
            //Render('null','1',lang()->get('success'));
            return '1';
        } else {
            //Render('null','-2013',lang()->get('fail'));
            return '-2013';
        }
    }

    /**
     * 检测是否设置交易密码
     * @param [type] $account_identity 用户id
     */
    public function checkPayPwd($account_identity='')
    {
        //$account_identity = isset($_SESSION['uinfo']['account_identity']) ? $_SESSION['uinfo']['account_identity'] : '';

        if (empty($account_identity)) {
            Render('', '-2001', lang()->get('user not login'));
        }
        //检查用户是否已经设置密码
        $judge = lm($this->pay_password, 'commons')->where(['account_identity' => $account_identity])->first();
        if ($judge) {
            return '1';
        } else {
            return '-1024';
        }
    }

    /**
     * 投注追号
     * @param  [type] $user_id 用户id
     * @param  [type] $money   投注追号金额
     * @param  array  $extra   其他数据
     * @return [type]          [description]
     */
    public function betting($user_id, $money, $extra = array())
    {
        if($money<=0)return -3311;
        //检测用户资金
        $check = $this->check($user_id, $money);
        if ($check < 0) {
            return $check;
        }
        //订单号
        $order_id = isset($extra['order_id']) ? $extra['order_id'] : '';
        if (empty($order_id)) {
            return -2116;
        }
        //投注了类型
        $type = isset($extra['money_type']) ? $extra['money_type'] : '';
        if (empty($type)) {
            return -2117;
        }
        //游戏期号
        $game_no = isset($extra['game_no']) ? $extra['game_no'] : '';
        if (empty($game_no)) {
            return -2119;
        }
        //游戏名
        $game_name = isset($extra['type_name']) ? $extra['type_name'] : '';
        if (empty($game_name)) {
            return -2118;
        }
        //投注号码
        $codes = isset($extra['codes']) ? $extra['codes'] : '';
        if (empty($codes)) {
            return -2122;
        }
        //反水金额
        $back_money = isset($extra['back_money']) ? $extra['back_money'] : '';
        //反水比例
        $back = isset($extra['back']) ? $extra['back'] : '';
        /*//获取购买号码
        $codes = $this->getCodes($order_id, $game_name);*/
        _beginTransaction();
        //获取用户信息
        $account = $this->getAccount($user_id);
        //投注影子表数据加入
        $data = array(
            'info_identity' => $extra['identity'],
            'account_name' => $account['account_name'],
            'account_identity' => $user_id,
            'order_id' => $order_id,
            'game_name' => $game_name,
            'game_no' => $game_no,
            'codes' => $codes,
            'money' => $money,
            'get_money' => -$money,
            'status' => $type,
            'money_time' => date('Y-m-d H:i:s', time()),
            'member_type' => $account['status'],
        );

        $this->money_buy = ($game_name=='sixlottery' || $game_name=='sfsixlottery')?'SixMoney_buy':$this->money_buy;
        ($game_name=='sixlottery' || $game_name=='sfsixlottery')?($data['game_identity'] = $extra['gameid']):null;

        $res = lm($this->money_buy, 'Commons')->insert($data);

        if (!$res) {
            _rollBack();
            return -2120;
        }
        //反水
        if ($back_money != 0) {
            $judge = $this->back_money($user_id, $back_money, $game_name, $order_id, $back,$extra['identity']);
            if ($judge < 0) {
                return $judge;
            }
        }
        $game = new \Biz\Game\GameQuery;
        //获取游戏信息
        $gameName = $game->getGameInfo($extra['type_name']);
        if (!is_array($gameName)) {
            return $gameName;
        }
        //$gameName = isset($extra['type_name']) ? $extra['type_name'] : '';
        $res = $this->insertMoney($user_id, $money, $order_id, $type, $gameName['name'], $game_no);
        if ($res < 0) {
            _rollBack();
        }
        _commit();
        return $res;
    }


    /**
     * 六合投注追号
     * @param  [type] $user_id 用户id
     * @param  [type] $money   投注追号金额
     * @param  array  $extra   其他数据
     * @return [type]          [description]
     */
    public function sixBetting($user_id, $money, $extra = array())
    {
        //检测用户资金
        $check = $this->check($user_id, $money);
        if ($check < 0) {
            return $check;
        }
        //订单号
        $order_id = isset($extra['order_id']) ? $extra['order_id'] : '';
        if (empty($order_id)) {
            return -2116;
        }
        //投注了类型
        $type = isset($extra['money_type']) ? $extra['money_type'] : '';
        if (empty($type)) {
            return -2117;
        }
        //游戏期号
        $game_no = isset($extra['game_no']) ? $extra['game_no'] : '';
        if (empty($game_no)) {
            return -2119;
        }
        //游戏名
        $game_name = isset($extra['type_name']) ? $extra['type_name'] : '';
        if (empty($game_name)) {
            return -2118;
        }
        //投注号码
        $codes = isset($extra['codes']) ? $extra['codes'] : '';
        if (empty($codes)) {
            return -2122;
        }
        //反水金额
        $back_money = isset($extra['back_money']) ? $extra['back_money'] : '';
        //反水比例
        $back = isset($extra['back']) ? $extra['back'] : '';
        /*//获取购买号码
        $codes = $this->getCodes($order_id, $game_name);*/
        _beginTransaction();
        //获取用户信息
        $account = $this->getAccount($user_id);
        //投注影子表数据加入
        $data = array(
            'info_identity' => $extra['identity'],
            'account_name' => $account['account_name'],
            'account_identity' => $user_id,
            'order_id' => $order_id,
            'game_name' => $game_name,
            'game_no' => $game_no,
            'codes' => $codes,
            'money' => $money,
            'get_money' => -$money,
            'status' => $type,
            'money_time' => date('Y-m-d H:i:s', time()),
            'member_type' => $account['status'],
        );

        $res = lm($this->sixMoney_buy, 'Commons')->insert($data);

        if (!$res) {
            _rollBack();
            return -2120;
        }
        //反水
        if ($back_money != 0) {
            $judge = $this->back_money($user_id, $back_money, $game_name, $order_id, $back,$extra['identity']);
            if ($judge < 0) {
                return $judge;
            }
        }
        $game = new \Biz\Game\GameQuery;
        //获取游戏信息
        $gameName = $game->getGameInfo($extra['type_name']);
        if (!is_array($gameName)) {
            return $gameName;
        }
        //$gameName = isset($extra['type_name']) ? $extra['type_name'] : '';
        $res = $this->insertMoney($user_id, $money, $order_id, $type, $gameName['name'], $game_no);
        if ($res < 0) {
            _rollBack();
        }
        _commit();
        return $res;
    }

    /**
     * 中奖
     */
    public function prize($user_id, $money, $game, $buy_id, $prize)
    {
        //生成订单id
        $order_id = OrderID();
        //生成信息id
        $info_id = UUID();
        //更新投注影子表
        //获取投注金额
        $buy_money = lm($this->money_buy, 'Commons')->where('order_id', $buy_id)->first();

        if ($buy_money) {
            $game_no = $buy_money->game_no;
            //阻止重新开奖的派彩
            /*if ($buy_money->prize_money > 0) {
            return 1;
            }*/
            $accountname = $buy_money->account_name;
            $buy_money = $buy_money->money;

        } else {
            return -2121;
        }
        //获取真实投注金额(除去反水金额的消费金额)
        //$rel_money = $this->getMoney($buy_id);

        //更新投注影子表
        $get_money = $money - $buy_money;
        $rest = lm($this->money_buy, 'Commons')
            ->where('order_id', $buy_id)
            ->update(['get_money' => $get_money, 'prize_money' => $money, 'game_status' => 1, 'prize' => $prize]);
        if (!$rest) {
            return -2120;
        }
        if (lm($this->prize_table, 'Commons')->where('buy_identity', $buy_id)->first()) {
            return 1;
        }
        //将中奖插入中奖记录
        $data = array(
            'game_name' => $game['table_name'],
            'buy_identity' => $buy_id,
            'account_name' => $accountname,
            'account_identity' => $user_id,
            'order_id' => $order_id,
            'info_identity' => $info_id,
            'money' => $money,
            'money_time' => date('Y-m-d H:i:s', time()),
        );
        $res = lm($this->prize_table, 'Commons')->insert($data);
        if ($res) {
            $type = 4;
            /* lm("message",'commons')->updateMessage('admin',$accountname,'中奖提示','恭喜中奖，您在'.lang()->get($game['table_name']).'中的第'.$game_no.'期中，中奖：'.$money.'元',2);*/
            return $this->insertMoney($user_id, $money, $order_id, $type, $game['name'], $game_no);
        } else {
            return '-2113';
        }
    }

    /***六合派奖
     * @param $user_id 用户id
     * @param $accountName 用户名
     * @param $buy_money 投注金额
     * @param $prize_money 派奖金额
     * * @param $buy_id 购买id
     * @param $gameInfo 游戏信息的数组 包含游戏名，游戏期号
     * @param $prize_code 中奖号码
     *
     */
    public function sixPrize($user_id, $prize_money, $game, $buy_id, $prize_code,$buy_money,$gameInfo,$userInfo)
    {
        //生成订单id
        $order_id = OrderID();
        //生成信息id
        $info_id = UUID();
        $game_no = $gameInfo['no'];
        //更新投注影子表
		//更新投注影子表
		//computeTime('更新影子表');

        $get_money = $prize_money - $buy_money;
       $rest = lm($this->sixMoney_buy, 'Commons')
            ->where('order_id', $buy_id)
            ->update(['get_money' => $get_money, 'prize_money' => $prize_money, 'game_status' => 1, 'prize' => $prize_code]);
        if (!$rest) {
            return -2120;
        }
      // computeTime('更新money_buy');
        //将中奖插入中奖记录
        $data = array(
            'game_name' => $gameInfo['en_name'],
            'buy_identity' => $buy_id,
            'account_name' => $userInfo['account'],
            'account_identity' => $user_id,
            'order_id' => $order_id,
            'info_identity' => $info_id,
            'money' => $prize_money,
            'money_time' => date('Y-m-d H:i:s', time()),
        );
		$res = lm($this->sixPrize_table, 'Commons')->insert($data);

       //computeTime('添加money_prize');
        if ($res) {
            $type = 4;
            $userInfo['account_name']=$userInfo['account'];
            return $this->insertMoney($userInfo['identity'], $prize_money, $order_id, $type, lang()->get($gameInfo['en_name']), $game_no,$userInfo,$gameInfo['en_name']);
        } else {
            return '-2113';
        }
    }
    /**
     * 重新开奖撤销中奖记录
     * @param  [type] $buy_id 购买id
     * @return [type]         [description]
     */
    public function reprize($buy_id, $user_id, $nowMoney)
    {
        $res = lm($this->money_buy, 'commons')->where('order_id', $buy_id)->first();
        if ($res) {
            $data = [
                'game_status' => 0,
                'prize_money' => 0,
                'get_money' => -$res->money,
                'prize' => '{}',
            ];
        } else {
            return -2051;
        }

        // $account = $this->getAccount($res->account_identity);
        $res1 = lm($this->money_buy, 'commons')->where('order_id', $buy_id)->update($data);
        //成功则更新中奖记录表的状态
        if ($res1) {
            $prize = lm($this->prize_table, 'commons')->where('buy_identity', $buy_id)->first();
            $res2 = lm($this->prize_table, 'commons')->where('buy_identity', $buy_id)->delete();
            //更新成功修改资金详情记录
            if ($res2) {
                $trade_id = OrderID();
                return $this->insertDetail($user_id, $trade_id, $res->prize_money, $nowMoney, 9, $buy_id, lang()->get($res->game_name), $res->game_no);
            }

        }
        return -2049;
    }

    /**
     * 重新开奖中奖用户退还中奖金额，扣除余额到0
     * @param  [type] $gameNo 游戏期号
     * @param  [type] $gameName 游戏名
     * @return [type]         [description]
     */
    public function returnPrizeMoney($gameNo, $gameName)
    {
        $gameName = strtolower($gameName);
        if($gameName=='sixlottery' || $gameName=='sfsixlottery'){
            $this->money_buy = 'SixMoney_buy';
            $this->prize_table = 'SixMoney_prize';
        }

        $isPrize = $this->isPrize($gameNo, $gameName);
        if ($isPrize < 0) {
            return $isPrize;
        }

        $res = lm($this->money_buy, 'commons')->select('account_identity', 'prize_money', 'order_id')->where('game_name', $gameName)->where('game_no', $gameNo)->where('prize_money', '>', '0')->get();
        if ($res) {
            _beginTransaction();
            $res = $res->toArray();
            try {
                foreach ($res as $key => $value) {
                    $userCash = lm($this->account_detailed, 'commons')->select('cash', 'available_cash')->where('account_identity', $value['account_identity'])->first();
                    /*if ($value['prize_money'] > $userCash->available_cash) {
                    $available_cash = 0;
                    $cash = $userCash->cash - $userCash->available_cash;
                    } else {*/
                    $available_cash = $userCash->available_cash - $value['prize_money'];
                    $cash = $userCash->cash - $value['prize_money'];
                    //}
                    $result = $this->updateAccountMoney($value['account_identity'], $value['prize_money'], 2, $available_cash);

                    if ($result < 0) {
                        _rollBack();
                    }
                    $this->reprize($value['order_id'], $value['account_identity'], $available_cash);
                }
                lm($gameName . '_buy', 'commons')->where('no', $gameNo)->update(array('status' => 0));

                //_commit();
            } catch (PDOException $e) {
                _rollBack();
            }
        }
        return 1;
    }

    public function updateStatus($gameno, $gamename)
    {
        lm('money_buy', 'commons')->where('game_no', $gameno)->where('game_name', $gamename)->where('game_status', 0)->update(array('game_status' => 2));
        lm($gamename . '_buy', 'commons')->where('no', $gameno)->where('status', 0)->update(array('status' => 2));
        return 1;
    }

    /**
     * 重新开奖中奖用户退还中奖金额，扣除余额到0
     * @param  [type] $gameno 游戏期号
     * @param  [type] $gamename 游戏名
     * @return [type]         [description]
     */
    public function isPrize($gameno, $gamename)
    {
        $status = lm($gamename, 'commons')->select('status')->where('info_no', $gameno)->first();
        if ($status) {
            if ($status['status'] == 2) {
                return 1;
            }
            return -3307;
        }
        return -3221;
    }

    /**
     * 充值
     * @param $user_id 用户id
     * @param $money 充值金额
     * @param array $extra 其他参数数组
     */
    public function addMoney($user_id, $money, $type)
    {
        $type = '在线充值';
        //获取用户信息
        $account = $this->getAccount($user_id);
        //生成订单id
        $order_id = OrderID();
        //充值后金额
        $nowMoney = $account['available_cash'] + $money;
        //充值记录
        $data = array(
            'info_identity' => UUID(),
            'order_id' => $order_id,
            'apply_time' => date('Y-m-d H:i:s', time()),
            'money' => $money,
            'account_name' => $account['account_name'],
            'account_identity' => $user_id,
            'status' => 3,
            'recharge_type' => $type,
            'money_cash' => $nowMoney,
        );
        $res = lm($this->money_recharge, 'Commons')->insert($data);
        if ($res) {
            return $order_id;
        }
    }
    /**
     * 确认充值
     * @param  [type] $order_id 充值订单
     * @return [type]           [description]
     */
    public function suerAddMoney($order_id, $status = 3)
    {
        $charge = lm($this->money_recharge, 'commons')->where('order_id', $order_id)->where('status', 3)->first();
        if (!$charge) {
            return -2047;
        }
        if ($status < 0) {
            $res = lm($this->money_recharge, 'commons')->where('order_id', $order_id)->update(['status' => 2]);
            return 1;
        }
        $res = lm($this->money_recharge, 'commons')->where('order_id', $order_id)
            ->update(['status' => 1, 'complete_time' => date('Y-m-d H:i:s', time())]);
        if ($res) {
            return $this->insertMoney($charge->account_identity, $charge->money, $order_id, 6);
        }
        return -2048;
    }
    /**
     * 提现
     * @param  array  $user_id 用户id
     * @param  array  $money 提现金额
     * @param  array  $pay_pwd 交易密码
     * @return [type]       [description]
     */
    public function takeMoney($user_id, $money, $pwd, $bank_no)
    {

        if ($money < 100) {
            return -2112;
        }
        $account = $this->getAccount($user_id);
        //检测用户资金
        $check = $this->check($user_id, $money);
        if ($check < 0) {
            return $check;
        }

        //验证交易密码
        if (!$this->verifyPayPwd($user_id, $pwd)) {
            return -2020;
        }

        //获取用户银行卡信息
        $bank_info = $this->getBankInfo($user_id, $bank_no);
        //生成订单id
        $order_id = OrderID();
        //提现后金额
        $nowMoney = $account['available_cash'] - $money;
        $nowCash = $account['cash'] - $money;
        //插入提现申请记录
        $data = array(
            'info_identity' => UUID(),
            'order_id' => $order_id,
            'account_identity' => $user_id,
            'account_name' => $account['account_name'],
            'money' => $money,
            'apply_time' => date('Y-m-d H:i:s', time()),
            'apply_date' => date('Y-m-d', time()),
            'bank_info' => $bank_info['bank_name'],
            'bank_no' => $bank_no,
            'bank_address' => $bank_info['bank_address'],
            'bank_user' => $bank_info['account_name'],
            'money_cash' => $nowMoney,
        );

        //验证三分钟内不能重复提交提现申请
        $txTime = lm($this->money_take, 'commons')->select('apply_time')->where('account_identity', $user_id)->orderBy('apply_time', 'desc')->first();
        $applyTime = date('Y-m-d H:i:s', time() - 300);
        if ($txTime) {
            if (!empty($txTime->apply_time) && $txTime->apply_time >= $applyTime) {
                return '-2051';
            }
        }

        _beginTransaction();
        try {
            $res = lm($this->money_take, 'Commons')->insert($data);
            if ($res) {
                $res1 = $this->updateAccountMoney($user_id, $money, 2, $nowMoney, $account['available_cash']);
                if ($res1 < 0) {
                    throw new PDOException($res1);
                    //return $res1;
                }
                $resdetail = $this->insertDetail($user_id, '', $money, $nowMoney, 15);
                //return $this->insertMoney($user_id, $money, $order_id, 5);
                //return 1;
                if ($resdetail < 0) {
                    throw new PDOException($resdetail);
                }
            } else {
                throw new PDOException(-2113);
                //return -2113;
            }
            _commit();
            return 1;
        } catch (PDOException $e) {
            _rollBack();
            return $e->getMessage();
        }
    }

    /**
     * 撤单
     * @param  [type] $user_id  用户id
     * @param  [type] $order_id 订单id
     * @param  [type] $money     操作金额
     * @return [type]           [description]
     */
    public function cancel($user_id, $order_id)
    {
        //获取订单信息
        $orderInfo = lm($this->money_buy, 'commons')->where('order_id', $order_id)->where('status', '<', 4)->first();
        if (!$orderInfo) {
            $this->money_buy = 'sixMoney_buy';
            $orderInfo = lm($this->money_buy, 'commons')->where('order_id', $order_id)->where('status', '<', 4)->first();
            if (!$orderInfo)return -2125;
        }
        $money = $this->getMoney($order_id);
        $account = $this->getAccount($user_id);
        $nowMoney = $account['available_cash'] + $money;
//        $now_allMoney = $account['cash'] + $money;
        //修改状态
        $desc = sprintf(lang()->get('user cancel'), lang()->get($orderInfo->game_name), $orderInfo->game_no, $account['account_name'], $order_id);
        // $desc = lang()->get($orderInfo->game_name) . '期号为：' . $orderInfo->game_no . ',' . $account['account_name'] . '撤销了订单,单号：' . $order_id;
        $res1 = lm($this->money_buy, 'Commons')->where('order_id', $order_id)->update(['status' => 4, 'get_money' => 0]);
        //更新用户金额
        $res = $this->updateAccountMoney($user_id, $money, 1, $nowMoney, $account['available_cash']);
        if (!$res) {
            return '-2034';
        }
        if (!$res1) {
            return -2034;
        }
//        //更新反水表
        $res2 = lm($this->money_back, 'Commons')->where('buy_identity', $order_id)->update(['status' => 3]);
        $res = $this->insertCancelData($account, $desc, $money, $nowMoney, 3, $order_id);
        if (!$res) {
            return '-2034';
        }
        return '1';
    }

    /**
     * 验证账户金额是否足够
     * @param  [type] $money          操作所需金额
     * @param  [type] $available_cash 账户可用金额
     * @return [type]                 [description]
     */
    public function verifyMoney($money, $available_cash)
    {
        if ($available_cash >= $money) {
            return true;

        } else {
            return false;
        }
    }
    /**
     * 验证账户金额是否异常
     * @param  [type] $available_cash 账户可用金额
     * @param  [type] $cash           账户总金额
     * @param  [type] $frozen_cash    冻结金额
     * @return [type]                 true or FALSE
     */
    public function verifyAccount($available_cash, $cash, $frozen_cash)
    {
        if ($cash == $available_cash + $frozen_cash) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 检测用户账户情况
     * @param  [type] $account_identity 用户id
     * @param  [type] $money            操作金额
     * @return [type]                   [description]
     */
    public function check($account_identity, $money)
    {
        //获取用户信息;
        $account = $this->getAccount($account_identity);
        //检测用户信息
        if (!$this->verifyAccount($account['available_cash'], $account['cash'], $account['frozen_cash'])) {
            return -2021;
        }
        //检测用户资金
        if (!$this->verifyMoney($money, $account['available_cash'])) {
            return -2022;
        }
        return 1;
    }
    /**
     * 验证交易密码
     * @param  [type] $account_identity 用户唯一id
     * @param  [type] $pwd              密码
     * @return [type]                   true or false
     */
    public function verifyPayPwd($account_identity, $pwd)
    {
        $enc = lm($this->pay_password, 'commons')->select('encryption')->where('account_identity', $account_identity)->first();
        if ($enc) {
            $enc = $enc->toArray();
        } else {
            return false;
        }
        $VerPwd = md5(md5($enc["encryption"] . $pwd));
        //dump($VerPwd);
        $res = lm($this->pay_password, 'commons')->where(['account_identity' => $account_identity, 'pay_password' => $VerPwd])->first();
        if ($res) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 获取用户信息
     * @param  [type] $account_identity 用户唯一id
     * @return [type]                   用户资金相关数组
     */
    public function getAccount($account_identity)
    {
//        $data = array();
        /*$res = lm($this->account_detailed, 'Commons')
        ->select('available_cash', 'cash', 'frozen_cash', 'account_identity')
        ->where('account_identity', $account_identity)
        ->sharedLock()
        ->first();
        if ($res) {
        $res = $res->toArray();
        } else {
        return -4001;
        }
        $res2 = lm($this->account_table, 'commons')->select('account', 'status')->where('identity', $account_identity)->first()->toArray();
        $data = $res;
        $data['account_name'] = $res2['account'];
        $data['status'] = $res2['status'];*/
        $res = lm($this->account_list, 'Commons')
            ->select('account as account_name', 'account_status as status', 'available_cash', 'cash', 'frozen_cash', 'account_identity')
            ->where('identity', $account_identity)->first();
//        print_r(lm($this->account_list, 'Commons')->getsql());
        if ($res) {
           return $res->toArray();

        } else {
            return -4001;
        }
    }
    /**
     * 根据代理id获取代理信息
     * @param  [string] $agent_id 代理id
     * @return [array]          代理相关信息
     */
    public function getAgent($agent_id)
    {
        $res = lm($this->agent, 'Commons')
            ->select('agent_user', 'agent_identity', 'take_money')
            ->where('agent_identity', $agent_id)
            ->first();
        if ($res) {
            $agent = $res->toArray();
        } else {
            return '-2001';
        }
        return $agent;
    }
    /**
     * 通过审核
     * @param  [type] $identity 信息id
     * @return [type]           [description]
     */
    public function pass_take($identity)
    {
        # code...
    }
    /**
     * 完成提现
     * @param  [type] $identity 信息id
     * @return [type]           [description]
     */
    public function give_take($identity)
    {

    }
    /**
     * 更新数据
     * @param  [type] $gameName [description]
     * @param  [type] $moeny    [description]
     * @param  [type] $code     [description]
     * @return [type]           [description]
     */
    public function codeMoneyBack($gameName, $order_id, $code)
    {
        $res1 = lm("money_buy", 'commons')->where('order_id', $order_id)->update(['codes' => json_encode($code)]);
        if ($res1) {
            $res2 = lm($gameName . "_buy", 'commons')->where('order_id', $order_id)->update(['codes' => json_encode($code)]);
            if ($res2) {
                return 1;
            }
        }
        return -2016;
    }
    /**
     * 反水记录增加
     * @param  string $account_identity 用户id
     * @param  [type] $money            金额
     * @param  string $game_name        游戏名
     * @param  string $buy_id           购买记录id
     * @param  [type] $ratio            反水比例
     * @return [type]                   [description]
     */
    public function back_money($account_identity, $money, $game_name, $buy_id, $ratio,$buy_identity='')
    {
        if(empty($buy_identity)){
            $buy_identity=UUID();
        }
        //获取用户信息
        $account = $this->getAccount($account_identity);
        //获取游戏信息
        $game = new \Biz\Game\GameQuery;
        $game_info = $game->getGameInfo($game_name);
        //查询是否反水
        $check = lm($this->money_back, 'Commons')->where('buy_identity', $buy_id)->first();
        if ($check) {
            return -2113;
        }
        //生成订单id
        $order_id = OrderID();
        //插入反水信息
        $data = array(
            'info_identity' => $buy_identity,
            'order_id' => $order_id,
            'account_name' => $account['account_name'],
            'account_identity' => $account_identity,
            'game_name' => $game_info['table_name'],
            'game_id' => $game_info['identity'],
            'buy_identity' => $buy_id,
            'money' => $money,
            'ratio' => $ratio,
            'processing_time' => date('Y-m-d H:i:s', time()),
        );
        $res = lm($this->money_back, 'Commons')->insert($data);

        if ($res) {
            return 1;
        } else {
            return -2113;
        }
    }
    /**
     * 确认反水
     * @param  [type] $order_id 购买订单
     * @return [type]           [description]
     */
    public function suer_back($order_id)
    {
        $info = lm($this->money_back, 'Commons')->where('buy_identity', $order_id)->where('status', '<>', 3)->first();
        if (!$info) {
            return -2113;
        }
        //$account=$this->getAccount($info->account_identity);
        $res = lm($this->money_back, 'Commons')->where('buy_identity', $order_id)->update(['status' => 3]);
        if ($res) {
            return $this->insertMoney($info->account_identity, $info->money, $info->order_id, 7);
        }
        return -2113;
    }
    /**
     * 回水操作
     * @param  string $account_identity 用户id
     * @param  string $money            金额
     * @param  string $ratio            回水比例
     * @param  string $total_money      亏损总金额
     * @return [type]                   [description]
     */
    public function return_money($account_identity, $money, $ratio, $total_money)
    {
        //获取用户信息
        $account = $this->getAccount($account_identity);
        //生成订单id
        $order_id = OrderID();
        //加入回水记录
        $data = array(
            'info_identity' => UUID(),
            'order_id' => $order_id,
            'account_name' => $account['account_name'],
            'account_identity' => $account_identity,
            'money' => $money,
            'ratio' => $ratio,
            'total_money' => $total_money,
            'processing_time' => date('Y-m-d H:i:s', time()),
        );
        $res = lm($this->money_return, 'Commons')->insert($data);
        if ($res) {
            return $this->insertMoney($account_identity, $money, $order_id, 8);
        } else {
            return -2113;
        }
    }
    /**
     * 管理员扣款
     * @param  [type] $account_identity 用户id
     * @param  [type] $money            金额
     * @return [type]                   [description]
     */
    public function cut_money($account_identity, $money)
    {
        //检测用户资金
        $check = $this->check($account_identity, $money);
        if ($check < 0) {
            return $check;
        }
        //生成订单id
        $order_id = OrderID();
        return $this->insertMoney($account_identity, $money, $order_id, 9);
    }
    /**
     * 资金记录修改
     * @param  string $account_identity 用户id
     * @param  string $money            金额
     * @param  订单号 $order_id         订单号
     * @param  int    $type             交易类型
     * @return [type]                   [description]
     */
    public function insertMoney($account_identity, $money, $order_id, $type, $game_name = '', $game_no = '',$account=array(),$game_eName='')
    {
        // lm($this->account_detailed, 'Commons')->beginTransaction();
        //_beginTransaction();
        //获取用户信息
        if(!is_array($account)){
            return -3219;
        }
        if(is_array($account)&&count($account)<1){
            $account = $this->getAccount($account_identity);
        }
       //computeTime('获取用户信息');
        if ($type == 4) {
            lm("message", 'commons')->updateMessage('admin', $account['account_name'], '中奖提示', '恭喜你中奖，您在' . $game_name . '中的第' . $game_no . '期中，中奖：' . $money . '元', 2);
        }
        //获取money_type
        $m_type = $this->getMtype($type);
       //computeTime('获取money_type');
        //总资金记录表
        if ($m_type == 1) {
            $nowMoney = $account['available_cash'] + $money;
//            $nowCash = $account['cash'] + $money;
        } else {
            $nowMoney = $account['available_cash'] - $money;
//            $nowCash = $account['cash'] - $money;
        }
        //更新用户余额
        if($game_eName='sixlottery' || $gameName=='sfsixlottery'){
            $res2 = $this->updateAccountSixMoney($account_identity, $money, $m_type, $nowMoney, $account['available_cash']);
        }else{
            $res2 = $this->updateAccountMoney($account_identity, $money, $m_type, $nowMoney, $account['available_cash']);
        }


      // computeTime('更新用户余额结束' . var_export($res2, 1));
        if ($res2 > 0) {
                if (empty($game_name)) {
                    $res3 = $this->insertDetail($account_identity, $order_id, $money, $nowMoney, $type);
                } else {
                    $res3 = $this->insertDetail($account_identity, $order_id, $money, $nowMoney, $type, $order_id, $game_name, $game_no,$account);
                }
           //computeTime('添加详细' . $res3);
            if ($res3 > 0) {
                //_commit();
                return 1;
            } else {
                //_rollBack();
                return $res3;
            }
        } else {
            //_rollBack();
            return $res2;
        }
       //computeTime('插入资金详情结束');
    }
    /**
     * 获取描述信息
     * @param  string $account_name 用户名
     * @param  string $money        金额
     * @param  string $order_id     订单号
     * @param  int     $type         操作类型
     * @return [type]               [description]
     */
    public function getDesc($account_name, $money, $order_id, $type, $game_name = '', $game_no = '')
    {
        // return ;
        switch ($type) {
            case 1:
                return sprintf(lang()->get('user betting'), $game_name, $game_no, $account_name, $money, $order_id);
                break;
            case 2:
                return sprintf(lang()->get('user append'), $game_name, $game_no, $account_name, $money, $order_id);
                break;
            case 3:
                return sprintf(lang()->get('user cancel'), $game_name, $game_no, $account_name, $order_id);
                break;
            case 4:
                return sprintf(lang()->get('user prize'), $game_name, $game_no, $account_name, $money, $order_id);
                break;
            case 5:
                return sprintf(lang()->get('user take money'), $account_name, $money, $order_id);
                break;
            case 6:

                return sprintf(lang()->get('user charge money'), $account_name, $money, $order_id);
                break;
            case 7:
                return sprintf(lang()->get('user back money'), $account_name, $money, $order_id);
                break;
            case 8:
                return sprintf(lang()->get('user return money'), $account_name, $money, $order_id);
                break;
            case 9:
                return sprintf(lang()->get('cancel prize'), $game_name, $game_no, $account_name, $money, $order_id);
                break;
            case 10:
                return sprintf(lang()->get('user empty money'), $account_name, $money, $order_id);
                break;
            case 11:
                return sprintf(lang()->get('user cut money'), $account_name, $money, $order_id);
                break;
            case 15:
                return sprintf(lang()->get('frozen money'), $account_name, $money, $order_id);
                break;
            default:
                return '';
                break;
        }
    }
    /**
     * 获取状态
     * @param  [type] $type 操作类型
     * @return [type]       [description]
     */
    public function getStatus($type)
    {
        $arr = array(
            '1' => '投注',
            '2' => '追号',
            '3' => '撤单',
            '4' => '派奖',
            '5' => '审核中',
            '6' => '待支付',
            '7' => '成功',
            '8' => '成功',
            '9' => '扣款',
            '10' => '佣金提成',
        );
        return $arr[$type];

    }
    /**
     * 返回money_type
     * @param  [type] $type 类型
     * @return [type]       [description]
     */
    public function getMtype($type)
    {
        $arr = array(
            '1' => 2,
            '2' => 2,
            '3' => 1,
            '4' => 1,
            '5' => 2,
            '6' => 1,
            '7' => 1,
            '8' => 1,
            '9' => 2,
            '10' => 1,
            '11' => 2,
            '15' => 2,
        );
        return $arr[$type];
    }
    /**
     * 获取用户绑定银行卡信息
     * @param  [type] $account_identity 用户唯一id
     * @param  [type] $bank_no          银行卡号
     * @return [type]                   [description]
     */
    public function getBankInfo($account_identity, $bank_no)
    {
        $res = lm($this->bank_table, 'Commons')
            ->select('bank_number', 'account_name', 'bank_address', 'bank_name')
            ->where(['account_identity' => $account_identity, 'bank_number' => $bank_no])
            ->first();
        if ($res) {
            $data = $res->toArray();
        } else {
            return -2114;
        }
        return $data;
    }
    /**
     * 根据英文游戏名及订单号获取用户投注号码
     * @param  [type] $order_id  订单号
     * @param  [type] $game_name 游戏英文名
     * @return [type]            购买号码
     */
    public function getCodes($order_id, $game_name)
    {
        $table = $game_name . '_buy';
        $res = lm($table, 'Commons')->select('codes')->where('order_id', $order_id)->first();
        return $res->codes;
    }
    /**
     * 根据投注订单查询实际消费金额
     * @param  [type] $order_id 投注订单
     * @return string           实际消费金额
     */
    public function getMoney($order_id)
    {
        //获取投注金额
        $money = lm($this->money_details, 'Commons')->where('trade_id', $order_id)->first();
        if ($money) {
            $money = $money->money;
        } else {
            return -2115;
        }
        return $money;
    }
    /**
     * 更新用户金额
     * @param  [type] $money 操作金额
     * @param  [type] $nowCash  做类型
     * @param  [type]  $last_money 操作后金额
     * @param  [type] $Cash  当前余额
     * @return [type]           [description]
     */
    public function updateAccountMoney($account_identity, $money, $type, $last_money, $cash = '')
    {
        //更新用户余额
       /* // computeTime('更新用户余额开始');
        if (!empty($cash)) {
            $res=$this->checkWater($account_identity,$cash);
            if($res<0){
                return $res;
            }
        }*/
       // computeTime('验证用户资金结束');

        $res=S('DB')->select("select update_money('".$account_identity."',".$money.",".$type.")");
        return 1;
        /*if ($type == 1) {
            $res3 = lm($this->account_detailed, 'Commons')->where('account_identity', $account_identity)->where('available_cash', '<', $last_money)->increment('available_cash', $money);
            $res4 = lm($this->account_detailed, 'Commons')->where('account_identity', $account_identity)->where('cash', '<', $last_money)->increment('cash', $money);
        } else {
            $res3 = lm($this->account_detailed, 'Commons')->where('account_identity', $account_identity)->where('available_cash', '>', $last_money)->decrement('available_cash', $money);
            $res4 = lm($this->account_detailed, 'Commons')->where('account_identity', $account_identity)->where('cash', '>', $last_money)->decrement('cash', $money);
		}*/
		//print_r(array($type,$account_identity,$money,$last_money,$cash));

        /*if ($res) {
            return 1;
        } else {
            return -2113;
        }*/
    }

    function updateAccountSixMoney($account_identity, $money, $type, $last_money='', $cash = ''){

        //更新用户余额
        /*if (!empty($cash)) {
             $res=$this->checkWater($account_identity,$cash);
            if($res<0){
                return $res;
            }
        }*/

        $res=S('DB')->select("select update_money('".$account_identity."',".$money.",".$type.")");
        return 1;
    }
    //
    /**
     * 检测资金流水情况
     * @param $account_identity
     * @param $cash
     */
    public function checkWater($account_identity, $NowCash)
    {
        //查询最后一条资金余额
        $last_data = lm($this->money_details, 'commons')->where('account_identity', $account_identity)->orderBy('id', 'desc')->first();
        if (!$last_data) {
            return -2113;
        }
        $last_data = $last_data->toArray();
        if ($last_data['money_cash'] != $NowCash) {
            return -2255;
        }
        return 1;
    }
    /**
     * 插入资金详情
     * @param  [type] $user_id    用户id
     * @param  [type] $trade_id   交易id
     * @param  [type] $money      交易金额
     * @param  [type] $nowMoney   剩余金额
     * @param  [type] $type       交易类型的数字表示
     * @return [type]             [description]
     */
    public function insertDetail($user_id, $trade_id, $money, $nowMoney, $type, $buy_id = '', $gamename = '', $gameNo = '',$account=array())
    {
        if(!is_array($account)){
            return -3219;
        }
        if(is_array($account)&&count($account)<1){
			//computeTime('getAccount');
            $account = $this->getAccount($user_id);
		}
		//computeTime('getMtype');

        //获取money_type
        $m_type = $this->getMtype($type);
        if (empty($trade_id)) {
            $trade_id = OrderID();
        }
        if (empty($buy_id)) {
            $trade_desc = $this->getDesc($account['account_name'], $money, $trade_id, $type);
        } else {
            $trade_desc = $this->getDesc($account['account_name'], $money, $buy_id, $type, $gamename, $gameNo);
        }
        $data2 = array(
            'info_identity' => UUID(),
            'trade_id' => $trade_id,
            'account_name' => $account['account_name'],
            'account_identity' => $user_id,
            'money' => $money,
            'money_time' => date('Y-m-d H:i:s', time()),
            'money_type' => $m_type,
            'money_cash' => $nowMoney,
            //'status' => $status,
            'trade_type' => $type,
            'trade_desc' => $trade_desc,
        );

        $res3 = lm($this->money_details, 'commons')->insert($data2);
        if ($res3) {
            return 1;
        }
        return -2049;
    }
    //测单记录插入
    public function insertCancelData($account, $desc, $money, $nowMoney, $type, $out_id)
    {
        $insert_Data = array(
            'info_identity' => UUID(),
            'trade_id' => OrderID(),
            'account_name' => $account['account_name'],
            'account_identity' => $account['account_identity'],
            'money' => $money,
            'money_time' => date('Y-m-d H:i:s'),
            'money_type' => 1,
            'money_cash' => $nowMoney,
            'trade_type' => $type,
            'trade_desc' => $desc,
            'out_order_id' => $out_id,
        );
        $res3 = lm($this->money_details, 'commons')->insert($insert_Data);
        if ($res3) {
            return 1;
        }
        return -2049;

    }

    /**
     * 绑定银行卡,新增2018-10-26，绑定银行卡时不需要交易密码
     * @param  [type] $account_identity 用户id
     * @param  [type] $bank_address     开户银行地址
     * @param  [type] $bank_name        银行名称
     * @param  [type] $bank_no          银行卡号
     * @param  [type] $bank_user        银行卡用户
     * @return [type]                   [description]
     */
    public function bindBank($account_identity, $bank_address, $bank_name, $bank_no, $bank_user)
    {
        //判断重要参数是否为空
        if (empty($account_identity)) {
            return '-2001';
        }
        /*if (empty($bank_address)) {

            return '-2002';
        }*/
        if (empty($bank_name)) {

            return '-2003';
        }
        if (empty($bank_no)) {

            return '-2004';
        }
        if (empty($bank_user)) {

            return '-2005';
        }

        //验证用户是否已经绑定了该银行卡
        $res = lm($this->bank_table, 'commons')->where(['account_identity' => $account_identity])->first();

        if ($res) {
            return '-2033';
        }
        //检测该银行卡是否已经绑定
        $res2 = lm($this->bank_table, 'commons')->where('bank_number', $bank_no)->first();
        if ($res2) {
            return '-2136';
        }

        //检测开户人姓名是否与用户真实姓名相同
        $userName = lm($this->account_detailed, 'commons')->select('name')->where('account_identity', $account_identity)->first();
        if ($userName) {
            if (!empty($userName->name) && $userName->name != $bank_user) {
                return '-3311';
            }
        } else {
            return '-4001';
        }

        //为用户绑定银行卡

        $data = array(
            'identity' => UUID(),
            'account_identity' => $account_identity,
            'bank_address' => $bank_address,
            'bank_name' => $bank_name,
            'account_name' => $bank_user,
            'bank_number' => $bank_no,
            'band_time' => date('Y-m-d H:i:s', time()),
        );

        $res = lm($this->bank_table, 'commons')->insert($data);
        $resd = lm($this->account_detailed, 'commons')->select('name')->where('account_identity', $account_identity)->first();

        if (empty($resd->name)) {
            lm($this->account_detailed, 'commons')->where('account_identity', $account_identity)->update(['name' => $bank_user]);
        }
        if ($res) {
            return 1;
        } else {
            return '-2009';
        }
    }
}
