<?php

namespace App\Http\Controllers\Admin;

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

/**
 *
 */
class RegulationController extends Controller
{
//    private $token='so5j3C150405826059a61b94de9df';
    /**
     * @return 加款扣款
     */
    function index()
    {
        $request = array();
        $request['account_name'] = Request::has ('account_name') ? Request::get ('account_name') : '';
        $dt = \App\Lib\DataTable\DataTable::init ();
        $dt->setDataSource ('/admin/money/getUser');
        $dt->setLang ('money');
        $dt->addColsFields ('id', array('width' => 100));
        $dt->addColsFields ('account_name', array('templet' => '#userRegulation', 'width' => 140));
        $dt->addColsFields ('cash', array('width' => 120));
//		$dt->addColsFields('add_money');
        $dt->addColsFields ('add_money', array('sort' => false, 'templet' => '#add_money'));
        $dt->addColsFields ('cut_money', array('sort' => false, 'templet' => '#cut_money'));
//		$dt->addColsFields('takeoff_money');
//		$dt->setToolBar(array('add','cut'));
        return view ('admin.Regulation/index', $dt->render ($request));
    }

    function add()
    {
        echo 123;
    }

    //查看充值
    function Edit(Req $req)
    {
        $id = $req->id;
        $identity = isset($req->identity)?$req->identity:'';
        $type = $req->type;
        if ((empty($id) || $id < 1) && empty($identity)) {
            echo '请选择加扣款用户';
            abort (404);
        }
        $keyv = empty($id)?2:1;
        $id = empty($id)?$identity:$id;
        $account_db = new \App\Models\Account(); //用户
        $rate = $req->rate ?? 1;
        if (!$req->isMethod ('post')) {
            $data = $account_db->getUserDetails ($id, $keyv, 'account_detailed', 'identity', 'account_identity');
            $data = $data['data'][0];

            return view ('admin.Regulation/edit', ['data' => $data, 'type' => $type]);
        } else {
            $money = $req->money;
            $remark = $req->remark;
            $bate = $req->peize_bate;
            $order_id = $req->order_id;

            if (!is_numeric ($money) || $money < 0) {
                return responseToJson (-3010025022);//提交金额必须为大于0的数字
            }
            if (!is_numeric ($bate) || $money < 0) {
                return responseToJson (-3010025122);//奖励百分比金额必须为大于0的数字
            }
            //验证可操作金额限额
            $limitroot = new \App\Models\System_user();
            $limitmoney = $limitroot->checkActMoney ($money);
            if ($limitmoney < 0) {
                return responseToJson ($limitmoney);
            }

            DB::beginTransaction ();
            $prize_money = $money * $bate / 100;//奖励金额
            $admin_name = session ('adminInfo.admin_name') ? session ('adminInfo.admin_name') : '来自接口';
            //获取用户信息
            $account_data = $account_db->getUserDetails ($id, $keyv, 'account_detailed', 'identity', 'account_identity');
            $account_data = current ($account_data['data']);

            //检测提交数据
            $res_data = $this->CheckaddMoney ($account_data['identity'], $money);
            if ($res_data < 0) {
                DB::rollback ();
                return responseToJson ($res_data);
            }
            $data = array(
                'account_name' => $account_data['account_name'],
                'account_identity' => $account_data['identity'],
                'money' => $money,
                'reason' => $remark,
                'sysetem_user' => $admin_name,
            );
            if ($type == 1) {
                //充值处理
                //资金统计记录
                $cdata = $data;
                $cdata['pass_time'] = date ('Y-m-d', time ());
                $res = \App\Models\Money_count::AddCountinfo ($cdata, 'save');

                if ($res < 0) {
                    DB::rollback ();
                    return responseToJson ($res);
                }
                //加钱
                $money_cash = $account_data['cash'] + $money;
                $data['money_cash'] = $money_cash;
                $data['rate'] = $rate;
                $trade_type = 11;
                /***********活动加款**************/
                $reason = str_replace ('用于活动', '!@#$', $data['reason']);
                if (strstr ($reason, '!@#$')) {
                    $trade_type = 12;
                    $prize_money = '';
                    //添加流水倍率数据
                    $res_data = Withdraw_rule::updateRule ($account_data['identity'], $money, $rate);
                    if ($res_data < 0) {
                        DB::rollback ();
                        return responseToJson ($res_data);
                    }
                }
                $order_id = $this->addMoney ($data, $type, $trade_type, $order_id, '', '', $rate);//加钱
                if ($order_id < 0) {
                    DB::rollback ();
                    return responseToJson ($order_id);
                }
                //赠送金额
                if (!empty($prize_money)) {
                    $data['money'] = $prize_money;//重置金额
                    $trade_type = 13;
                    /***********活动加款**************/
                    $reason = str_replace ('用于活动', '!@#$', $data['reason']);
                    if (strstr ($reason, '!@#$')) {
                        $trade_type = 12;
                    }
                    $data['money_cash'] = $data['money_cash'] + $prize_money;
                    $res = $this->addMoney ($data, $type, $trade_type, '', $prize_money, $order_id, $rate);//充值赠送
                    if ($res < 0) {
                        DB::rollback ();
                        return responseToJson ($res);
                    }
                }
                $prize_money = empty($prize_money) ? 0 : $prize_money;
                $log = array(
                    session ('adminInfo.admin_name'),
                    $data['account_name'],
                    $money,
                    $prize_money,
                    $data['reason'],
                    $order_id,
                    $rate,
                );
                OperationLog (session ('adminInfo.admin_id'), 'add_money', $log);
            } else {
                $order_id = OrderID();
                $money_cash = $account_data['cash'] - $money;
                $data['money_cash'] = $money_cash;
                
                $res = $this->cutMoney ($data, $type, $order_id);
                if ($res < 0) {
                    DB::rollback ();
                    return responseToJson ($res);
                }
               /*if(!empty($prize_money)){
                   $data['money']=$prize_money;//重置金额
                   $res=$this->cutMoney($data,$type,$order_id);
                   if($res<0){
                       return responseToJson($res);
                   }
               }*/
                $log = array(
                    session ('adminInfo.admin_name'),
                    $data['account_name'],
                    $data['money'],
                    $data['reason'],
                    $res,
                );
                OperationLog (session ('adminInfo.admin_id'), 'cut_money', $log);
            }
            $session_data = array(
                'time' => date ('Y-m-d H::s'),
                'money' => $data['money'],
                'user_id' => $data['account_identity'],
                'user_name' => $data['account_name'],
            );
            event (new \App\Events\MoneyRecharge($session_data));
            DB::commit ();
            return responseToJson (1);
        }
    }

