<?php
namespace wstshop\admin\model;
use think\Db;
 use think\Loader;
/**
 * ============================================================================
 * WSTShop网上商店
 * 版权所有 2016-2066 广州商淘信息科技有限公司，并保留所有权利。
 * 官网地址:http://www.wstshop.net
 * 交流社区:http://bbs.shangtao.net
 * 联系QQ:153289970
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 提现分类业务处理
 */
class CashDraws extends Base{
	/**
	 * 分页
	 */
	public function pageQuery(){
		$cashNo = input('cashNo');
		$cashSatus = input('cashSatus',-1);
        $where = [];
        if(in_array($cashSatus,[0,1]))$where['cashSatus'] = $cashSatus;
        if($cashNo!='')$where['cashNo'] = ['like','%'.$cashNo.'%'];
        // 排序
		$sort = input('sort');
		$order = [];
		if($sort!=''){
			$sortArr = explode('.',$sort);
			$order = $sortArr[0].' '.$sortArr[1];
			if($sortArr[0]=='cashNo'){
				$order = $sortArr[0].'+0 '.$sortArr[1];
			}
		}
        return $this->alias('c')
                    ->join('__USERS__ u','u.userId=c.targetId')
                    ->where($where)
                    ->field('u.loginName,u.userName,c.*')
                    ->order($order)->order('createTime desc')
                    ->paginate(input('limit/d'))
                    ->toArray();
	}

	/**
	 * 获取提现详情
	 */
	public function getById(){
		$id = (int)input('id');
		return $this->alias('c')
                    ->join('__USERS__ u','u.userId=c.targetId')
                    ->where('cashId',$id)->find();
	}

	/**
	 * 处理提现
	 */
	public function handle(){
		$id = (int)input('cashId');
		$cash = $this->get($id);
		if(empty($cash))return WSTReturn('无效的提现申请记录');
		$user = model('users')->get($cash->targetId);
		if($user->lockMoney<$cash->money)return WSTReturn('操作失败，被冻结的金额小于提现金额');
		Db::startTrans();
		try{
            $cash->cashSatus = 1;
            $cash->cashRemarks = input('cashRemarks');
            $result = $cash->save();
            if(false != $result){

            	$user->lockMoney = $user->lockMoney-$cash->money;
            	$user->save();
            	//创建一条流水记录
            	$lm = [];
				$lm['targetType'] = 0;
				$lm['targetId'] = $cash->targetId;
				$lm['dataId'] = $id;
				$lm['dataSrc'] = 3;
				$lm['remark'] = '提现申请单【'.$cash->cashNo.'】申请提现¥'.$cash->money.'。'.(($cash->cashRemarks!='')?"【操作备注】：".$cash->cashRemarks:'');
				$lm['moneyType'] = 0;
				$lm['money'] = $cash->money;
				$lm['payType'] = 0;
				$lm['createTime'] = date('Y-m-d H:i:s');
				model('LogMoneys')->save($lm);
				//发送信息信息
				$tpl = WSTMsgTemplates('CASH_DRAW_SUCCESS');
		        if($tpl['tplContent']!='' && $tpl['status']=='1'){
		            $find = ['${CASH_NO}'];
		            $replace = [$cash->cashNo];
		            WSTSendMsg($cash->targetId,str_replace($find,$replace,$tpl['tplContent']),['from'=>5,'dataId'=>$id]);
		        } 
				//微信消息
				if((int)WSTConf('CONF.wxenabled')==1){
					$params = [];
					$params['CASH_NO'] = $cash->cashNo;
					$params['MONEY'] = $cash->money;
					$params['CASH_TYPE'] = '银行提现';           
					$params['CASH_TIME'] = $cash['createTime'];
					$params['CASH_RESULT'] = "审核通过。【备注：".((input('cashRemarks')=='')?"无":input('cashRemarks'))."】";
					$params['EXAMINE_TIME'] = date('Y-m-d H:i:s');
					WSTWxMessage(['CODE'=>'WX_CASH_DRAW_SUCCESS','userId'=>$cash->targetId,'params'=>$params]);
				}
				Db::commit();
				return WSTReturn('操作成功!',1);
            }
		}catch (\Exception $e) {
            Db::rollback();
        }
		return WSTReturn('操作失败!',-1);
	}

