<?php

namespace app\admin\service\coupon;

use app\model\Coupon;
use app\model\CouponDetail;
use app\model\Goods;
use support\Db;
use support\exception\BusinessException;
use support\Log;

class CouponService
{
    /**
     * @Desc 优惠券自动过期
     * @Author Gorden
     * @Date 2024/8/26 17:58
     *
     * @return void
     */
    public static function checkCouponExpired()
    {
        $couponDetails = Db::select("select * from app_coupon_detail where (coupon_detail_status = 'INIT' OR coupon_detail_status = 'PENDING' OR coupon_detail_status = 'ACTIVED' OR coupon_detail_status = 'WAITING') AND coupon_detail_deadline_datetime != '' AND CAST(UNIX_TIMESTAMP(coupon_detail_deadline_datetime) as SIGNED) < " . time());
        foreach ($couponDetails as $detail) {
            $endTimeUnix = strtotime($detail->coupon_detail_deadline_datetime);
            if ($endTimeUnix < time()) {
                CouponDetail::where('coupon_detail_id', $detail->coupon_detail_id)->update(['coupon_detail_status' => 'EXPIRED']);
                echo $detail->coupon_detail_id . "已过期\n";
            }
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/9/18 11:44
     *
     * @return void
     */
    public static function sendPeriodCoupon()
    {
        Db::beginTransaction();
        try {
            $coupons = Coupon::where('coupon_is_period', 'Y')->where('coupon_status', 'ACTIVED')->get()->toArray();
//            dump("周期全",$coupons);
            foreach ($coupons as $coupon) {
                if (!empty($coupon['coupon_validdate_end']) && time() > strtotime($coupon['coupon_validdate_end'])) {
                    continue;
                }
                $details = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
                    ->where('join_coupon_detail_member_id', '<>', '')
                    ->selectRaw('join_coupon_detail_member_id,COUNT(*) as count')
                    ->groupBy('join_coupon_detail_member_id')
                    ->get();
                foreach ($details as $item) {
                    $detail = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
                        ->where('join_coupon_detail_member_id', $item->join_coupon_detail_member_id)
                        ->orderBy('coupon_detail_addtimes', 'DESC')
                        ->first();
                    if (strtotime($detail->coupon_detail_deadline_datetime) > time()) {
                        continue;
                    } elseif (empty($coupon['coupon_validdate_end']) && !empty($coupon['coupon_validdate_day'])) {
                        $firstDetail = CouponDetail::where('join_detail_coupon_id', $coupon['coupon_id'])
                            ->where('join_coupon_detail_member_id', $item->join_coupon_detail_member_id)
                            ->orderBy('coupon_detail_addtimes', 'ASC')
                            ->first();
                        if ((time() - strtotime($firstDetail->coupon_detail_addtimes)) > (3600 * 24 * $coupon['coupon_validdate_day'])) {
                            continue;
                        }
                    }

                    $params = [
                        'coupon_detail_gain_datetime' => date('Y-m-d 00:00:00'),
                        'coupon_id' => $coupon['coupon_id'],
                        'member_id' => $detail->join_coupon_detail_member_id,
                        'coupon_detail_period_num' => $detail->coupon_detail_period_num + 1
                    ];
                    // 超出期数
                    if (!empty($coupon['coupon_period_json'])) {
                        $periodJson = json_decode($coupon['coupon_period_json'], true);
                        if ($periodJson['nbr'] < $params['coupon_detail_period_num']) {
                            continue;
                        }
                        if ($periodJson['unit'] == 'day') {
                            $val = $periodJson['val'] - 1;
                            if ($val < 1) {
                                $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59');
                            } else {
                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime("+" . $val . " day"));
                            }
                        } elseif ($periodJson['unit'] == 'week') {
                            $val = $periodJson['val'] - 1;
                            if ($val < 1) {
                                $params['coupon_detail_deadline_datetime'] = date('Y-m-d 23:59:59', strtotime('this week Sunday'));
                            } else {
                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime("+" . $val . ' week', date('Y-m-d', strtotime("+" . $val . " month"))));
                            }
                        } elseif ($periodJson['unit'] == 'month') {
                            $val = $periodJson['val'] - 1;
                            if ($val < 1) {
                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59');
                            } else {
                                $params['coupon_detail_deadline_datetime'] = date('Y-m-t 23:59:59', strtotime("+" . $val . " month"));
                            }
                        }
                    }
                    if (CouponDetail::whereIn('coupon_detail_status', ['INIT', 'PENDING'])->exists()) {
                        // 匹配已发行的优惠券
                        $params['chooseCouponNbr'] = 1;
                        CouponDetailService::customSendCouponHave($params);
                    } else {
                        // 写入优惠券
                        CouponDetailService::customSendCoupon($params);
                    }

                    _syslog("周期券", "发放周期券", false, $params, 1001);
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            dump($e->getTrace());
            Db::rollBack();
        }
    }

    public static function couponClassifyInfo($classify, $category, $value, $limit)
    {
        try {
            switch ($classify) {
                case "满减券":
                    if (!empty($limit) && $category == 'NORMAL') {
                        return "满" . $limit . '减' . $value;
                    } elseif (!empty($limit) && !empty($value) && $category == 'PIECE') {
                        return "满" . intval($limit) . '件减' . $value;
                    }
                    break;
                case "立减券":
                    return "立减" . $value;
                    break;
                case "抵用券":
                    return "抵用券";
                    break;
                case "折扣券":
                    if (!empty($limit) && $category == 'NORMAL') {
                        return "满" . $limit . '打' . ($value / 10) . '折';
                    } else if (!empty($limit) && !empty($value) && $category == 'PIECE') {
                        return "满" . intval($limit) . '件打' . ($value / 10) . '折';
                    } else {
                        return $value / 10 . '折';
                    }
                    break;
                case "赠品券":
                    return "赠品券";
                    break;
                case "福利券":
                    return '抵扣' . $value;
                    break;
                case "年卡":
                    return "年卡";
                    break;
                case "季卡":
                    return "季卡";
                    break;
                case "月卡":
                    return "月卡";
                    break;
            }
        } catch (\Exception $e) {
        }

    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/9/28 14:00
     *
     * @param $params
     *          join_sheet_goods_id  关联测产品
     *          member_id   接收人
     * @return void
     * @throws BusinessException
     */
    public static function autoSendCouponByGoods($params)
    {
        try {
            $gettype = $params['gettype'] ?? '';
            $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])->select('goods_attribute_json')->first();
            if (!empty($goods) && !empty($goods->goods_attribute_json)) {
                $goodsAttributeJson = json_decode($goods->goods_attribute_json, true);
                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 = ['gettype' => $gettype, 'coupon_id' => $key, 'member_id' => $params['member_id'],'order_id' => $params['orderId']];
                            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' => $gettype,
                            '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);
                            }
                        }
                    }
                }
            }
        }catch (\Exception $e){
            Log::info("优惠券发放失败：".$e->getMessage());
            throw new BusinessException("优惠券发放失败");
        }
    }
}