<?php
/**
 *------Create thems Model------
 *------SCWPHP  Version 1.0.0------
 *------Dev Model Jions------
 *------Create Time 2017-06-12 05:08:18------
 */
namespace App\Api\Model;

use \System\Model;
use Biz\Account\AccountManager;

class MoneyBuy extends Model {

    protected $table = 'money_buy';

    //晋级流水统计
    function getstreamAmount($params=array(),$startime='',$endtime='')
    {

        if (empty($params['account_identity'])) {
            return -51005;
        }
        $gradeinfo = lm('UserGrade', 'Api')->select('name', 'rule', 'rule_details')->where('grade', '=', 0)->first();
        if (empty($gradeinfo)) {
            return -5002;
        }
        $gradeinfo = $gradeinfo->toArray();
        $gradeinfo['rule_details'] = explode(',', $gradeinfo['rule_details']);
        $bet = lm('MoneyBuy', 'Api')->where('account_identity', $params['account_identity'])->where('status', '<', 4)->where('game_status', '>', 0);
        $uservip = lm('User_vip', 'Api')->select('audittime')->where('account_identity', $params['account_identity'])->first();
        if ($gradeinfo['rule_details'][0] == 'year') {
            $startime = date('Y-01-01', time()) . ' 00:00:00';
            $endtime = date('Y-12-31', time()) . ' 23:59:59';
            $bet = $bet->where('money_time', '>=', $startime)->where('money_time', '<=', $endtime);
        } elseif ($gradeinfo['rule_details'][0] == 'month') {
            $startime = date('Y-m-01', strtotime(date('Y', time()) . '-' . (date('m', time()) - 1) . '-01')) . ' 00:00:00';
            $endtime = date('Y-m-d', strtotime("$startime +1 month -1 day")) . ' 23:59:59';
            $bet = $bet->where('money_time', '>=', $startime)->where('money_time', '<=', $endtime);
        } elseif ($gradeinfo['rule_details'][0] == 'week') {
            $now_day = date('W', time()) - 1;
            $sunday_str = time() - $now_day * 60 * 60 * 24;
            $sunday = date('Y-m-d 00:00:00', $sunday_str);
            $strday_str = time() + (6 - $now_day) * 60 * 60 * 24;
            $strday = date('Y-m-d 23:59:59', $strday_str);
            $bet = $bet->where('money_time', '>=', $sunday)->where('money_time', '<=', $strday);
        } elseif ($gradeinfo['rule_details'][0] == 'day') {
            $firstday = date('Y-m-d 00:00:00', strtotime("-" . $gradeinfo['rule_details'][3] . " day"));
            $bet = $bet->where('money_time', '>=', $firstday)->where('money_time', '<=', date('Y-m-d 23:59:59', strtotime('-1 day')));
        } elseif ($gradeinfo['rule_details'][0] == 'ymd') {
            $firstday = $gradeinfo['rule_details'][3] . ' 00:00:00';
            $bet = $bet->where('money_time', '>=', $firstday);
        }

        if(!empty($uservip)){
        		$bet = $uservip->audittime?$bet->where ('money_time', '>=', $uservip->audittime):$bet;
        }
        $bet=$startime?$bet->where ('money_time', '>=', $startime):$bet;
        $bet=$endtime?$bet->where ('money_time', '<', $endtime):$bet;
        $bet = $bet->sum('money');
        return $bet;
    }

