<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request as Req;
use Request;

/**
 *
 */
class RemittanceController extends Controller {
	/**
	 * @return 汇款管理
	 */
	function index() {
        $request=array();
        $request['account_name'] = Request::has('account_name') ? Request::get('account_name') : '';
        $request['order_id'] = Request::has('order_id') ? Request::get('order_id') : '';
        $request['recharge_type'] = Request::has('recharge_type') ? Request::get('recharge_type') : '';
        $request['status'] = Request::has('status') ? Request::get('status') : '3';
        $request['apply_startime'] = Request::get('apply_startime') ? Request::get('apply_startime') : '';
        $request['apply_endtime'] = Request::get('apply_endtime') ? Request::get('apply_endtime') : '';
        $request['haddle_startime'] = Request::get('haddle_startime') ? Request::get('haddle_startime') : '';
        $request['haddle_endtime'] = Request::get('haddle_endtime') ? Request::get('haddle_endtime') : '';
        $request['money_small'] = Request::has('money_small') ? Request::get('money_small') : '';
        $request['money_big'] = Request::has('money_big') ? Request::get('money_big') : '';

		$dt = \App\Lib\DataTable\DataTable::init();
		$account_name = Request::has('account_name') ? Request::get('account_name') : '';
		$status = Request::has('status') ? Request::get('status') : '';
		$dt->setDataSource('/admin/Remittance/getData');
		$dt->setLang('money');
		$dt->setPriKey('order_id');
		$dt->addColsFields('id', array('width' => 80));
		$dt->addColsFields('account_name', array('templet' => '#userrecharge', 'width' => 150, 'sort' => false));
		$dt->addColsFields('apply_time');
		$dt->addColsFields('group_name', array('width' => 220));
		$dt->addColsFields('recharge_time', array('templet' => '#money_user','width' => 180));
		$dt->addColsFields('complete_time', array('templet' => '#taked', 'width' => 180));
		$dt->addColsFields('money', array('templet' => '#money_aftercash', 'width' => 290));
		$dt->addColsFields('systemuser_rechargetype', array('sort' => false, 'width' => 150));
		$dt->addColsFields('action', array('sort' => false, 'templet' => '#sendmoney', 'width' => 110));
		return view('admin.remittance/index', $dt->render($request));
	}

