<?php

namespace app\event\order;

use app\admin\service\coupon\CouponDetailService;
use app\model\Coupon;
use app\model\CouponDetail;
use app\model\Goods;
use app\model\Member;
use app\model\MemberAccount;
use app\model\PayDetail;
use app\model\SysSerial;
use support\Db;
use support\exception\BusinessException;
use support\Log;

class NewCustomerEvent
{
    public function grant($params)
    {
        Db::beginTransaction();
        try {
            Log::info("进入新客专享事件", $params);
            // 余额账户
            $memberAccount = MemberAccount::where('join_account_member_id', $params['member_id'])->where('member_account_classify', 'CASH')->first();
            // 分期付款
            if (isset($params['order_amount_paid']) && $params['order_amount_paid'] > 0) {
                $params['order_amount_pay'] = $params['order_amount_paid'] + $params['order_amount_pay'];
            }

            //发放优惠券
            $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])->select('goods_id', 'goods_name', 'goods_attribute_json')->first();
            if (!empty($goods) && !empty($goods->goods_attribute_json)) {
                $goodsAttributeJson = json_decode($goods->goods_attribute_json, true);
                if (isset($goodsAttributeJson['account'])) {
                    $memberAccount->member_account_income = $memberAccount->member_account_income + $goodsAttributeJson['account']['amount'];
                    $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $goodsAttributeJson['account']['amount'];
                    $memberAccount->save();

                    Log::info("余额账户入账：" . $goodsAttributeJson['account']['amount']);

                    // PayDetail 里写条充值记录
                    PayDetail::insert([
                        'join_pay_member_id' => $params['member_id'],
                        'join_pay_order_id' => 'COMBINE',
                        'join_pay_object_json' => json_encode([
                            'recharge_order_id' => $params['orderId'],
                            'recharge_config' => ['nbr' => 0],
                            'recharge_goods_id' => $goods->goods_id,
                            'recharge_goods_name' => $goods->goods_name
                        ]),
                        'pay_status' => 'SUCCESS',
                        'pay_category' => 'RECHARGE',
                        'pay_amount' => $goodsAttributeJson['account']['amount'],
                        'pay_paytimes' => date('Y-m-d H:i:s'),
                        'pay_prepayid' => $params['member_id'] . '-CASH',
                        'pay_json_request' => '[]',
                        'pay_json_response' => '[]',
                        'pay_extend_json' => '[]',
                        'pay_addtimes' => time()
                    ]);
                }
                if (!empty($goodsAttributeJson['coupon'])) {
                    foreach ($goodsAttributeJson['coupon'] as $key => $coupon) {
                        $couponModel = Coupon::where('coupon_id', $key)->select('coupon_id', 'coupon_validdate_day', 'coupon_validdate_end', 'coupon_is_period', 'coupon_number')->first();
                        if (empty($couponModel)) {
                            continue;
                        }
                        // 券是否过期
                        if (!empty($couponModel->coupon_validdate_end) && strtotime($couponModel->coupon_validdate_end) < time()) {
                            continue;
                        }
                        // 发周期券
                        if ($couponModel->coupon_is_period == 'Y') {
                            // 发券参数
                            $couponSendParams = [
                                'order_id' => $params['orderId'],
                                'gettype' => 'COMBINE',
                                'coupon_id' => $key,
                                'member_id' => $params['member_id']
                            ];

                            Log::info("发周期券参数", $couponSendParams);

                            CouponDetailService::sendPeriodCoupon($couponSendParams);
                            continue;
                        }

                        $couponResidue = 'all';
                        if ($couponModel->coupon_number != 0) {
                            $couponResidue = CouponDetail::where('join_detail_coupon_id', $key)->whereIn('coupon_detail_status', ['INIT', 'PENDING'])->count();
                            // 超出优惠券设置的数量
                            if ($couponResidue < $coupon['num']) {
                                continue;
                            }
                        }
                        $endDate = '';
                        if (!empty($couponModel->coupon_validdate_end)) {
                            $endDate = $couponModel->coupon_validdate_end;
                        } elseif ($couponModel->coupon_validdate_day > 0) {
                            $endDate = date('Y-m-d H:i:s', time() + ($couponModel->coupon_validdate_day * 24 * 3600) - 1);
                        }
                        // 发券参数
                        $couponSendParams = [
                            'gettype' => 'COMBINE',
                            'coupon_id' => $key,
                            'order_id' => $params['orderId'],
                            'chooseCouponNbr' => $coupon['num'],
                            'member_id' => $params['member_id'],
                            'coupon_detail_gain_datetime' => date('Y-m-d H:i:s'),
                            'coupon_detail_deadline_datetime' => $endDate,
                        ];

                        Log::info("发普通券参数", $couponSendParams);
                        if ($couponResidue != 'all' && $couponResidue - $coupon['num'] >= 0) {
                            CouponDetailService::customSendCouponHave($couponSendParams);
                        } else {
                            for ($i = 0; $i < $coupon['num']; $i++) {
                                CouponDetailService::customSendCoupon($couponSendParams);
                            }
                        }
                    }
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            _syslog("新客专享", "处理失败");
            Log::error("新客专享处理失败", ['msg' => $e->getMessage()]);
        }
    }
}