    /**
     * 单式投注记录
     *
     * @access public
     * @return String
     */
    public function singleBetRecord()
    {
        // 获取用户信息
        $accountManagerClass = new AccountManager;
        $userInfo = $accountManagerClass -> getCurrentUser();
        if (empty($userInfo['identity'])) {
            Render([], '2001', lang('Common','Api') -> get('user does login'));
        }
        // 用户ID
        $moneyBuySpxWhere['account_identity'] = $userInfo['identity'];
        // 时间区间
        $startTime = isset($_POST['startTime'])? $_POST['startTime'] : '1900-01-01 00:00:00';
        $endTime = isset($_POST['endTime'])? $_POST['endTime'] : '3000-12-12 00:00:00';
        $moneyBuySpxBetween = ['money_time' => [$startTime, $endTime]];
        $moneyBuySpxMdl = lm('money_buy_simplex', "commons");
        // 获取订单记录
        $moneyBuySpxSlt = ['batch_id'];
        $getMoneyBuySpx = $moneyBuySpxMdl -> moneyBuySimplex($moneyBuySpxSlt, $moneyBuySpxWhere, $moneyBuySpxBetween, '', '', 1);
        // 获取全部订单id
        $moneyBuyMthOr = [];
        $allBatchId = array_unique($getMoneyBuySpx, SORT_REGULAR);
        if (!$allBatchId) {
            // 获取记录总数
            $result['total'] = 0;
            $result['list'] = [];
            // 总页数计算
            $result['countPage'] = 1;
            $result['currentPage'] = 1;

            return $result;
        }
        foreach ($allBatchId as $key => $value) {
            $moneyBuyMthOr[0][$key][0] = 'batch_id';
            $moneyBuyMthOr[0][$key][1] = $value['batch_id'];
        }
        $moneyBuyMthWhere['bet_type'] = 1;
        // 输赢
        if (!empty($_POST['result']) && $_POST['result'] == 1) {
            $moneyBuyMthOr[1][0][0] = 'result';
            $moneyBuyMthOr[1][0][1] = 1;
            $moneyBuyMthOr[1][1][0] = 'result';
            $moneyBuyMthOr[1][1][1] = 3;
            $moneyBuyMthOr[1][2][0] = 'result';
            $moneyBuyMthOr[1][2][1] = 2;
        } elseif (!empty($_POST['result']) && $_POST['result'] == 2) {
            $moneyBuyMthOr[1][0][0] = 'result';
            $moneyBuyMthOr[1][0][1] = -1;
            $moneyBuyMthOr[1][1][0] = 'result';
            $moneyBuyMthOr[1][1][1] = 4;
        } elseif ($_POST['result'] === '0') {
            $moneyBuyMthOr[1][0][0] = 'result';
            $moneyBuyMthOr[1][0][1] = 0;
        }
        // 当前页
        $currentPage = isset($_POST['currentPage']) ? $_POST['currentPage'] : "1";
        // 分页大小
        $pageSize = isset($_POST['pageSize']) ? $_POST['pageSize'] : "10";
        // 起始查询位置
        $begin = ($currentPage - 1) * $pageSize;
        // 获取注单
        $moneyBuyMthMdl = lm('Money_buy_match', "commons");
        $moneyBuyMthSlt = ['status', 'bet_money', 'matchResult', 'result', 'home_team',  'batch_id', 'guest_team', 'condition', 'ctime', 'odds', 'odds_name', 'match_id', 'money_buy_match.game_code', 'money_buy_match.odds_code'];
        $getMoneyBuyMth = $moneyBuyMthMdl -> moneyBuyMatch($moneyBuyMthSlt, $moneyBuyMthWhere, $moneyBuyMthOr, $begin, $pageSize);
        $allCount = $moneyBuyMthMdl -> moneyBuyMatchTotal($moneyBuyMthWhere, $moneyBuyMthOr);
        // 获取可加注所需要的查询条件
        $commonFunction = C() -> get('commonFunction');
        $stOddsWheres = [];
        foreach ($getMoneyBuyMth as $key => $value) {
            $match_id = $value -> match_id;
            $odds_code = $value -> odds_code;
            $gameType = $value -> game_code;
            $where = [
                'match_id' => $match_id,
                'odds_code' => $odds_code,
            ];
            // 判断是否重复
            if (!$commonFunction -> judgeEqual($where, $stOddsWheres[$gameType])) {
                $stOddsWheres[$gameType][] = $where;
            }
        }
        // 查询数据下所有可加注的游戏
        $stOddsModel = lm('stOdds','commons');
        $stOddsSelect = ['match_id', 'odds_code'];
        $getSstOdds = [];
        // 循环查询每个运动的可加注游戏  注：由于查询不同表所以必须循环查询
        foreach ($stOddsWheres as $key => $value) {
            if ($value) {
                $getSstOdds[$key] = $stOddsModel -> stOdds($stOddsSelect, $value, $key);
            }
        }
        // 循环添加玩法和判断玩法是否可加注
        foreach ($getMoneyBuyMth as $key => $value) {
            $getMoneyBuyMth[$key]->willMoney = $value->bet_money * $value->odds;
            if ($value->result) {
                switch (intval($value->result)) {
                    case 1:
                        $oddsDiscount = 1 + $value->odds;
                        break;
                    case 2:
                        $oddsDiscount = 1;
                        break;
                    case 3:
                        $oddsDiscount = 1 + $value->odds * 0.5;
                        break;
                    case 4:
                        $oddsDiscount = 0.5;
                        break;
                    default:
                        $oddsDiscount = 0;
                }
                $getMoneyBuyMth[$key]->winMoney = $value->bet_money * ($oddsDiscount - 1);
            } else {
                $getMoneyBuyMth[$key]->winMoney = 0;
            }
            $typeSstOdds = $getSstOdds[$value -> game_code];
            $thisSstOdds = [
                'match_id' => $value -> match_id,
                'odds_code' => $value -> odds_code,
            ];
            // 判断如果在数组中则为可加注
            if (!!$commonFunction->judgeEqual($thisSstOdds, $typeSstOdds)) {
                $getMoneyBuyMth[$key] -> addBet = 0;
            } else {
                $getMoneyBuyMth[$key] -> addBet = 1;
            }
        }
        // 获取记录总数
        $result['total'] = $allCount;
        $result['list'] = $getMoneyBuyMth;
        // 总页数计算
        $result['countPage'] = ceil($result['total'] / $pageSize);
        $result['currentPage'] = $currentPage;

        return $result;
    }

