<?php


namespace App\Http\Controllers\Admin;


use App\dao\Pay\PayController;
use App\Facade\TableName;
use App\Http\helper\CreateOrder;
use App\Http\helper\NumConfig;
use App\Http\logic\api\OrderLogic;
use App\Jobs\Order;
use App\Models\PrivateMail;
use App\Models\RecordUserDataStatistics;
use App\Services\AuPay;
use App\Services\FirstRechargeGifts;
use App\Services\LogDayStatisticalByDayAndChannel;
use App\Services\MonthCard;
use App\Services\OrderService;
use App\Services\OrderServices;
use App\Services\StoredProcedure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PayTestController
{
    // 模拟支付回调
    public function pay(Request $request)
    {
        $bool = env('SURROUNDINGS') ?? false;
        if (!$bool) {
            return 'Please switch environment';
        }

        $GameID = $request->userId ?: '';
        $GiftsID = $request->GiftsID ?: '';
        $payAmt = $request->payAmt ?: '';
//        $AdId = $request->AdId ?: 'efa7d051-2f29-429b-b26e-d73b64604673';
        $AdId = $request->AdId ?: 'd206cefddda8b6b209428cd5b8129aab';
        $eventType = $request->eventType ?: 1;

        $GiftsID = empty($GiftsID) ? 0 : $GiftsID;
        $payAmt = empty($payAmt) ? 100 : $payAmt;


        $userId = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('GameID', $GameID)
            ->value('UserID');
        if (empty($userId)) return '缺少用户ID';
        if (empty($payAmt)) return '缺少支付金额';

        // 礼包类型验证
        $PayVerify = new PayController();
        $pay_amount = $PayVerify->verify($userId, $GiftsID, $payAmt);
        if ($pay_amount === false) return apiReturnFail($PayVerify->getError());


        $orderSn = CreateOrder::order_sn($userId);

        $post = [
            'orderid' => $orderSn,
            'prdOrdNo' => '',
            'ordStatus' => 'success',
            'payAmt' => $payAmt * 100,
        ];

        // 生成订单信息
        $logic = new OrderLogic();
        $logic->orderCreate($orderSn, $post['payAmt'], 'TestPay', $userId, '', $GiftsID,$AdId,$eventType);

        return $this->notify($post);
    }

    public function notify($post)
    {

        $order_sn = $post['orderid'];

        try {
            // 查询订单信息
            $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();

            if (!$order) return '订单不存在';

            if (!empty($order->pay_at) || !empty($order->finished_at)) return '订单已支付';

            $body = [
                'payment_sn' => $post['prdOrdNo'],
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $apply_data = [
                'order_id' => $order->id,
                'payment_sn' => $post['prdOrdNo'],
                'payment_code' => 'TestPay',
                'return' => \GuzzleHttp\json_encode($post),
                'is_error' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $ordStatus = $post['ordStatus'];
            $GiftsID = $order->GiftsID ?: '';
            $userID = $order->user_id ?: '';
            $AdId = $order->AdId ?: '';
            $eventType = $order->eventType ?: '';
            $payAmt = (int)$post['payAmt'] / NumConfig::NUM_VALUE;

            // 说明:除了成功，失败和退款状态,都可以认为是处理中
            switch ($ordStatus) {
                case 'success':    // 支付成功

                    $body['pay_status'] = 1;
                    $body['pay_at'] = date('Y-m-d H:i:s');
                    $body['finished_at'] = date('Y-m-d H:i:s');
                    // 获取金额
                    $service = new OrderServices();
                    [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmt);
                    // 增加充值记录
                    [$Score] = $service->addRecord($userID, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason,$AdId,$eventType);

                    // 成功处理回调
                    Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID,$order_sn]);
                    break;
                case 'error':    // 支付失败
                    $body['pay_status'] = 2;
                    $apply_data['is_error'] = 1;
                    break;
            }

            $order_up = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->update($body);
            $apply = DB::connection('write')->table('agent.dbo.payment_apply')->insert($apply_data);
            if (($order_up && $apply) != true) return '订单更新失败';

            exit('OK');
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }


    // 订单提现状态修改  完成修改为订单失败
    public function recovery(Request $request)
    {
        // +---------------------------------------------------------
        // 增加用户提现
        // +---------------------------------------------------------

//        $custOrderNo = $request->custOrderNo ?? '';
//        if (empty($custOrderNo)) {
//            return apiReturnFail('订单号为空！');
//        }
//        $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $custOrderNo)->first();
//
//        $withdraw_data = [
//            'State' => 6,
//        ];
//
//        // 增加提现记录
//        $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $query->UserID)->first();
//        $TakeMoney = $query->WithDraw + $query->ServiceFee;
//
//        if ($first) {
//            DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $query->UserID)->increment('TakeMoney', $TakeMoney);
//        }
//
//        $RecordData = [
//            'before_state' => 2,
//            'after_state' => 6,
//        ];
//
//        // 添加用户提现操作记录
//        DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
//
//        //DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->where('order_sn', $custOrderNo)->delete();
//        DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
//        // 返还用户提现额度
//        $user_id = $query->UserID;
//        $WithDraw = $query->WithDraw + $query->ServiceFee;
//        DB::connection('write')->table('QPAccountsDB.dbo.AccountWithDrawInfo')->where('UserID', $user_id)->increment('HistoryWithDraw', $WithDraw);
//        DB::connection('write')->table('QPAccountsDB.dbo.AccountWithDrawInfo')->where('UserID', $user_id)->decrement('Win', $WithDraw);
//        return apiReturnSuc();


        // +---------------------------------------------------------
        // 扣除用户提现
        // +---------------------------------------------------------
        $custOrderNo = $request->custOrderNo ?? '';
        if (empty($custOrderNo)) {
            return apiReturnFail('订单号为空！');
        }
        $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $custOrderNo)->first();

        if ($query->State != 2) {
            return apiReturnFail('订单不是已完成！或者已经处理过');
        }

        $withdraw_data = [
            'State' => 6,
        ];

        // 增加提现记录
        $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $query->UserID)->first();
        $TakeMoney = $query->WithDraw + $query->ServiceFee;

        if ($first) {
            DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $query->UserID)->decrement('TakeMoney', $TakeMoney);
        }


        // 免审的时候，修改免审状态
        $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $custOrderNo)->first();
        if ($withdrawal_position_log) {
            DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $custOrderNo)->update(['take_effect' => 1]);
        }

        $RecordData = [
            'before_state' => 2,
            'after_state' => 6,
        ];

        // 添加用户提现操作记录
        DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);

        DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->where('order_sn', $custOrderNo)->delete();
        DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);

        $msg = 'Liquidation failure';   // 清算失败

        $user_id = $query->UserID;
        $WithDraw = $query->WithDraw + $query->ServiceFee;
        $bonus = '30000,' . $WithDraw;
        $TitleString = 'Your withdrawal order application failed.';
        $TextString = "1、Your withdrawal order： {$custOrderNo} application failed.
