<?php


namespace App\Services;


use App\Http\AppFlyerEvent\AppflyerEvent;
use App\Http\helper\Helper;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Models\AgentUser;
use App\Models\PrivateMail;
use App\Models\RecordOperateLog;
use App\Models\RecordScoreInfo;
use App\Models\RecordUserDataStatistics;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class OrderService
{
    protected $FirstCharge = 10;
    protected $FirstChargeGive = 60;

    /**
     * 支付成功  处理逻辑
     * @param $GiftsID // 首冲礼包ID
     * @param $user_id // 用户ID
     * @param $payAmt // 支付金额--元
     * @param $order_sn // 订单号
     */
    public function paySuccess($GiftsID, $user_id, $payAmt, $order_sn)
    {

        $give = $czReason = $cjReason = 0;

        // 判断是不是首冲礼包
        if (!empty($GiftsID)) {

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

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

                // 给服务端更新首冲状态
                DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
                    ->where('UserID', $user_id)
                    ->update(['RechargeGiftTime' => date('Y-m-d H:i:s')]);

                $Gifts = DB::connection('write')->table('QPAccountsDB.dbo.FirstRechargeGifts')->where('GiftsID', $GiftsID)->first();
                $favorable_price = $Gifts->AllScore;
                $give = $Gifts->ExtraScore;
                $Recharge = $Gifts->Price;
                $czReason = 50;
                $cjReason = 51;
            } elseif ($GiftsID > 100 && $GiftsID < 200) {  // 周卡
                $CardID = $GiftsID - 100;
                $WeeklyCard = DB::connection('write')->table('QPPlatformDB.dbo.MonthCard')->where('CardID', $CardID)->first();
                $favorable_price = $WeeklyCard->FirstReward / 100;
                $Recharge = $WeeklyCard->Price;

            } elseif ($GiftsID == 200) {        // 10元首充

                $RechargeNum = $this->FirstCharge * NumConfig::NUM_VALUE;
                // 执行首充存储
                $result = StoredProcedure::FirstCharge($user_id, $RechargeNum, 2)[0]->Ret ?? 0;
                Log::info('10元首充返回结果：' . $result);
                if ($result != 0) {
                    return 'fail';
                }
                $give = $this->FirstChargeGive * NumConfig::NUM_VALUE;  // 赠送
                $favorable_price = $this->FirstCharge;   // 充值
                $Recharge = $this->FirstCharge;     // 充值
                $czReason = 1;

            }elseif ($GiftsID == 300){ // 谷歌支付

                $give = 0;  // 赠送
                $favorable_price = $payAmt;   // 充值
                $Recharge = $payAmt;     // 充值
                $czReason = 1;
            }

        } else { // 普通订单
            // 查找送的金额
            $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('money', $payAmt)->select('favorable_price', 'give')->first();
            $Recharge = $recharge_gear->favorable_price;
            $give = $recharge_gear->give;
            $favorable_price = $Recharge + $give;
            $czReason = 1;
            $cjReason = 45;

        }

//        // 发送邮件给玩家
//        $TitleString = 'Transacción de moedas completada';
//        $TextString = "
//Adquira adereços:{$favorable_price} Moedas
//Número do pedido:{$order_sn}
//Se você tiver alguma dúvida, entre em contato com o atendimento ao cliente.
//";
//        PrivateMail::sendMail(2, $user_id, $TitleString, $TextString, '', $order_sn, $payAmt);
        PrivateMail::PaySuccess($user_id,$payAmt,$favorable_price,$order_sn);

        // 增加充值记录
        $query = DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
            ->where('UserID', $user_id)
            ->value('Recharge');

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

        $favorable_price = $favorable_price * 100;
        $firstScore = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->value('Score');
        $Score = $favorable_price + $firstScore;
        Log::info('变化金币' . $Score);

        // 记录订单变化后金币
        DB::connection('write')->table('agent.dbo.order')
            ->where('order_sn', $order_sn)
            ->update(['after_amount' => $Score]);

        // 不是周卡的时候执行
        if ($GiftsID < 100 || $GiftsID >= 200) {
            // 增加用户金币
            DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->increment('Score', $favorable_price);
        }


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

        // 充值推广佣金
        (new AgentUser())->reward($user_id, $payAmt, $order_sn);

        // 增加用户充值 值
        RecordUserDataStatistics::updateOrAdd($user_id, 0, $payAmt);

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


        $dataToJson = [
            'userID' => $user_id,
            'payAmt' => $payAmt,
            'favorable_price' => $favorable_price,
            'Score' => $Score,
            'GiftsID' => $GiftsID
        ];
        $dataToJson = \GuzzleHttp\json_encode($dataToJson);

        Log::info("支付成功回调 ：" . $dataToJson);

        // 周卡 -- 执行存储过程
        if (!empty($GiftsID) && $GiftsID > 100 && $GiftsID < 200) {
            $CardID = (int)$GiftsID - 100;
            StoredProcedure::BuyMonthCard($user_id, $CardID, $order_sn);

            // 开始执行时间
            $startTime = Helper::millisecond();
            Log::info('GSP_GP_BuyMonthCard 执行时间：' . ((Helper::millisecond() - $startTime) / 1000));
        }

        # 链接redis -- 防止三方重复回调
        Redis::lPush('payService', $dataToJson);

        // }

        return true;
    }


}
