<?php

namespace app\admin\controller\notify;

use app\admin\service\notify\RechargeService;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberAccountList;
use app\model\Order;
use app\model\PayDetail;
use support\Db;
use support\exception\BusinessException;
use support\Log;
use support\Request;
use Tinywan\Jwt\JwtToken;
use Webman\Event\Event;

class RechargeController
{
    /**
     * @Desc 计划任务
     * @Author Gorden
     * @Date 2024/5/29 11:31
     *
     * @return void
     */
//    public function disposePaySuccess()
//    {
////        $unix = strtotime(date("Y-m-d H:i",strtotime("-1 minute")).':00');
//        $payDetails = PayDetail::where('pay_category', 'RECHARGE')
//            ->where('pay_status', 'SUCCESS')
//            ->where(function ($query) {
//                $query->whereRaw("JSON_EXTRACT(`pay_extend_json`, '$.notify') IS NULL")
//                    ->orWhereJsonDoesntContain('pay_extend_json->notify', 'success');
//            })
//            ->get()
//            ->toArray();
//        if (!$payDetails) {
//            return;
//        }
//
//        foreach ($payDetails as $payDetail) {
//            $this->paySuccess($payDetail['pay_id']);
//        }
//    }


    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/8/19 13:33
     *
     * @param Request $request
     * @return \support\Response
     */
    public function paySuccess(Request $request)
    {
        $data = $request->post();
        if (is_json($data)) {
            $data = json_decode($data, true);
        }
        _syslog("APP充值", "APP充值回调开始", $data, $data, 1001);
        if (!$data['pay_id']) {
            return json_fail('参数异常');
        }
        try {
            $result = $this->disposePaySuccess($data['pay_id']);
            _syslog("APP充值", "APP处理完成", $data, $data, 1001);

            return $result;
        } catch (BusinessException $e) {
            _syslog("APP充值", "APP充值失败", $data, $data, 1001);
            return json_fail("处理失败");
        } catch (\Exception $e) {
            _syslog("APP充值", "APP充值失败", $data, $data, 1001);
            return json_fail("处理失败");
        }

//    public function paySuccess($id)
//    {
//        if (!$id) {
//            return json_fail('参数异常');
//        }
//
//        $payDetail = PayDetail::find($id);
//        if ($payDetail->pay_status != 'SUCCESS') {
//            return json_fail("支付状态异常");
//        }
    }

    /**
     * @param $payId
     * @return \support\Response
     * @throws BusinessException
     */
    public function disposePaySuccess($payId)
    {
        Log::info("开始充值", ['pay_id' => $payId]);
        $payDetail = PayDetail::find($payId);
        if (!$payDetail) {
            Log::error("充值记录异常");
            return json_success('支付状态异常');
//           return json_fail("支付状态异常");
        }
        $extendJson = [];
        if (!empty($payDetail->pay_extend_json)) {
            $extendJson = json_decode($payDetail->pay_extend_json, true);
            if (isset($extendJson['notify']) && $extendJson['notify'] == 'success') {
                return json_success('处理完成');
            }
        }
        try {
            $updateUserId = JwtToken::getCurrentId();
        } catch (\Exception $e) {
            $updateUserId = 1001;
        }

        Db::beginTransaction();
        try {
            $extendJson['notify'] = 'success';
            $payDetail->pay_extend_json = json_encode($extendJson);
            $payDetail->save();
            // 赠送比例
            $objectJson = json_decode($payDetail->join_pay_object_json, true);
            $goodsAttributeJson = [];
            $couponParams = [];
            if (isset($objectJson['order_id'])) {
                $couponParams['order_id'] = $objectJson['order_id'];
                // 对应订单设置已完成
                Order::where('order_groupby', $payDetail->join_pay_order_id)->update(['order_status_system' => 'DONE', 'order_is_complete' => 'Y', 'order_status_storage' => 'DONE']);
                $goodsAttributeJson = RechargeService::getGoodsAttributeJson($objectJson['order_id']);
            }
            // 赠送金额累加到 账户表 member_account_added
            $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
                ->where('member_account_classify', 'CASH')
                ->first();
            $addedNbr = !empty($goodsAttributeJson['added']) && !empty($goodsAttributeJson['added']['nbr']) ? $goodsAttributeJson['added']['nbr'] : 0;
            $payAmount = floatval($payDetail->pay_amount);
            $addedAmount = round($payAmount * $addedNbr, 2);
            $added = $memberAccount->member_account_added + $addedAmount;
            $income = $memberAccount->member_account_income + $payAmount;
            // 保留原数据
            RechargeService::saveOriginData($memberAccount, $payAmount, $addedNbr, $addedAmount);

            $memberAccount->member_account_added = $added;
            $memberAccount->member_account_income = $income;
            $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payAmount;
            $memberAccount->member_account_update_user_id = $updateUserId ?? 1001;
            $memberAccount->member_account_updatetimes = time();
            $memberAccount->save();
            if (!empty($goodsAttributeJson)) {
                // 根据最新的数据，更新用户等级
                RechargeService::disposeRole($payDetail->join_pay_member_id, $payDetail->pay_amount);

                // 发券
                RechargeService::disposeRoleCoupon($goodsAttributeJson, $couponParams, $payDetail->join_pay_member_id);
            }
            // 计算充值提成
            if (!empty($payDetail->join_pay_object_json)) {
                $payObjectJson = json_decode($payDetail->join_pay_object_json, true);
                if (isset($payObjectJson['order_id'])) {
                    // 没有提成过
                    if (!MemberAccountList::whereJsonContains('member_account_list_json->order_id', $payObjectJson['order_id'])->exists()) {
                        // 上级提成
                        Event::dispatch('commission.order', ['orderId' => $payObjectJson['order_id'], 'member_account_list_category' => '充值']);
                    }

                    // 入收支明细表
                    $params['orderId'] = $payObjectJson['order_id'];
                    $params['inout_category'] = '会员充值';
                    $params['pay_id'] = $payId;
                    Event::dispatch('statistics.inout.in', $params);
                }
            }

            Log::info("充值成功", ['pay_id' => $payId]);

            Db::commit();

            return json_success('success');
        } catch (BusinessException $e) {
            Db::rollBack();
            Log::error("充值失败", ['msg' => $e->getMessage()]);
            throw new BusinessException("处理失败");
        } catch (\Exception $e) {
            Db::rollBack();
            Log::error("充值失败", ['msg' => $e->getMessage()]);
            throw new BusinessException("处理失败");
        }
    }
}