<?php


namespace App\Http\logic\api;


use App\Http\helper\CreateOrder;
use App\Http\helper\HttpCurl;
use App\Models\AgentUser;
use App\Models\Order;
use App\Models\RecordOperateLog;
use App\Models\RecordScoreInfo;
use App\Services\FirstRechargeGifts;
use App\Services\Pay;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Log;

class PayLogic extends BaseApiLogic
{
    protected $pay_bankcode = 924;

    public function pay($userId, $pay_amount, $pay_productname,$GiftsID)
    {
        // 验证支付金额

        if ($pay_amount < 0) {
            $this->error = '非法支付金额';
            return false;
        }

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

        // 购买礼包
        $giftService = new FirstRechargeGifts();
        $bool = $giftService->buyGifts($GiftsID, $userId);
        if ($bool === false) {
            $this->error = $giftService->getError();
            return false;
        }

        $now = date('Y-m-d H:i:s');
        $config = config('pay.pay_api');
        $service = new Pay();
        $service->setPayAmount($pay_amount);
        $service->setPayNotifyurl($config['service_notify']);    //   回调地址 - 异步
        $service->setPayCallbackurl($config['web_notify']);  //   回调地址 - 同步
        $service->setPayOrderid($order_sn);      // 订单ID

        $service->setPayApplydate($now);
        $service->setPayBankcode($this->pay_bankcode);

        $data = $service->allData();

        $sign = $service->sign($data);

        $create_data = $data;

        $create_data['pay_productname'] = $pay_productname;
        // 生成订单信息
        $logic = new OrderLogic();
        $create_data['pay_amount'] = $pay_amount * 100; // 元转化分
        $create_order = $logic->create($create_data, $userId, 0);

        $data['pay_md5sign'] = $sign;

        $result = $service->curlPost($data, 5, 'array');

        $to_arr = json_decode($result, true);


        if (isset($to_arr['status']) && $to_arr['status'] == 'error') {
            $this->error = $to_arr['msg'] ?? '';
            return false;
        }

        return $result;
    }