	//获取数据
	function getData() {
		$page = Request::has('page') ? Request::get('page') : 1;
		$limit = Request::has('limit') ? Request::get('limit') : 10;
		$field = Request::has('field') ? Request::get('field') : 'apply_time';
		$order = Request::has('order') ? Request::get('order') : 'desc';

		$account_name = Request::has('account_name') ? Request::get('account_name') : '';
		$order_id = Request::has('order_id') ? Request::get('order_id') : '';
		$recharge_type = Request::has('recharge_type') ? Request::get('recharge_type') : '';
		$status = Request::has('status') ? Request::get('status') : '';
		$apply_startime = Request::get('apply_startime') ? Request::get('apply_startime').' 00:00:00' : '';
		$apply_endtime = Request::get('apply_endtime') ? Request::get('apply_endtime').' 23:59:59' : '';
		$haddle_startime = Request::get('haddle_startime') ? Request::get('haddle_startime').' 00:00:00' : '';
		$haddle_endtime = Request::get('haddle_endtime') ? Request::get('haddle_endtime').' 23:59:59' : '';
		$money_small = Request::has('money_small') ? Request::get('money_small') : '';
		$money_big = Request::has('money_big') ? Request::get('money_big') : '';
		$sureblur = Request::has('sureblur') ? Request::get('sureblur') : '';

        $whereIn = array();
		$where = array();
        $reType=trans('status.money_recharge.send_type');
		if (!empty($recharge_type)) {
			$where[] = array('recharge_type', '=', $reType[$recharge_type]);
		}
//		if (!empty($status)) {
//			$status = ($status==3)?'0':$status;
//			$where[] = array('status', '=', $status);
//		}
        if (is_numeric($status)) {
            if ($status != 4) {
                $where[] = array('status', '=', $status);
            }

        }
		if (!empty($apply_startime)) {
			$apply_startime = date('Y-m-d H:i:s', strtotime($apply_startime));
			$where[] = array('apply_time', '>=', $apply_startime);
		}
		if (!empty($apply_endtime)) {
			$apply_endtime = date('Y-m-d H:i:s', strtotime($apply_endtime));
			$where[] = array('apply_time', '<=', $apply_endtime);
		}
		if (!empty($haddle_startime)) {
			$haddle_startime = date('Y-m-d H:i:s', strtotime($haddle_startime));
			$where[] = array('complete_time', '>=', $haddle_startime);
		}
		if (!empty($haddle_endtime)) {
			$haddle_endtime = date('Y-m-d H:i:s', strtotime($haddle_endtime));
			$where[] = array('complete_time', '<=', $haddle_endtime);
		}
		if (!empty($money_small)) {
			$where[] = array('money', '>=', $money_small);
		}
		if (!empty($money_big)) {
			$where[] = array('money', '<=', $money_big);
		}

		$infield = 'recharge_type';
        $invalue = ['汇款', '汇款赠送'];

		if (!empty($account_name)) {
			if (empty($sureblur) || $sureblur == '模糊') {
				$where[] = array('account_name', 'like', '%' . $account_name . '%');
			} else {
				$where[] = array('account_name', '=', $account_name);
			}
		}

		if (!empty($order_id)) {
			$where = array(array('money_recharge.order_id', '=', $order_id));
		}
		$moneydetails = new \App\Models\Money_recharge();
		$jointable = 'money_recharge_remark';

		if($field=='recharge_time'){
			$field = 'money_recharge_remark.'.$field;
		}else if($field=='group_name'){
            $field = 'account_detailed.'.$field;
        } else{
			$field = 'money_recharge.'.$field;
		}
        $remark = 'money_recharge.remark';

		$data = $moneydetails->getRechargelist($where, 8, $limit, $field, $order, $infield, $invalue, $jointable,$whereIn);
		if ($data < 0) {
			return $data;
		}
		$status = trans('status');
		$status = $status['money_recharge']['sendstatus'];
		foreach ($data['data'] as $k => $v) {
			$data['data'][$k]['apply_time'] = $v['order_id'] . '<br>' . $v['apply_time'];
			$data['data'][$k]['statuss'] = $status[$v['status']];
			// $data['data'][$k]['complete_time'] = $data['data'][$k]['statuss'] . '<br>' . $v['complete_time'];
			$data['data'][$k]['systemuser_rechargetype'] = $v['sysetem_user'] . '<br>' . $v['recharge_type'];
			(empty($v['remark']))?null:($data['data'][$k]['systemuser_rechargetype'].='---'.$v['remark']);
			//$data['data'][$k]['recharge_time'] = $v['name'] . '<br>' . $v['recharge_time'];
		}
		$data['data'] = arrayToNumber($data['data'], ['money', 'money_cash']);
		return \App\Lib\DataTable\DataTable::init()->toJson($data['data'], $data['total'], 0, $where);
	}
	//汇款统计
	function getTotal() {

	}
	//获取
	private function getSumRemit($startTime, $endTime, $type = '') {
		if (empty($startTime)) {
			$startTime = date('Y-m-d 00:00:00');
		}
		if (empty($endTime)) {
			$endTime = date('Y-m-d 23:59:59');
		}
		$db = new \App\Models\Money_recharge;
		$where = array();
		$where[] = array('money_time', '>=', $startTime);
		$where[] = array('money_time', '<=', $endTime);
		if ($type) {
			$where[] = array('trade_type', '=', $type);
		} else {
			//获取总存取反水金额
			return $db->getRimitTotal($where);
		}
		//规定的类型总数
		return $db->sumRimitMoney($where);
	}

	//汇款详情

	function Sendview(Req $req) {
		return $this->senddetail($req);
	}

	//查看汇款详情
	function senddetail(Req $req) {
		$orderid = $req->orderid;
		if (empty($orderid)) {
			abort(404);
		}
		$send = new \App\Models\Money_recharge();
		if (!$req->isMethod('post')) {
			$where = array();
			if (!empty($orderid)) {
				$where[] = array('order_id', '=', $orderid);
			}
			$data = $send::where($where)->first();
			if (!$data) {
				abort(404);
			}
			$data = $data->toArray();
			return view('admin.MoneyManage/Senddetail', ['data' => $data]);
			//return view('admin.menu/userAdd', ['data' => $data_details]);
		}
		abort(404);
	}

	//汇款通过
	function save_recharge(Req $req) {
		return $this->EditSend($req);
	}