    /**
     * 加钱函数
     * @param array $data
     * @param int $type
     * @param int $trade_type
     * @param string $order_id
     * @param string $prize_money
     * @param string $parent_order_id
     * @param int $rate
     * @return int|string
     */
    private function addMoney(array $data, $type, $trade_type, $order_id = '', $prize_money = '', $parent_order_id = '', $rate)
    {
        $accountDB = new \App\Models\Account_detailed(); //用户详情
        $order_id = $this->rechargeLog ($data, $order_id, $prize_money, $parent_order_id, $rate);//充值记录
        if ($order_id < 0) {
            return $order_id;
        }
        $detail=$data;
        $detail['rate']=$rate;
        $res = $this->dataLog ($detail, $order_id, $type, $trade_type);
        if ($res < 0) {
            return $res;
        }
        $res2 = $accountDB->addMoney ($data['account_identity'], $data['money']);
        if ($res2 < 0) {
            return $res2;
        }
        $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);
        return $order_id;
    }

    /**
     * 扣钱函数
     * @param array $data 扣款详情数组
     * @param int $type 操作类型，此处为2
     * @param string $order_id 扣款订单号
     * @return int|string  处理结果,成功返回扣款订单号，失败返回错误号
     */
    private function cutMoney(array $data, int $type, string $order_id)
    {
        $accountDB = new \App\Models\Account_detailed(); //用户详情
        $trade_type = 9;
        $reason = str_replace ('用于活动', '!@#$', $data['reason']);
        if (strstr ($reason, '!@#$')) {
            $trade_type = 12; //活动扣款
        }
        $res = $this->dataLog ($data, $order_id, $type, $trade_type);//扣款

        if ($res < 0) {
            return $res;
        }
        $res2 = $accountDB->costMoney ($data['account_identity'], $data['money']);
        if ($res2 < 0) {
            return $res2;
        }
        return $order_id;
    }

    /**
     * 充值记录
     * @param array $data 充值记录数据
     * @param string $order_id 充值订单ID
     * @param float $prize_money 充值金额
     * @param string $parent_order_id 父订单ID
     * @param int $rate 流水倍数要求
     * @return int|string 充值成功返回充值订单号
     */
    private function rechargeLog(array $data, $order_id = '', $prize_money = 0.00, $parent_order_id = '', $rate)
    {
        $recharge = new \App\Models\Money_recharge(); //充值
        $re_data = $data;

        if (strstr ($data['reason'], '用于活动')) {
            $re_data['recharge_type'] = '活动充值';
            if (!empty($parent_order_id)) {
                $re_data['reason'] = $parent_order_id;
            }
        } else {
            $re_data['recharge_type'] = '后台充值';
        }
        if (!empty($prize_money)) {
            $re_data['recharge_type'] .= '赠送';
        }
        $re_data['status'] = 1;
        $re_data['apply_time'] = date ('Y-m-d H:i:s', time ());
        $re_data['complete_time'] = date ('Y-m-d H:i:s', time ());
        $re_data['rate'] = $rate;
        if (empty($order_id)) {
            $re_data['order_id'] = OrderID ();
        } else {
            $re_data['order_id'] = $order_id;
        }
        $order_id = $recharge->addMoney ($re_data);
        return $order_id;
    }


    /**
     * 添加充值/扣款详情记录函数
     * @param array $data 详情数据数组
     * @param mixed $order_id 充值/扣款订单号
     * @param int $type 订单类别[1=>'充值',2=>'扣款'];
     * @param int $trade_type 交易类型
     * @return int|string 成功返回当前详单号，失败返回错误号
     */
    private function dataLog(array $data, $order_id, $type, $trade_type)
    {
        if (empty($order_id)) {
            $order_id = OrderID ();
        }
        $rate = 1;
        $money_db = new \App\Models\Money_details;//资金详情表
        if (isset($data['rate'])) {
            $rate = $data['rate'];
            unset($data['rate']);
        }
        $deal_data = $data;
        $deal_data['money_type'] = $type;
        $deal_data['money_time'] = date ('Y-m-d H:i:s', time ());
        $deal_data['trade_id'] = $order_id;
        $deal_data['trade_type'] = $trade_type;
        $admin_name = session ('adminInfo.admin_name');
        $admin_name = isset($admin_name) ? $admin_name : '来自接口' . GETIP ();
        $deal_data['sysetem_user'] = $admin_name;


        if ($trade_type == 11) {
            $deal_data['trade_desc'] = sprintf (trans ('trade.admin_add_momey'), $admin_name, $data['account_name'], $data['money'], $order_id, $rate);
        } else if ($trade_type == '13') {
            $deal_data['trade_desc'] = sprintf (trans ('trade.admin_prize_money'), $admin_name, $data['account_name'], $data['money'], $order_id, $rate);
        } else if ($trade_type == '9') {
            $deal_data['trade_desc'] = sprintf (trans ('trade.admin_cut_momey'), $admin_name, $data['account_name'], $data['money'], $order_id, $rate);
        } else if ($trade_type == '14') {
            $deal_data['trade_desc'] = sprintf (trans ('trade.admin_rimit_money'), $admin_name, $data['account_name'], $data['money'], $order_id, $rate);
        } else if ($trade_type == '12') {
            $deal_data['trade_desc'] = sprintf (trans ('trade.admin_active_money'), $admin_name, $data['account_name'], $data['money'], $order_id, $rate);
        }

        $deal_data['status'] = 1;
        $res = $money_db->insertData ($deal_data);
        if ($res < 0) {
            return $res;
        }
        return $order_id;
    }

    /**
     * 对外充值或者扣款接口
     * @param Req $req
     * @return mixed
     */
    public function AddOrCutMoney(Req $req)
    {
        $user_name = $req->name;
        $type = intval ($req->type) ? $req->type : '';
        $money = $req->money;
        $remark = $req->remark;
        $bate = floatval ($req->peize_bate) ? $req->peize_bate : 0;
        $order_id = $req->order_id;
        $time = $req->time;
        $sign = $req->sign;
        $rate = $req->rate ?? 1;

        $parent_order_id = $req->parent_order_id ?? '';
        if (empty($user_name) || empty($money) || empty($type)) {
            return responseToJson (-3010229022);//必要项不能为空
        }
        if (!is_numeric ($money) || $money < 0) {
            return responseToJson (-3010025022);//提交金额必须为大于0的数字
        }
        if (!is_numeric ($bate) || $bate < 0) {
            return responseToJson (-3010025122);//奖励百分比金额必须为大于0的数字
        }
        //时间检验
        if ($time < (time () - 10)) {
            return responseToJson (-3020035023);//请求超时
        }
        //token校验
        $setInfo_db = new \App\Models\Setinfo;
        $token = $setInfo_db->getInfo (19);
        $token = $token['infocontent'];
        //校验数据
        $ver_data = array(
            'name' => $user_name,
            'type' => $type,
            'money' => $money,
            'peize_bate' => $bate,
            'order_id' => $order_id,
            'time' => $time,
        );
        krsort ($ver_data);
        $right_sign = md5 (http_build_query ($ver_data) . '&token=' . $token);
        if ($right_sign != $sign) {
            return responseToJson (-3020035024);//
        }
        //赠送金额
        $prize_money = ($money * $bate) / 100;
        $prize_money = round ($prize_money, 2);
        //获取用户信息
        $account_db = new \App\Models\Account(); //用户表
        $account_data = $account_db->getUserDetails ($user_name, 3, 'account_detailed', 'identity', 'account_identity');
        if ($account_data < 0) {
            return responseToJson ($account_data);
        }
        $account_data = current ($account_data['data']);
        if (!$account_data) {
            return responseToJson (-30203000202);
        }

        $data = array(
            'account_name' => $account_data['account_name'],
            'account_identity' => $account_data['identity'],
            'money' => $money,
            'reason' => $remark,
            'sysetem_user' => '接口',
        );
        if ($type == 1) {
            //加钱
            $money_cash = $account_data['cash'] + $money;
            $data['money_cash'] = $money_cash;
            $trade_type = 11;
            if (strstr ($data['reason'], '用于活动')) {
                $trade_type = 12;
                $prize_money = '';
            }
            $order_id = $this->addMoney ($data, $type, $trade_type, $order_id, 0, '', $rate);//加钱
            if ($order_id < 0) {
                return responseToJson ($order_id);
            }
            if (!empty($prize_money) && $prize_money > 1) {
                $data['money'] = $prize_money;//重置金额
                $trade_type = 13;
                if (strstr ($data['reason'], '用于活动')) {
                    $trade_type = 12;
                }
                $res = $this->addMoney ($data, $type, $trade_type, '', $prize_money, $parent_order_id, $rate);//赠送
                if ($res < 0) {
                    return responseToJson ($res);
                }
            }
            $prize_money = empty($prize_money) ? 0 : $prize_money;
            $log = array(
                '来自接口IP' . GETIP (),
                $data['account_name'],
                $money,
                $prize_money,
                $data['reason'],
                $order_id,
            );
            OperationLog (0, 'add_money', $log);
        } else {
            $money_cash = $account_data['cash'] - $money;
            $data['money_cash'] = $money_cash;
            $res = $this->cutMoney ($data, $type, $order_id);
            $log = array(
                '来自接口' . GETIP (),
                $data['account_name'],
                $data['money'],
                $data['reason'],
                $res,
            );
            OperationLog (0, 'cut_money', $log);
        }
        $session_data = array(
            'time' => date ('Y-m-d H::s'),
            'money' => $data['money'],
            'user_id' => $data['account_identity'],
            'user_name' => $data['account_name'],
        );
        event (new \App\Events\MoneyRecharge($session_data));
        return responseToJson (1);

    }

    function rechergeMoney($data, $type, $trade_type, $order_id = '', $prize_money = '', $rate = 1)
    {
        //加钱
        $accountDB = new \App\Models\Account_detailed(); //用户详情
        //充值记录
        $order_id = $this->rechargeLog ($data, $order_id, $prize_money, '', $rate);
        if ($order_id < 0) {
            return $order_id;
        }
        if (!empty($prize_money)) {
            $prize_data = $data;
            $prize_data['money'] = $prize_money;//重置金额
            $order_id2 = $this->rechargeLog ($prize_data, $order_id, $prize_money, '', $rate);
            if ($order_id2 < 0) {
                return $order_id2;
            }
        }

        //详情记录
        $res = $this->dataLog ($data, $order_id, $type, $trade_type);
        if ($res < 0) {
            return $res;
        }
        if (!empty($prize_money)) {
            $res2 = $this->dataLog ($prize_data, $order_id, $type, $trade_type);
            if ($res2 < 0) {
                return $res2;
            }
        }
        //加钱
        $res3 = $accountDB->addMoney ($data['account_identity'], $data['money']);
        if ($res3 < 0) {
            return $res3;
        }
        return $order_id;
    }

    function CheckaddMoney($account_id, $money)
    {
        $money_db = new \App\Models\Money_recharge;
        $time = date ('Y-m-d H:i:s', time () - 10);
        return $money_db->checkAdd ($account_id, $money, $time);
    }


}