    // 异步回调
    public function notify($data)
    {
        try {
            $custOrderNo = $data['orderid'];

            $sign = $data['sign'];

            unset($data['sign']);
            $service = new Pay();
            // 查询订单信息

            $order = Order::where('order_sn', $custOrderNo)->first();

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

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

            // 验证签名
            $verify_sign = $service->sign($data);

            if ($verify_sign != strtoupper($sign)) {
                Log::info('签名错误2');
                return 'fail';
            }

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

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

            $ordStatus = $data['returncode'];

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

                    // 判断是不是首冲礼包
                    $GiftsID = $order->GiftsID ?? '';

                    if (!empty($GiftsID)) {
                        $GiftsData = [
                            'UserID' => $order->user_id,
                            'GiftsID' => $GiftsID,
                            'BuyCount' => 1,
                            'LastBuyDate' => date('Y-m-d H:i:s')
                        ];
                        // 卖出去数量 +1
                        DB::table('QPAccountsDB.dbo.FirstRechargeGifts')->where('GiftsID', $GiftsID)->increment('TotalCount');
                        $userGifts = DB::table('QPAccountsDB.dbo.UserFirstRechargeGifts')->where('UserID', $order->user_id)->where('GiftsID', $GiftsID)->first();

                        if ($userGifts) {
                            DB::table('QPAccountsDB.dbo.UserFirstRechargeGifts')->where('UserID', $order->user_id)->where('GiftsID', $GiftsID)->increment('BuyCount');
                        } else {
                            DB::table('QPAccountsDB.dbo.UserFirstRechargeGifts')->insert($GiftsData);
                        }

                        $Gifts = DB::table('QPAccountsDB.dbo.FirstRechargeGifts')->where('GiftsID', $GiftsID)->first();
                        $favorable_price = $Gifts->AllScore;
                        $give = $Gifts->ExtraScore;
                        $Recharge = $Gifts->Price;
                        $czReason = 50;
                        $cjReason = 51;
                    } else {
                        // 查找送的金额
                        $recharge_gear = DB::table('agent.dbo.recharge_gear')->where('money', $data['amount'])->select('favorable_price', 'give')->first();
                        $Recharge = $recharge_gear->favorable_price;
                        $give = $recharge_gear->give;
                        $favorable_price = $Recharge + $give;
                        $czReason = 1;
                        $cjReason = 45;
                    }


                    // 发送邮件给玩家
                    $recharge = $favorable_price * 100;
                    $bonus = '30000,' . $recharge;
                    $data = [
                        'MailType' => 2,
                        'MailStatus' => 1,
                        'UserID' => (int)$order->user_id,
                        'CreateTime' => date('Y-m-d H:i:s', time()),
                        'TitleString' => 'This is the chip coins you get from Recharge',
                        'TextString' => "Order number：{$order->order_sn}",
                        'BonusString' => '',
                        'type' => 1,
                        'order_sn' => $order->order_sn,
                        'amount' => $favorable_price

                    ];

                    $result = DB::table('QPAccountsDB.dbo.PrivateMail')->insert($data);

                    // 增加充值记录

                    $query = DB::table('QPAccountsDB.dbo.YN_VIPAccount')
                        ->where('UserID', $order->user_id)
                        ->value('Recharge');
                    if ($query) {
                        DB::table('QPAccountsDB.dbo.YN_VIPAccount')
                            ->where('UserID', $order->user_id)
                            ->increment('Recharge',$data['amount']);
                    } else {
                        DB::table('QPAccountsDB.dbo.YN_VIPAccount')
                            ->where('UserID', $order->user_id)
                            ->insert(['Recharge' => $data['amount'], 'UserID' => $order->user_id]);
                    }

                    // 增加用户金币变化记录
                    RecordScoreInfo::addScore($order->user_id, ($Recharge * 100), $czReason); #充值
                    RecordScoreInfo::addScore($order->user_id, ($give * 100), $cjReason); #赠送彩金


                    // 充值推广佣金
                    (new AgentUser())->reward($order->user_id, $data['amount'], $custOrderNo);

                    // 增加用户金币
                    $firstScore = DB::table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $order->user_id)->value('Score');
                    $Score = $recharge + $firstScore;
                    Log::info('变化金币' . $Score);
                    DB::table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $order->user_id)->increment('Score',$recharge);

                    // 服务器通知

                    $url = config('transfer.stock')['url'] . 'notifyPay';

                    $data = [
                        'userid' => $order->user_id,
                        'getScore' => $recharge,
                        'score' => $Score
                    ];

                    (new HttpCurl())->service($url, $data);



                    // 埋点记录 -- 支付成功
                    RecordOperateLog::add_log(10222, $order->user_id, 0);
                    // 埋点记录 -- 支付卢比
                    RecordOperateLog::add_log(30102, $order->user_id, $recharge);
                    break;

                default :    // 失败
                    $body['pay_status'] = 2;
                    $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('订单更新失败2');
                return 'fail';
            }

            Log::info('success2');
            exit("ok");
        } catch (\Exception $exception) {
            $this->error = $exception->getMessage();
            return 'false';
        }


    }

    // 同步回调
    public function sync_notify($data)
    {

        $custOrderNo = $data['orderid'];
        $sign = $data['sign'];
        unset($data['sign']);

        $service = new Pay();

        // 查询订单信息
        $order = Order::where('order_sn', $custOrderNo)->first();

        if (!$order) {
            Log::info('同步回调：订单不存在2');
            return 'fail';
        }

        if (!empty($order['pay_at']) || !empty($order['finished_at'])) {
            Log::info('同步回调：订单已支付2');
            return 'fail';
        }

        // 验证签名
        $verify_sign = $service->sign($data);

        if ($verify_sign != strtolower($sign)) {
            Log::info('同步回调：签名错误2');
            return 'fail';
        }

        if ($data["returncode"] == "00") {
            $str = "交易成功！订单号：" . $data["orderid"];
            exit($str);
        } else {
            exit('Fail');
        }
    }

}
