<?php

namespace app\event;

use app\admin\service\notify\RechargeService;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberRole;
use app\model\PayDetail;
use support\Db;
use support\exception\BusinessException;

class MemberLevelEvent
{
    public function payOrderLevelUp($memberId)
    {
        return json_success('不升级了');
        Db::beginTransaction();
        try {
            $member = Member::where('member_id', $memberId)->select('member_id', 'join_member_role_id', 'member_mobile')->first();
            if ($member->member_mobile == '0000') {
                throw new BusinessException("散客不参与升级");
            }
//            $account = MemberAccount::where('join_account_member_id',$memberId)->where('member_account_classify','CASH')->first();
//            $income = $account->member_account_income;

            $recharge = PayDetail::where('join_pay_member_id', $memberId)
                ->where('pay_category', 'RECHARGE')
                ->where('pay_status', 'SUCCESS')
                ->where(function ($query) {
                    $query->whereIn('pay_prepayid', ['ALIPAY', 'WXPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY'])
                        ->orWhere('pay_prepayid', 'like', '%CASH%');
                })
                ->sum('pay_amount');

            $paySuccessDetail = PayDetail::where('join_pay_member_id', $memberId)
                ->where('pay_status', 'SUCCESS')
                ->whereIn('pay_category', ['GOODS', 'SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE', 'MEALS'])
                ->where(function ($query) {
                    $query->whereIn('pay_prepayid', ['ALIPAY', 'WXPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY']);
                });
            $payAmount = $paySuccessDetail->sum('pay_amount');
            $paySuccessDetail = $paySuccessDetail->select('pay_id', 'join_pay_order_id', 'pay_amount')
                ->get()
                ->toArray();
            $orderIds = array_column($paySuccessDetail, 'join_pay_order_id');
            $refundAmount = PayDetail::whereIn('join_pay_order_id', $orderIds)
                ->where('pay_category', 'REFUND')
                ->where('pay_status', 'SUCCESS')
                ->sum('pay_amount');
            $amount = $payAmount - $refundAmount;
            $resultAmount = max($recharge, $amount);
            $memberRole = MemberRole::where('member_role_range_begin', '<=', $resultAmount)
                ->where('member_role_range_end', '>', $resultAmount)
                ->first();
            if (!empty($memberRole->member_role_id) && !empty($member->join_member_role_id) && $memberRole->member_role_id != $member->join_member_role_id) {
                $oldRole = MemberRole::where('member_role_id', $member->join_member_role_id)->first();
                if (!empty($oldRole->member_role_range_begin) && $oldRole->member_role_range_begin < $memberRole->member_role_range_begin) {
                    $member->join_member_role_id = $memberRole->member_role_id;
                    $member->save();
                    RechargeService::disposeAdded($memberRole->member_role_id, $memberId);

                    _syslog("会员升级", "会员升级成功", false, ['member' => $memberId], 1001);
                }
            } elseif (!empty($memberRole->member_role_id) && empty($member->join_member_role_id)) {
                $member->join_member_role_id = $memberRole->member_role_id;
                $member->save();
                RechargeService::disposeAdded($memberRole->member_role_id, $memberId);

                _syslog("会员升级", "会员升级成功", false, ['member' => $memberId], 1001);
            }
            Db::commit();
        }catch (BusinessException $e){
            Db::rollBack();
            _syslog("会员升级","会员升级失败，原因：".$e->getMessage(),false,['member'=>$memberId],1001);
        }catch (\Exception $e){
            Db::rollBack();
            _syslog("会员升级","会员升级失败，原因：".$e->getMessage(),false,['member'=>$memberId],1001);
        }
    }
}