<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Withdraw_rule;
use Illuminate\Http\Request as Req;
use Illuminate\Support\Facades\DB;
use Request;

/**
 *
 */
class TakeController extends Controller
{
    /**
     * @return 提现管理
     */
    function index(Req $req)
    {
        $request = array();
        $request['grade'] = isset($req->grade) ? trim ($req->grade) : null;
        $request['account_name'] = isset($req->account_name) ? trim ($req->account_name) : null;
        $request['order_id'] = isset($req->order_id) ? trim ($req->order_id) : null;
        $request['bank_user'] = isset($req->bank_user) ? trim ($req->bank_user) : null;
        $request['grade'] = isset($req->grade) ? trim ($req->grade) : null;
        $request['status'] = isset($req->status) ? trim ($req->status) : 3;
        $request['money_small'] = isset($req->money_small) ? trim ($req->money_small) : null;
        $request['money_big'] = isset($req->money_big) ? trim ($req->money_big) : null;
        $request['apply_startime'] = isset($req->apply_startime) ? trim ($req->apply_startime) : trans ('status.default_time.atime');
        $request['apply_endtime'] = isset($req->apply_endtime) ? trim ($req->apply_endtime) : trans ('status.default_time.etime');
        $request['haddle_startime'] = isset($req->haddle_startime) ? trim ($req->haddle_startime) : null;
        $request['haddle_endtime'] = isset($req->haddle_endtime) ? trim ($req->haddle_endtime) : null;
        $request['sureblurs'] = isset($req->sureblurs) ? $req->sureblurs : 'on';


        $dt = \App\Lib\DataTable\DataTable::init ();
        $dt->setDataSource ('/admin/money/withdraw');
        $dt->setLang ('money');
        $dt->setPriKey ('order_id');
        $dt->addColsFields ('id', array('width' => 90));
        $dt->addColsFields ('account_name', array('templet' => '#usertake', 'width' => 130));
        $dt->addColsFields ('apply_time', array('width' => 230));
        $dt->addColsFields ('money', array('templet' => '#money_aftercash', 'width' => 280));
        $dt->addColsFields ('bank_info_no', array('sort' => false, 'templet' => '#infoNo', 'width' => 200));
        $dt->addColsFields ('bank_user_address', array('sort' => false, 'width' => 180));
        $dt->addColsFields ('reason', array('sort' => false));
        $dt->addColsFields ('pass_time', array('templet' => '#takes', 'width' => 180));
        $dt->addColsFields ('pass', array('sort' => false, 'templet' => '#pass', 'width' => 120));
        return view ('admin.Take/index', $dt->render ($request));
    }

    /**
     * 单用户提现列表
     * [detail description]
     * @return [type] [description]
     */
    function usertake()
    {
        $account_name = Request::has ('account_name') ? Request::get ('account_name') : '';
        $dt = \App\Lib\DataTable\DataTable::init ();
        $dt->setDataSource (htmlspecialchars ('/admin/money/withdraw?account_name=' . $account_name . "&sureblur=精确"));
        $dt->setLang ('money');
        $dt->setPriKey ('order_id');
        $dt->addColsFields ('id', array('width' => 100));
        $dt->addColsFields ('account_name', array('templet' => '#usertake', 'width' => 110));
        $dt->addColsFields ('apply_time', array('width' => 200));
        $dt->addColsFields ('money', array('width' => 100));
        $dt->addColsFields ('bank_info_no', array('sort' => false, 'width' => 180));
        $dt->addColsFields ('bank_user_address', array('sort' => false, 'width' => 180));
        $dt->addColsFields ('pass_time', array('width' => 180));
        $dt->addColsFields ('pass', array('sort' => false, 'templet' => '#pass', 'width' => 100));
        return view ('admin.Take/usertake', $dt->render ());
    }