    /**
     * 串式投注记录
     *
     * @access public
     * @return String
     */
    public function stringBetRecord()
    {
        // 获取用户信息
        $accountManagerClass = new AccountManager;
        $userInfo = $accountManagerClass -> getCurrentUser();
        if (empty($userInfo['identity'])) {
            Render([], '2001', lang('Common','Api') -> get('user does login'));
        }
        // 用户ID
        $moneyBuyStrWhere['account_identity'] = $userInfo['identity'];
        // 输赢
        if (!empty($_POST['result'])) {
            $moneyBuyStrWhere['game_status'] = $_POST['result'];
        }
        // 时间区间
        $startTime = isset($_POST['startTime'])? $_POST['startTime'] : '1900-01-01 00:00:00';
        $endTime = isset($_POST['endTime'])? $_POST['endTime'] : '3000-12-12 00:00:00';
        $moneyBuyStrBetween = ['money_time' => [$startTime, $endTime]];
        $moneyBuyStrMdl = lm('money_buy_str', "commons");
        // 当前页
        $currentPage = isset($_POST['currentPage']) ? $_POST['currentPage'] : "1";
        // 分页大小
        $pageSize = isset($_POST['pageSize']) ? $_POST['pageSize'] : "10";
        // 起始查询位置
        $begin = ($currentPage - 1) * $pageSize;
        // 获取订单记录
        $moneyBuyStrSlt = ['batch_id', 'gain_money', 'game_status', 'money', 'prize_money', 'money_time'];
        $getMoneyBuyStr = $moneyBuyStrMdl -> moneyBuyStr($moneyBuyStrSlt, $moneyBuyStrWhere, $moneyBuyStrBetween, $begin, $pageSize, 1);
        $allCount = $moneyBuyStrMdl -> moneyBuyStrTotal($moneyBuyStrWhere, $moneyBuyStrBetween);
        // 获取全部订单id
        $moneyBuyMthOr = [];
        $allBatchId = array_unique($getMoneyBuyStr, SORT_REGULAR);
        if (!$allBatchId) {
            // 获取记录总数
            $result['total'] = 0;
            $result['list'] = [];
            // 总页数计算
            $result['countPage'] = 1;
            $result['currentPage'] = 1;

            return $result;
        }
        foreach ($allBatchId as $key => $value) {
            $moneyBuyMthOr[0][$key][0] = 'batch_id';
            $moneyBuyMthOr[0][$key][1] = $value['batch_id'];
        }
        $moneyBuyMthWhere['bet_type'] = 2;
        // 获取注单
        $moneyBuyMthMdl = lm('Money_buy_match', "commons");
        $moneyBuyMthSlt = ['status', 'matchResult', 'bet_money', 'home_team', 'guest_team', 'condition', 'odds', 'odds_name', 'match_id', 'batch_id', 'money_buy_match.game_code', 'money_buy_match.odds_code'];
        $getMoneyBuyMth = $moneyBuyMthMdl -> moneyBuyMatch($moneyBuyMthSlt, $moneyBuyMthWhere, $moneyBuyMthOr, $begin, $pageSize);
        // 获取可加注所需要的查询条件
        $commonFunction = C() -> get('commonFunction');
        $stOddsWheres = [];
        foreach ($getMoneyBuyMth as $key => $value) {
            $match_id = $value -> match_id;
            $odds_code = $value -> odds_code;
            $gameType = $value -> game_code;
            $where = [
                'match_id' => $match_id,
                'odds_code' => $odds_code,
            ];
            // 判断是否重复
            if (!$commonFunction -> judgeEqual($where, $stOddsWheres[$gameType])) {
                $stOddsWheres[$gameType][] = $where;
            }
        }
        // 查询数据下所有可加注的游戏
        $stOddsModel = lm('stOdds','commons');
        $stOddsSelect = ['match_id', 'odds_code'];
        $getSstOdds = [];
        // 循环查询每个运动的可加注游戏  注：由于查询不同表所以必须循环查询
        foreach ($stOddsWheres as $key => $value) {
            if ($value) {
                $getSstOdds[$key] = $stOddsModel -> stOdds($stOddsSelect, $value, $key);
            }
        }
        // 循环添加玩法和判断玩法是否可加注
        foreach ($getMoneyBuyMth as $key => $value) {
            $typeSstOdds = $getSstOdds[$value -> game_code];
            $thisSstOdds = [
                'match_id' => $value -> match_id,
                'odds_code' => $value -> odds_code,
            ];
            // 判断如果在数组中则为可加注
            if (!!$commonFunction->judgeEqual($thisSstOdds, $typeSstOdds)) {
                $getMoneyBuyMth[$key] -> addBet = 0;
            } else {
                $getMoneyBuyMth[$key] -> addBet = 1;
            }
        }
        foreach ($getMoneyBuyStr as $key => $value) {
            // 计算所赢金额.
            if ($value->gain_money) {
                $getMoneyBuyStr[$key]->winMoney = $value->gain_money - $value->money;
            } else {
                $getMoneyBuyStr[$key]->winMoney = 0;
            }
            foreach ($getMoneyBuyMth as $k => $v) {
                if ($value['batch_id'] == $v['batch_id']) {
                    $getMoneyBuyStr[$key]['money_buy'][$k] = $v;
                }
            }
        }
        // 获取记录总数
        $result['total'] = $allCount;
        $result['list'] = $getMoneyBuyStr;
        // 总页数计算
        $result['countPage'] = ceil($result['total'] / $pageSize);
        $result['currentPage'] = $currentPage;

        return $result;
    }