2、Reasons for order submission failure:{$msg}
3、This is the withdrawal amount you requested, please collect it as soon as possible.
4、If you have any questions, please contact customer service.
";

        PrivateMail::sendMail(2, $user_id, $TitleString, $TextString, $bonus, $custOrderNo, $WithDraw, 2);

        // 返还用户提现额度
        DB::connection('write')->table('QPAccountsDB.dbo.AccountWithDrawInfo')->where('UserID', $user_id)->decrement('HistoryWithDraw', $WithDraw);
        DB::connection('write')->table('QPAccountsDB.dbo.AccountWithDrawInfo')->where('UserID', $user_id)->increment('Win', $WithDraw);


        return apiReturnSuc();
    }

    // 用户提现成功
    public function cashNotify(Request $request)
    {
        // +---------------------------------------------------------
        // 用户提现成功
        // +---------------------------------------------------------
        $custOrderNo = $request->custOrderNo ?? '';
        $orderStatus = $request->orderStatus ?: 1;  # 1.成功 2.失败
        if (empty($custOrderNo)) {
            return apiReturnFail('订单号为空！');
        }

        $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $custOrderNo)->first();

        if (!$query) {
            Log::info('订单不存在');
            return 'fail';
        }

        if ($query->State != 5 && $query->State != 7 && $query->State != 1) {     // 不是待支付订单 -- 或者第三方清算中  返回
            Log::info('订单状态已完成');
            return 'fail';
        }

        $UserID = $query->UserID;
        $TakeMoney = $query->WithDraw + $query->ServiceFee;

        $notify_data = [
            'state' => 1,
            'finish_at' => date('Y-m-d H:i:s'),
            'extra' => '',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'order_sn' => $custOrderNo,
            'amount' => $TakeMoney,
        ];

        Log::info('测试提现结果：' . $orderStatus);

        switch ($orderStatus) {
            case 1:
                Log::info('提现成功');

                $withdraw_data = [
                    'State' => 2,
                    'agent' => 5
                ];

                // 增加提现记录
                $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();


                if ($first) {
                    DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $query->UserID)->increment('TakeMoney', $TakeMoney);
                } else {
                    DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
                }


                // 免审的时候，修改免审状态
                $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $custOrderNo)->first();
                if ($withdrawal_position_log) {
                    DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $custOrderNo)->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
                }

                $ServiceFee = $query->ServiceFee;
                // 增加用户提现值
                RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);

                // 给用户发邮件
                PrivateMail::successMail($UserID, $custOrderNo, $TakeMoney);
                break;

            case 0:

                $withdraw_data = [
                    'State' => 7,
                    'agent' => 5
                ];

                $notify_data = [
                    'state' => 2,
                ];
                break;

            case 2: # 提现失败

                // 发送邮件给玩家
                if (isset($post['failMessage'])) {
                    $msg = $post['failMessage'];
                } else {
                    $msg = 'Liquidation failure';   // 清算失败
                }

                $bonus = '30000,' . $TakeMoney;
                $TitleString = 'Your withdrawal order application failed.';
                $TextString = "1、Your withdrawal order： {$custOrderNo} application failed.