    //查看提现
    function Edit(Req $req)
    {
        $order_id = $req->order_id;
        if (empty($order_id)) {
            abort (404);
        }
        $moneydetails = new \App\Models\Money_take();
        $userObj = new \App\Models\Account();
        $accountDB = new \App\Models\Account_detailed();
        $reccharge = new \App\Models\Money_recharge(); //充值
        $money_buy_db = new \App\Models\MoneyBuy(); //购买
        $data = $moneydetails->getOrderDetails ($order_id, 3);
        if ($data < 0) {
            return responseToJson ($data);
        }
        if (!$req->isMethod ('post')) {
            $userRemark = $userObj->getinfo ($data['account_identity'], 2);
            $data['user_remark'] = $userRemark['remark'];
            $account = $accountDB->getInfoBy ($data['account_identity']);
            $data['last_money'] = $account['available_cash']; //交易余额
            $data['pre_money'] = $data['money'] + $account['available_cash']; //交易余额
            $count_take = $moneydetails->getCount ($data['account_identity']);
            $data['take_count'] = $count_take;
            $data['today_take'] = $moneydetails->gettoDayCount ($data['account_identity']);
            $last_rech_info = $reccharge->getLast ($data['account_identity']);
            $time = isset($last_rech_info['apply_time']) ? $last_rech_info['apply_time'] : '';
            $data['last_recharge_time'] = $time; //最后一笔存款时间
            $data['last_recharge_money'] = isset($last_rech_info['money']) ? $last_rech_info['money'] : '0'; //最后一笔存款金额
            $data['total_bet_money'] = 0;
            $re = Withdraw_rule::check ($data['account_identity']);
            $data['needBettingMoney'] = $re ? $re->needBettingMoney : '未设定';
            $data['bettingMoney'] = $re ? $re->bettingMoney : '未设定';
            $data['total_bet_money'] = $data['bettingMoney'];
            $tradetype = \App\Models\Money_details::select('trade_type')->where('trade_id',$data['order_id'])->first();
            $data['active'] = ($tradetype && isset($tradetype->trade_type))?$tradetype->trade_type:5;
            return view ('admin.Take/edit', ['data' => $data]);
        } else {
            //验证可操作金额限额
            $limitroot = new \App\Models\System_user();
            $limitmoney = $limitroot->checkActMoney ($data['money']);
            if ($limitmoney < 0) {
                return responseToJson ($limitmoney);
            }
            if (empty($req->status)) {
                return responseToJson (-3025210022); //已处理的订单不能再处理
            }
            $tradetype = $req->active?trim($req->active):5;
            //开启事务
            DB::beginTransaction ();
            $datas = array(
                'status' => $req->status,
                'reason' => $req->reason,
            );
            $datas['pass_time'] = date ('Y-m-d H:i:s');
            $data['pass_time'] = $datas['pass_time'];
            $res = \App\Models\Money_count::AddCountinfo ($data, 'take');
            if ($res < 0) {
                DB::rollback ();//事务回滚
                return responseToJson ($res);
            }
            $res = $moneydetails->checkInfo ($order_id);
            if ($res < 0) {
                DB::rollback ();//事务回滚
                return responseToJson ($res);
            }
            if ($req->status == 2) {
                //如果驳回
                $res1 = $accountDB->addMoney ($data['account_identity'], $data['money']);
                if ($res1 < 0) {
                    DB::rollback ();//事务回滚
                    return responseToJson ($res1);
                }
            }
            $res = $moneydetails->updateInfo ($datas, $order_id);
            if ($res < 0) {
                DB::rollback ();//事务回滚
                return responseToJson ($res);
            }
            $log = array(
                session ('adminInfo.admin_name'),
                $data['account_name'],
                $data['money'],
                $order_id,
            );
            if ($req->status == 1) {
                OperationLog (session ('adminInfo.admin_id'), 'pass_take', $log);
            } else {
                OperationLog (session ('adminInfo.admin_id'), 'nopass_take', $log);
            }
            $data['reason'] = $datas['reason'];
            $res = $this->addLog ($data, $req->status,$tradetype);
            if ($res < 0) {
                DB::rollback ();//事务回滚
                return responseToJson ($res);
            }
            $db = new \App\Models\Manager;
            if ($req->status == 1) {
                $db->updateMessage ('admin', $data['account_name'], '提款提示', '提款成功，提款金额:' . $data['money'], 2);
            } else {
                $db->updateMessage ('admin', $data['account_name'], '提款提示', '提款失败，提款金额:' . $data['money'], 2);
            }
            $clear = Withdraw_rule::withDraw ($data['account_identity']);//更新目标流水增量记录
            if (!$clear)
                DB::rollback ();
            DB::commit ();//事务回滚
            return responseToJson ($res);
        }
    }

    //详情记录
    function addLog($data, $type,$trade_type=5)
    {
        $ac_log = array(
            $data['account_name'],
            $data['money'],
            $data['order_id'],
        );
        $str = 'take_money_';
        if ($type == 2) {
            $str .= 'fail';
            $money_type = 1;
        } else {
            $str .= 'success';
            $money_type = 2;
        }
        $accountDB = new \App\Models\Account_detailed();
        $account = $accountDB->getInfoBy ($data['account_identity']);
        $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', time ()),
            'trade_type' => $trade_type,
            'trade_desc' => vsprintf (trans ('trade.' . $str), $ac_log),
            'status' => $type,
            'money_type' => $money_type,
            'money_cash' => $account['cash'],
            'reason' => $data['reason'],
            'sysetem_user' => session ('adminInfo.admin_name'),
        );
        $moeny_db = new \App\Models\Money_details;//详情表
        return $moeny_db->insertData ($log);
    }

    public function checkMoney(Req $req)
    {
        $idd = $req->account_identity ?? '';
        if (!$idd) return responseToJson (-3020300502);
        return $ret = Withdraw_rule::check ($idd)??0;
    }
}

?>