    /**
     * 盈亏记录
     *
     * @access public
     * @return String
     */
    public function moneyRecord()
    {
        // 获取用户信息
        $accountManagerClass = new AccountManager;
        $userInfo = $accountManagerClass -> getCurrentUser();
        if (empty($userInfo['identity'])) {
            Render([], '2001', lang('Common','Api') -> get('user does login'));
        }
        $moneyRecordWhere = array();
        // 用户ID
        $moneyRecordWhere['account_identity'] = $userInfo['identity'];
        $moneyRecordWhere['status'] = 1;
        $moneyRecordWhere['settle_status'] = 2;
        if (empty($_POST['result']) === false) {
            $moneyRecordWhere['game_status'] = empty($_POST['result']);
        }
        // 时间区间
        $startTime = isset($_POST['startTime'])? $_POST['startTime'] : '1900-01-01 00:00:00';
        $endTime = isset($_POST['endTime'])? $_POST['endTime'] : '3000-12-12 00:00:00';
        $moneyRecordBetween = [$startTime, $endTime];
        // 当前页
        $currentPage = isset($_POST['currentPage']) ? $_POST['currentPage'] : "1";
        // 分页大小
        $pageSize = isset($_POST['pageSize']) ? $_POST['pageSize'] : "10";
        // 起始查询位置
        $begin = ($currentPage - 1) * $pageSize;
        $moneyRecord = lm('Money_buy_simplex', "commons");
        $moneyRecordSelect = ['info_identity', 'trade_id', 'account_identity', 'money', 'money_time', 'money_type'];
        // 获取盈亏记录
        $result['list'] = $moneyRecord -> winLoseRecord($moneyRecordWhere, $moneyRecordBetween, $begin, $pageSize);
        // 获取记录总数
        $result['total'] = $moneyRecord -> winLoseCount($moneyRecordWhere, $moneyRecordBetween);
        // 总页数计算
        $result['countPage'] = ceil($result['total'] / $pageSize);
        $result['currentPage'] = $currentPage;

        return $result;
    }