	//汇款通过
	function EditSend(Req $req) {
		$order_id = $req->order_id;
		if (empty($order_id)) {
			abort(404);
		}
		$send = new \App\Models\Money_recharge();
		$where = array();
		$where[] = array('order_id', '=', $order_id);
		$data = $send::where($where)->first();
		if (!$data) {
			abort(404);
		}
		$data = $data->toArray();
		//print_r($data);exit;
		if (!$req->isMethod('post')) {
			$account = new \App\Models\Account_detailed();
			$uinfo = $account->getInfoBy($data['account_identity']);
			if($uinfo<0){
				return responseToJson($uinfo);
			}
			$data['cur_cash'] = $uinfo['cash'];
			return view('admin.remittance/save_recharge', ['data' => $data]);
		} else {
			$limitroot = new \App\Models\System_user();
			$limitmoney = $limitroot->checkActMoney($data['money']);
			if($limitmoney<0){
				return responseToJson($limitmoney);
			}
			$point = empty($req->point)?0:$req->point;
			$checkedL = empty($req->checkedL)?2:$req->checkedL;
			$point = ($checkedL == 1) ? $point / 100 : 0;
			$rimit = new \App\Http\Controllers\Admin\MoneyController;
			$res = $rimit->Rimit($order_id, $point);

			$log = array(
				session('adminInfo.admin_name'),
                $data['account_name'],
                $data['money'],
                $order_id,
			);

            $db = new \App\Models\Manager;

            $dbs = new \App\Models\Account();
            $names=$dbs->getinfo($data['account_identity'],2);
            $db->updateMessage('admin',$names['account'],'充值提示','充值成功，充值金额:'.$data['money'],2);
			OperationLog(session('adminInfo.admin_id'), 'EditSend', $log);
			return responseToJson($res);
		}
	}

	//汇款驳回
	function return_recharge(Req $req) {
		return $this->EditReturn($req);
	}

	//汇款驳回
	function EditReturn(Req $req) {
		$order_id = $req->order_id;
		if (empty($order_id)) {
			abort(404);
		}
		$send = new \App\Models\Money_recharge();
		$where = array();
		$where[] = array('order_id', '=', $order_id);
		$data = $send::where($where)->first();
		if (!$data) {
			abort(404);
		}
		$data = $data->toArray();
		$temp_data=$data;
		if (!$req->isMethod('post')) {
			return view('admin.remittance/return_recharge');
		} else {
			//验证可操作金额权限
			$db = new \App\Models\Money_recharge;
			$info = $db->getRimitDetails($order_id);
			if ($info < 0) {
				return responseToJson($info);
			}
			$limitroot = new \App\Models\System_user();
			$limitmoney = $limitroot->checkActMoney($info['money']);
			if($limitmoney<0){
				return responseToJson($limitmoney);
			}
            $db = new \App\Models\Manager;
            $dbs = new \App\Models\Account();
            $names=$dbs->getinfo($data['account_identity'],2);
            $db->updateMessage('admin',$names['account'],'充值提示','充值失败，充值金额:'.$info['money'],2);


			$reason = $req->reason;
			$account = new \App\Models\Account_detailed();
			$uinfo = $account->getInfoBy($data['account_identity']);
			if($uinfo<0){
				return responseToJson($uinfo);
			}
			$data = array();
			$data['status'] = 2;
			if (!empty($reason)) {
				$data['sysetem_user'] = session('adminInfo.admin_name');
				$data['money_cash'] = $uinfo['cash'];
				$data['complete_time'] = date('Y-m-d H:i:s',time());
				$data['reason'] = $reason;
			}

			$db = new \App\Models\Money_recharge;
			$res = $db->updateInfo($data, 'order_id', $order_id);
			if($res<0){
                return responseToJson($res);
            }
            $res=$this->addRemitFailLog($temp_data,$uinfo['cash'],$reason);
            $log = array(
				session('adminInfo.admin_name'),
                $temp_data['account_name'],
                $info['money'],
                $reason,
                $order_id,
			);
			OperationLog(session('adminInfo.admin_id'), 'EditReturn', $log);
			return responseToJson($res);
		}
	}
    //添加汇款失败详情
    function addRemitFailLog($data,$money_cash,$reason){
        $lang=array(
          session('adminInfo.admin_name'),
            $data['account_name'],
            $data['money'],
            $data['order_id']
        );
	    $log=array(
	        'trade_id'=>$data['order_id'],
            'account_name'=>$data['account_name'],
            'account_identity'=>$data['account_identity'],
            'money'=>$data['money'],
            'money_time'=>date('Y-m-d H:i:s'),
            'money_type'=>2,
            'trade_type'=>14,
            'trade_desc'=>vsprintf( trans('trade.remit_money_fail') , $lang),
            'reason'=>$reason,
            'sysetem_user'=>session('adminInfo.admin_name'),
            'money_cash'=>$money_cash,
            'status'=>2,
        );
	    $db=new \App\Models\Money_details;
	    return $db->insertData($log);
    }

}
