<?php
defined('PP_PATH') or exit;
class withdraw_control extends user_control{
	public $_navgroup = 'withdraw';

	//提现申请
	public function index(){
		$this->assign_value('navkey', 'withdraw-index');
		
		if(empty($_POST)) {
			$this->display('withdraw_index.htm');
		}else{
			$money 		= floatval(R('money','P'));
			$paybank 	= R('paybank','P');
			//$charge 	= floatval(R('charge','P'));

			$order_id = order_number();

			if($money <= 0){
				E(1, '提现金额必须大于0');
			}
			if($money < $this->_cfg['user']['mintx']){
				E(1, '单笔提现金额应不少于'.$this->_cfg['user']['mintx']);
			}
			if($money > $this->_user['money']){
				E(1, '提现金额不足');
			}
			//手续费
			$charge = number_format($money*$this->_cfg['user']['charge']/100,2, ".", "");
			
			//更新用户金额
			$userdate = array(
				'uid' 			=> $this->_user['uid'],
				'money' 		=> $this->_user['money'] - $money,
				'dmoney' 		=> $this->_user['dmoney'] + $money,
			);

			if(!$this->user->update($userdate)){
				E(1, '用户余额更新失败');
			}

			//写入交易记录库
			//成功后更新充值状态，更新订单状态，并增加消费记录
			$record = &$this->record;
			$recordata = array(
				'uid'		=> $this->_user['uid'],
				'username'	=> $this->_user['username'],
				'money'		=> $money,
				'charge'	=> $charge,
				'type'		=> 3, //1 充值 2消费 3提现 4提成
				'paybank'	=> $paybank,
				'order_id'	=> $order_id,
				'created'	=> $_ENV['_time'],
				'status'	=> 1,
				'comment'	=> '提现，扣除手续费 '.$charge.' 元',
			);
			if($record->create($recordata)){
				E(0, '提现申请成功！');
			}else{
				E(1, '提现申请失败！请联系站长！');
			}
		}
	}
	
	//提现列表
	public function mylist(){
		$this->assign_value('navkey', 'withdraw-mylist');
		$where['uid'] = $this->_uid;
		$pagenum = 20;
		
		$where['type'] = 3;	
		$total = $this->record->find_count($where);
		
		$maxpage 	= max(1, ceil($total/$pagenum));
		$page 		= min($maxpage, max(1, intval(R('page'))));
		$pages 		= user_pages($page, $maxpage, 'index.php?u=record-index-page-{page}');
		$this->assign('total', $total);
		$this->assign('pages', $pages);
		
		$cms_arr = $this->record->list_arr($where, 'id', -1, ($page-1)*$pagenum, $pagenum, $total);
		foreach($cms_arr as &$v) {
			switch ($v['paybank']){
				case 'chinabank':
					$v['paybank'] = '网银在线';break;
				case 'lifealipay':
					$v['paybank'] = '支付宝转帐';break;
				case 'alipay':
					$v['paybank'] = '支付宝';break;
				default:
					$v['paybank'] = '系统';
			}
		}
		$this->assign('lists', $cms_arr);
		$this->display('withdraw_mylist.htm');
	}
	//修改支付宝
	public function edit_alipay(){
		$this->assign_value('navkey', 'index-profile');
		if(empty($_POST) ){
			E(1, '无效参数!');
		}else{
			$alipay_name = R('alipay_name','P');
			$alipay = R('alipay','P');
			
			if(empty($alipay)){
				E(1, '支付宝不能为空！');
			}else{
				$user = &$this->user;
				$info['uid'] 			= $this->_user['uid'];
				$info['alipay_name'] 	= $alipay_name;
				$info['alipay'] 		= $alipay;
				if( $user->update($info) ){
					E(0, '修改成功！');
				}else{
					E(1, '修改失败！');
				}
			}
		}
	}
}