    /**
     * 统计记录
     *
     * @access public
     * @return String
     */
    public function monthRecord()
    {
        $accountManagerClass = new AccountManager;
        $userInfo = $accountManagerClass -> getCurrentUser();
        if (empty($userInfo['identity'])) {
            Render([], '2001', lang('Common','Api') -> get('user does login'));
        }
        // 用户ID
        $moneyBuyWhere['account_identity'] = $userInfo['identity'];
        // 时间区间
        $endTime = date('Y-m-d H:i:s');
        if ($userInfo['statisticsTime']) {
            $startTime = $userInfo['statisticsTime'];
        } else {
            $startTime = '1900-01-01 00:00:00';
        }
        $moneyBuyBetween = [$startTime, $endTime];
        $moneyRecordWhere['settle_status'] = 2;
        // 获取单式投注订单
        $moneyBuySimplex = lm('money_buy_simplex', "commons");
        $mnyBuySpxData = $moneyBuySimplex
            ->select(['order_id', 'money', 'gain_money', 'batch_id'])
            ->where($moneyBuyWhere)
            ->whereBetween('settlementTime', $moneyBuyBetween)
            ->get()
            ->toArray();
        // 获取全部订单id
        $moneyBuyMthOr = [];
        $allBatchId = array_unique($mnyBuySpxData, SORT_REGULAR);
        if ($allBatchId) {
            foreach ($allBatchId as $key => $value) {
                $moneyBuyMthOr[0][$key][0] = 'batch_id';
                $moneyBuyMthOr[0][$key][1] = $value['batch_id'];
            }
            $moneyBuyMthWhere['bet_type'] = 1;
            // 获取注单
            $moneyBuyMthMdl = lm('Money_buy_match', "commons");
            $moneyBuyMthSlt = ['bet_money', 'odds', 'result'];
            $getMoneyBuyMth = $moneyBuyMthMdl -> moneyBuyMatchAll($moneyBuyMthSlt, $moneyBuyMthWhere, $moneyBuyMthOr);
        } else {
            $getMoneyBuyMth = [];
        }

        // 获取串式投注订单
        $moneyBuyStr = lm('money_buy_str', "commons");
        $mnyBuyStrData = $moneyBuyStr
            ->select(['order_id', 'money', 'gain_money'])
            ->where($moneyBuyWhere)
            ->whereBetween('settlementTime', $moneyBuyBetween)
            ->get();
        $winMoney = $userInfo['allWin'];
        $loseMoney = $userInfo['allLose'];
        // 单式盈利.
        foreach ($getMoneyBuyMth as $key => $value) {
            // 判断订单是否盈利
            if ($value->result == 1) {
                $winMoney += $value->bet_money * $value->odds;
            } else if ($value->result == 3) {
                $winMoney += $value->bet_money * $value->odds * 0.5;
            } else if ($value->result == 4) {
                $loseMoney += $value->bet_money * 0.5;
            } else if ($value->result == -1) {
                $loseMoney += $value->bet_money;
            }
        }
        // 串式盈利.
        foreach ($mnyBuyStrData as $key => $value) {
            // 判断订单是否盈利
            if ($value->money >= $value->gain_money) {
                $loseMoney += $value->money - $value->gain_money;   //本钱减回款
            } else {
                $winMoney += $value->gain_money - $value->money;    //回款减本钱
            }
        }
        // 修改用户统计
        $updateActDtd = [
          'allWin' => $winMoney,
          'allLose' => $loseMoney,
          'statisticsTime' => date('Y-m-d H:i:s'),
        ];
        $accountDetailed = lm('account_detailed', "commons");
        $accountDetailed->where(['account_identity'=>$userInfo['identity']])->update($updateActDtd);
        $result = [
            'winMoney' => $winMoney ?? 0,
            'loseMoney' => $loseMoney ?? 0,
            'allMoney' => $userInfo['available_cash'],
        ];

        return $result;
    }
}
