<?php
namespace Biz\Pay;
define('GAME_APPEND_MAX_NUM', 100);
/**
 * game append
 */
class GameAppend {
	public function update($gameName, $userId, $code, $money, $num = 1) {
		$data = M($gameName)->sort('open_time', 'desc')->find();
		$length = M($gameName)->select('count(id) as ct')->where('open_time', '')->find();
		if (!$data) {
			return -2; //无当前期数
		}
		$num = GAME_APPEND_MAX_NUM - $length['ct'];
		if ($num < 1) {
			return -3; //期数超过
		}
		$list = $this->appendGame($data['info_no'], $num);
		$sw = new DBExtension();
		$sw->B();
		if (is_array($list) && count($list) > 0) {
			foreach ($list as $k => $v) {
				M($gameName)->I($v);
				$new = array();
				$new['identity'] = UUID();
				$new['account_identity'] = $userId;
				$new[$gameName . '_identity'] = $v['identity'];
				$new['no'] = $v['info_no'];
				$new['money'] = $money;
				$new['codes'] = json_encode($code);
				$new['order_id'] = OrderID();
				$new['status'] = 0;
				M($gameName . '_buy')->I($new);
				$re = $this->updateMoney($userId, $v['identity'], $new['identity'], OrderID(), $money);
				if ($re < 0) {
					$res = $sw->C();
					return -4; //余额不足
				}
			}
		}
		return 1;

	}

	public function appendGame($gameNo, $num = 1, $jump = 1) {
		$data = array();
		while ($num > 0) {
			$row = array();
			$gameNo = $gameNo + $jump;
			$row['info_no'] = $gameNo;
			$row['identity'] = UUID();
			$row['info_identity'] = UUID();
			$row['open_time'] = '';
			$row['time'] = date('Y-m-d H:i:s');
			$row['status'] = 0;
			$row['sealingplate'] = 60;
			$data[] = $row;
			$num--;
		}
		return $data;
	}

	public function buy($game_table, $userId, $money, $no_old, $time_old, $time) {
		//查询账号余额
		$user = M('account_detailed');
		$balance = $user->select('available_cash,cash')->where('account_identity', $userId)->find();
		//判断账户余额是否支持追号
		if ($balance['available_cash'] < $money) {
			echo json_encode(['code' => 400, 'msg' => 'Sorry, your credit is running low', 'data' => null]);
			exit;
		}
		//获取投注期号，开奖唯一id
		$xy28 = M($game_table);
		$nos = $xy28->select('info_no,identity,open_time')->where('status', 0)->sort('open_time', 'asc')->find();
		//判断是否处于封盘时间
		$op_time = strtotime($nos['open_time']);
		if ($op_time - time() < 60) {
			echo json_encode(['code' => 400, 'msg' => '当前期游戏已封盘', 'data' => null]);
			exit;
		}

		$no = $nos['info_no']; //期号
		$xy28_identity = $nos['identity']; //开奖唯一id
		$identity = UUID(); //生成identity
		//资金明细记录
		$detail_id = UUID(); //用户明细id
		$account_name = isset($_SESSION['uinfo']['account']) ? $_SESSION['uinfo']['account'] : ''; //用户名
		$account_email = isset($_SESSION['uinfo']['email']) ? $_SESSION['uinfo']['email'] : ''; //用户邮箱
		$account_phone = isset($_SESSION['uinfo']['phone']) ? $_SESSION['uinfo']['phone'] : ''; //用户手机
		$money_type = 2;
		$remarks = $identity;
		$money_time = date('Y-m-d H:i:s', time());
		$money_date = date('Y-m-d ', time());
		//获取游戏id
		$game_id = M('game_list')->select('identity')->where('table_name', $game_table)->find();
		$game_id = $game_id['identity'];
		/**开启事务**/
		$SW = new DBExtension();
		$SW->B(); //开启事务
		//更新用户表金额的记录
		$available_cash = $balance['available_cash'] - $money;
		$cash = $balance['cash'] - $money;
		$allcash = ['available_cash' => $available_cash, 'cash' => $cash];
		$res1 = $SW->ST('account_detailed')->W('account_identity', $userId)->U($allcash);
		//组装数组添加明细
		$money_detil = [
			'identity' => $detail_id,
			'account_identity' => $userId,
			'account_name' => $account_name,
			'account_phone' => $account_phone,
			'account_email' => $account_email,
			'money_type' => $money_type,
			'money' => $money,
			'remarks' => $remarks,
			'money_time' => $money_time,
			'money_date' => $money_date,
			'game_type' => 1,
			'order_id' => OrderID(),
			'cur_cash' => $available_cash,
			'game_type' => $game_id,
		];
//        $xy28_buy = M('fund_detailed');
		$res2 = $SW->ST('fund_detailed')->I($money_detil);
		if (!$res1) {
			echo json_encode(['code' => 400, 'msg' => 'fail', 'data' => null]);
			exit;
		}
		//查询追号号码信息
		$xy28_buy1 = M($game_table . '_buy');
		$code = $xy28_buy1->select('codes')->where("no = '{$no_old}'", " and open_time='{$time_old}' and account_identity=", "$userId")->find();
		$code = $code['codes'];
		//组装数组添加购买记录
		$data = [
			'no' => $no,
			'identity' => $identity,
			'account_identity' => $userId,
			$game_table . '_identity' => $xy28_identity,
			'codes' => $code,
			'money' => $money,
			'code_type' => '多种',
			'open_time' => $time,
			'buy_status' => 2,
			'order_id' => OrderID(),
		];
//        $xy28_buy = M($game_table.'_buy');
		$res3 = $SW->ST($game_table . '_buy')->I($data);
		$data['gameid'] = $game_id;
		$res = $SW->C();
		if ($res) {
			echo json_encode(['code' => 200, 'msg' => 'success', 'data' => $data]);
		} else {
			echo json_encode(['code' => 400, 'msg' => 'fail', 'data' => null]);
		}
	}

	function updateMoney($userId, $gameId, $buyId, $orderId, $money) {

		//查询用户信息
		$a = M('account_detailed');
		$userInfo = $a
			->select('cash,available_cash')
			->where('account_identity', $userId)
			->find();
		$name = M('account')->select('account')->where('identity', $userId)->find();
		$name = $name['account'];
		$csh = $userInfo['cash'] - $money;
		if ($csh < 0) {
			return -2;
		}
		$ach = $userInfo['available_cash'] - $money;
		//用户资金变动数组
		$newCash = array(
			'cash' => $csh,
			'available_cash' => $ach,
		);
		$newInfo = array(
			'identity' => UUID(),
			'account_identity' => $userId,
			'account_name' => $name,
			'money_type' => 2,
			'money' => $money,
			'remarks' => $buyId,
			'money_time' => date('Y-m-d H:i:s', time()),
			'money_date' => date('Y-m-d', time()),
			'game_type' => $gameId,
			'order_id' => $orderId,
			'cur_cash' => $ach,
		);
		//开启事务
		$sw = new DBExtension();
		$sw->B();
		//更新用户余额
		$sw->ST('account_detailed')->W('account_identity', $userId)->U($newCash);
		//插入用户消费资金记录
		$sw->ST('fund_detailed')->I($newInfo);
		$res = $sw->C();
		if ($res) {
			return 1;
		}
		return -1;
	}
}