<?php
namespace admin\controller;

/**
 * 控制器
 * 
 */
class Cash extends Admin {
	
	//修改
	public function shenhe(){
		if(IS_POST){
			$id=I('id','0');
			$m=D('pub/Cash');
			$m->where(array('status'=>array('in',array(0,2)),'id'=>array('in',$id)))->save(array('status'=>1));
			$this->ajaxReturn(array('status'=>1));
		}
	}
	
	//支付
	public function zhifu(){
		$list=M('cash')->where(array('status'=>1))->select();
		$num=0;
		foreach ($list as $k => $v) {
			$aop = new \alipay\aop\AopClient ();
			$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
			$aop->appId = C('ALIPAY_appId');
			$aop->rsaPrivateKey = C('ALIPAY_rsaPrivateKey');
			$aop->alipayrsaPublicKey=C('ALIPAY_alipayrsaPublicKey');
			$aop->apiVersion = '1.0';
			$aop->signType = 'RSA2';
			$aop->postCharset='UTF-8';
			$aop->format='json';
			$request = new \alipay\aop\request\AlipayFundTransToaccountTransferRequest ();
			$data=array(
				'out_biz_no'=>$v['no'],
				'payee_type'=>'ALIPAY_LOGONID',
				'payee_account'=>$v['cash_card'],
				'amount'=>$v['amount'],
				'payer_show_name'=>'106云盘',
				'payee_real_name'=>$v['truename'],
				'remark'=>'提现',
			);
			$request->setBizContent(json_encode($data));
			$result = $aop->execute ( $request); 
			
			$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
			$resultCode = $result->$responseNode->code;
			if(!empty($resultCode)&&$resultCode == 10000){
				D('pub/Cash')->save(array(
					'id'=>$v['id'],
					'status'=>3,
					'pay_time'=>time(),
				));
				$num++;
			} else {
				if($result->$responseNode->sub_code=='PAYER_BALANCE_NOT_ENOUGH'){
				    $status=2;
				}else{
					$status=-1;
				}
				D('pub/Cash')->save(array(
					'id'=>$v['id'],
					'status'=>$status,
					'about'=>$result->$responseNode->sub_msg,
				));
			}
		}
		if(count($list)==0){
		    $this->error('待支付笔数为0');
		}else if(count($list)>$num){
			$this->error('有'.(count($list)-$num).'笔支付失败');
		}else{
			$this->success('支付成功');
		}
		
	}

	public function del(){
		$id=I('id',false);
		$this->ajaxReturn(array(
			'status'=>1
		));
		
	}
	
	/**
	 * 
	 */
	public function mod($id){
		$m = D('pub/Cash');
		if(IS_POST){
			if($m->create() && $m->save()){
				$this->success('修改成功',Cookie('__forward__'));
			}else{
				$this->error($m->getError());
			}
		}
	}
		
}