	/**
	 * 处理提现失败
	 */
	public function handleFail(){
		$id = (int)input('cashId');
		$cash = $this->get($id);
		if(empty($cash))return WSTReturn('无效的提现申请记录');
		if(input('cashRemarks')=='')return WSTReturn('请输入提现失败原因');
		Db::startTrans();
		try{
	        $user = model('users')->get($cash->targetId);
			if($user->lockMoney<$cash->money)return WSTReturn('操作失败，无效的冻结的金额');
			$user->userMoney = $user->userMoney + $cash->money;
			$user->lockMoney = $user->lockMoney-$cash->money;
        	$user->save();
        	$targetId = $user->userId;
            
            $cash->cashSatus = -1;
            $cash->cashRemarks = input('cashRemarks');
            $result = $cash->save();

            if(false != $result){
				//发送信息信息
				$tpl = WSTMsgTemplates('CASH_DRAW_FAIL');
		        if( $tpl['tplContent']!='' && $tpl['status']=='1'){
		            $find = ['${CASH_NO}','${CASH_RESULT}'];
		            $replace = [$cash->cashNo,input('cashRemarks')];
		            WSTSendMsg($targetId,str_replace($find,$replace,$tpl['tplContent']),['from'=>5,'dataId'=>$id]);
		        } 
				//微信消息
				if((int)WSTConf('CONF.wxenabled')==1){
					$params = [];
					$params['CASH_NO'] = $cash->cashNo;
					$params['MONEY'] = $cash->money;
					$params['CASH_TYPE'] = '银行提现';           
					$params['CASH_TIME'] = $cash['createTime'];
					$params['CASH_RESULT'] = "审核不通过。【备注：".((input('cashRemarks')=='')?"无":input('cashRemarks'))."】";
					$params['EXAMINE_TIME'] = date('Y-m-d H:i:s');
					WSTWxMessage(['CODE'=>'WX_CASH_DRAW_FAIL','userId'=>$targetId,'params'=>$params]);
				}
				Db::commit();
				return WSTReturn('操作成功!',1);
            }
		}catch (\Exception $e) {
            Db::rollback();
        }
		return WSTReturn('操作失败!',-1);
	}
	/**
	 * 导出提现申请
	 */
	public function toExport(){
		$name='提现申请表';
		$cashNo = input('cashNo');
		$cashSatus = input('cashSatus',-1);
        $where = [];
        $where['targetType'] = 0;
        if(in_array($cashSatus,[0,1]))$where['cashSatus'] = $cashSatus;
        if($cashNo!='')$where['cashNo'] = ['like','%'.$cashNo.'%'];
        // 排序
		$sort = input('sort');
		$order = [];
		if($sort!=''){
			$sortArr = explode('.',$sort);
			$order = $sortArr[0].' '.$sortArr[1];
			if($sortArr[0]=='cashNo'){
				$order = $sortArr[0].'+0 '.$sortArr[1];
			}
		}
        $page = $this->where($where)->order($order)->order('createTime desc')->select();
	    if(count($page)>0){
	    	$userIds = [];
	    	foreach ($page as $key => $v) {
	    		if($v['targetType']==0)$userIds[] = $v['targetId'];
	    	}
	    	$userMap = [];
	    	if(count($userIds)>0){
	    		$user = Db::name('users')->where(['userId'=>['in',$userIds]])->field('userId,loginName,userName')->select();
	    	    foreach ($user as $key => $v) {
	    	    	$userMap["0_".$v['userId']] = $v; 
	    	    }
	    	}
	    	foreach ($page as $key => $v) {
	    		$page[$key]['userType'] = "【会员】";
	    		$page[$key]['loginName'] = $userMap[$v['targetType']."_".$v['targetId']]['loginName'];
	    		$page[$key]['userName'] = $userMap[$v['targetType']."_".$v['targetId']]['userName'];
	    		$page[$key]['cashSatus'] = ($page[$key]['cashSatus']==1)?'提现成功':(($page[$key]['cashSatus']==-1)?'提现失败':'待处理');
	    	}
	    }

		Loader::import('phpexcel.PHPExcel.IOFactory');
		$objPHPExcel = new \PHPExcel();
		// 设置excel文档的属性
		$objPHPExcel->getProperties()->setCreator("WSTMart")//创建人
		->setLastModifiedBy("WSTMart")//最后修改人
		->setTitle($name)//标题
		->setSubject($name)//题目
		->setDescription($name)//描述
		->setKeywords("提现")//关键字
		->setCategory("Test result file");//种类
	
		// 开始操作excel表
		$objPHPExcel->setActiveSheetIndex(0);
		// 设置工作薄名称
		$objPHPExcel->getActiveSheet()->setTitle(iconv('gbk', 'utf-8', 'Sheet'));
		// 设置默认字体和大小
		$objPHPExcel->getDefaultStyle()->getFont()->setName(iconv('gbk', 'utf-8', ''));
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(11);
		$styleArray = array(
				'font' => array(
						'bold' => true,
						'color'=>array(
								'argb' => 'ffffffff',
						)
				),
				'borders' => array (
						'outline' => array (
								'style' => \PHPExcel_Style_Border::BORDER_THIN,  //设置border样式
								'color' => array ('argb' => 'FF000000'),     //设置border颜色
						)
				)
		);
		//设置宽
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(12);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(12);


		$objPHPExcel->getActiveSheet()->getStyle('A1:I1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('A1:I1')->getFill()->getStartColor()->setARGB('333399');
		
		$objPHPExcel->getActiveSheet()->setCellValue('A1', '提现单号')
		->setCellValue('B1', '会员类型')->setCellValue('C1', '会员名称')
		->setCellValue('D1', '提现银行')->setCellValue('E1', '银行卡号')
		->setCellValue('F1', '持卡人')->setCellValue('G1', '提现金额')
		->setCellValue('H1', '提现时间')->setCellValue('I1', '状态');
		$objPHPExcel->getActiveSheet()->getStyle('A1:I1')->applyFromArray($styleArray);
	
		for ($row = 0; $row < count($page); $row++){
			$i = $row+2;
			$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $page[$row]['cashNo'])
			->setCellValue('B'.$i, $page[$row]['userType'])->setCellValue('C'.$i, $page[$row]['userName'].'('.$page[$row]['loginName'].')' )
			->setCellValue('D'.$i, $page[$row]['accTargetName'])->setCellValue('E'.$i, $page[$row]['accNo'])
			->setCellValue('F'.$i, $page[$row]['accUser'])->setCellValue('G'.$i, '￥'.$page[$row]['money'])
			->setCellValue('H'.$i, $page[$row]['createTime'])->setCellValue('I'.$i, $page[$row]['cashSatus']);
		}
	
		//输出EXCEL格式
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		// 从浏览器直接输出$filename
		header('Content-Type:application/csv;charset=UTF-8');
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-excel;");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
		header('Content-Disposition: attachment;filename="'.$name.'.xls"');
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
	}
}