2、Reasons for order submission failure:{$msg}
3、This is the withdrawal amount you requested, please collect it as soon as possible.
4、If you have any questions, please contact customer service.
";

                PrivateMail::sendMail(2, $UserID, $TitleString, $TextString, $bonus, $custOrderNo, $TakeMoney, 2);

                // 修改订单状态为失败
                $withdraw_data = [
                    'State' => 6,
                    'agent' => 5
                ];

                $notify_data = [
                    'state' => 2,
                ];

                break;
        }

        $RecordData = [
            'before_state' => $query->State,
            'after_state' => $withdraw_data['State'] ?? 0,
            'RecordID' => $query->RecordID,
            'create_at' => date('Y-m-d H:i:s'),
            'update_at' => date('Y-m-d H:i:s')
        ];

        // 添加用户提现操作记录
        DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);

        DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->updateOrInsert(['order_sn' => $custOrderNo], $notify_data);
        DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $custOrderNo)->update($withdraw_data);

        if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
            // 单控标签
            StoredProcedure::user_label($UserID, 2, $TakeMoney);
            // 渠道后台埋点
            (new LogDayStatisticalByDayAndChannel())->updateData($UserID, 2);
        }
        return apiReturnSuc();
    }


    public function notify1($post)
    {

        try {

            $custOrderNo = $post['custOrderNo'];

            // 查询订单信息
            $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $custOrderNo)->first();

            if (!$order) {
                Log::info('订单不存在');
                return 'fail';
            }

            if (!empty($order->pay_at) || !empty($order->finished_at)) {
                Log::info('订单已支付');
                return 'fail';
            }


            $body = [
                'payment_sn' => $post['prdOrdNo'],
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $apply_data = [
                'order_id' => $order->id,
                'payment_sn' => $post['prdOrdNo'],
                'payment_code' => 'SerPayMent',
                'return' => \GuzzleHttp\json_encode($post),
                'is_error' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $ordStatus = $post['ordStatus'];
            $amount = $post['payAmt'];

            // 说明:除了成功，失败和退款状态,都可以认为是处理中
            switch ($ordStatus) {
                case 01:    // 支付成功
                    $body['pay_status'] = 1;
                    $body['pay_at'] = date('Y-m-d H:i:s');
                    $body['finished_at'] = date('Y-m-d H:i:s');

                    $payAmt = $amount / 100;

                    $GiftsID = $order->GiftsID ?: '';
                    $userID = $order->user_id ?: '';
                    (new OrderService())->paySuccess($GiftsID, $userID, $payAmt, $custOrderNo);


                    break;
                case 00:    // 未交易
                    $body['pay_status'] = 4;
                    $apply_data['is_error'] = 1;
                    break;
                case 02:    // 失败
                    $body['pay_status'] = 2;
                    $apply_data['is_error'] = 1;
                    break;
                case 03:    // 被拒绝
                    $body['pay_status'] = 3;
                    $apply_data['is_error'] = 1;
                    break;
                case 05: // 取消支付
                    $body['pay_status'] = 5;
                    $apply_data['is_error'] = 1;
                    break;
                case 06:    // 未支付
                    $body['pay_status'] = 6;
                    $apply_data['is_error'] = 1;
                    break;
                case 07: // 退款
                    $body['pay_status'] = 7;
                    $apply_data['is_error'] = 1;
                    break;
            }
            $order_up = DB::table('agent.dbo.order')
                ->where('order_sn', $custOrderNo)
                ->update($body);

            $apply = DB::table('agent.dbo.payment_apply')
                ->insert($apply_data);

            if (($order_up && $apply) != true) {
                Log::info('订单更新失败');
                return 'fail';
            }

            Log::info('success');
            echo 'SC000000';
            return 'SC000000';
        } catch (\Exception $exception) {
            Log::info('支付失败11 ' . $exception->getMessage());
            return apiReturnFail($exception->getMessage());
        }
    }

}
