<?php

namespace app\admin\service\order;

use app\model\CouponDetail;
use app\model\CouponGoods;
use app\model\Goods;
use app\model\GoodsRunning;
use app\model\GoodsSku;
use app\model\Member;
use app\model\MemberBenefit;
use app\model\Order;
use app\model\OrderSheet;
use app\model\PayDetail;
use app\model\SysDept;
use support\Db;
use support\exception\BusinessException;
use support\Log as SupportLog;
use support\Redis;
use Webman\Event\Event;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;

class OrderService
{

    /**
     * @Desc 自动确认收货
     * @Author Gorden
     * @Date 2024/4/11 16:09
     *
     * @return void
     */
    public static function AutomaticReceipt()
    {
        try {
            Db::beginTransaction();
            $timeUnix = strtotime("-7 days");
            $orders = Order::where('order_status_system', 'SIGNED')
                ->where('order_addtimes', '<', $timeUnix)
                ->get();
            foreach ($orders as $order) {
                // 订单主表
                Order::where('order_id', $order->order_id)->update([
                    'order_is_complete' => 'Y',
                    'order_status_system' => 'CONFIRM',
                    'order_status_storage' => 'DONE'
                ]);
                // 订单详情表
                OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'DONE']);

                // 会员升级
                Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);

                // 7天后自动完成 order_is_complete=Y
//                $redis = Redis::connection();
//                $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
//                $redis->sadd($key, $order->order_id);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
        }
    }

    /**
     * @Desc 自动完成订单
     * @Author Gorden
     * @Date 2024/7/16 9:37
     *
     * @return void
     */
    public static function AutomaticComplete()
    {
        Db::beginTransaction();
        try {

            $redis = Redis::connection();
            $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd');
            $orderIds = $redis->smembers($key);

            foreach ($orderIds as $orderId) {
                $order = Order::where('order_id', $orderId)
                    ->select('order_is_complete', 'order_category', 'order_status_system', 'join_order_member_id')
                    ->first();
                if ($order && $order->order_is_complete != 'Y' && $order->order_category != 'RETURN' && in_array($order->order_status_system, ['RECVING', 'SIGNED', 'CONFIRM'])) {
                    // 更新主表
                    Order::where('order_id', $orderId)->update(['order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE']);
                    // sheet表
                    OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);

                    // 会员升级
                    Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);
                }
            }

            $redis->del($key);

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

    public static function checkPayingOrder()
    {
        try {
            Db::beginTransaction();
            $timeUnix = strtotime("-30 minutes");
            $orders = Order::where('order_status_system', 'PAYING')
                ->where('order_category', '<>', 'DISHES')     // 点餐不自动取消
                ->where('order_category', '<>', 'VIP')      // 康养城订单不自动取消，有分次付款
                ->where('order_category', '<>', 'COMBINE')      // 新客专享
                ->where('order_category', '<>', 'PARTNER')      // 会员合伙人
                ->where('order_category', '<>', 'REFERRER')      // 推荐官
                ->where(function ($query) {
                    $query->where('order_platform', '<>', 'SYSTEM')->orWhereNull('order_platform');
                })
                ->where('order_addtimes', '<', $timeUnix)
                ->get();
            foreach ($orders as $order) {
                \support\Log::info("取消的订单", ['order_id' => $order->order_id]);
                // 订单主表
                Order::where('order_id', $order->order_id)->update([
                    'order_is_complete' => 'Y',
                    'order_status_system' => 'CANCEL',
                    'order_status_payment' => 'CANCEL'
                ]);
                $sheets = OrderSheet::where('join_sheet_order_id', $order->order_id)->get();
                foreach ($sheets as $sheet) {
                    // 还原库存
                    $goodsSku = GoodsSku::where('goods_sku_id', $sheet->join_sheet_goods_sku_id)->first();
                    if (!empty($goodsSku) && !empty($goodsSku->goods_sku_storage_json)) {
                        $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
                        if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
                            $skuStorageJson['storage'] = $skuStorageJson['storage'] + $sheet->order_sheet_num;
                            $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
                            $goodsSku->save();
                        }
                    }


                    $goodsRunning = GoodsRunning::where('join_running_goods_id', $sheet->join_sheet_goods_id)->first();
                    if (!empty($goodsRunning)) {
                        $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $sheet->order_sheet_num;
//                        $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $sheet->order_sheet_num;
                        $goodsRunning->save();
                    }
                }
                // 释放优惠券
                if (!empty($order->order_discount_json)) {
                    $orderDiscountJson = json_decode($order->order_discount_json, true);
                    foreach ($orderDiscountJson as $discount) {
                        if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {
                            foreach ($discount['coupon_detail_id'] as $detailId) {
                                if (substr($detailId, 0, 4) == 'CUDT') {
                                    // 恢复优惠券
                                    CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);
                                }
                            }
                        }
                    }
                }

                // 订单详情表
                OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'CANCEL']);
                // 支付表
                $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
                if (!empty($payDetail)) {
                    $payExtendJson = [];
                    if (!empty($payDetail->pay_extend_json)) {
                        $payExtendJson = json_decode($payDetail->pay_extend_json, true);
                    }
                    $payExtendJson['cancel_times'] = date('Y-m-d H:i:s');
                    PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
                        'pay_status' => 'CANCEL',
                        'pay_extend_json' => json_encode($payExtendJson)
                    ]);
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            \support\Log::error("取消订单失败:" . $e->getMessage());
            Db::rollBack();
        }
    }

    /**
     * @Desc 生成核销数据
     * @Author Gorden
     * @Date 2024/9/9 17:07
     *
     * @param $params
     * @return array
     */
    public static function generateWriteOffData($params)
    {
        return [
            'charge' => [
                'charge_amount' => 1,
                'charge_content' => $params['order_remark'] ?? '',
                'charge_user_id' => $params['write_off_member_id'],
                'charge_premises' => $params['dept_premises_id'],
                'charge_waiter' => $params['charge_waiter'] ?? ''
            ],
            'member_id' => $params['join_order_member_id']
        ];
    }

    /**
     * @Desc 生成核销数据-入order_process
     * @Author Gorden
     * @Date 2024/9/9 17:07
     *
     * @param $params
     * @return array
     */
    public static function generateWriteOffDataByOrderProcess($params)
    {
        return [
            'charge' => [
                'charge_amount' => $params['charge_amount'],
                'charge_content' => $params['order_remark'] ?? '',
                'charge_waiter' => $params['charge_waiter'] ?? '',
                'charge_user_id' => $params['write_off_member_id'],
                'charge_premises' => $params['dept_premises_id'],
                'charge_premises_info' => $params['dept'] ?? ''
            ],
            'member_id' => $params['join_order_member_id'],
            'goods_id' => $params['goods_id'] ?? '',
            'goods_sku_id' => $params['goods_sku_id'] ?? '',
            'order_id' => $params['order_id'],
            'platform' => 'SYSTEM',
            'order_code' => random_string(10, 'number'),
            'appointment' => $params['appointment_ids'] ?? '',
        ];
    }

    public static function generateAppointmentApplyData($params)
    {
        $member = Member::with('cert', 'info')
            ->where('member_id', $params['join_order_member_id'])
            ->first();
        $name = '';
        if (!empty($member) && !empty($member->cert) && !empty($member->cert->member_cert_name)) {
            $name = $member->cert->member_cert_name;
        } else if (!empty($member) && !empty($member->info) && !empty($member->info->member_info_nickname)) {
            $name = $member->info->member_info_nickname;
        }

        return [
            'name' => $name,
            'times' => '',
            'mobile' => !empty($member) ? $member->member_mobile : '',
            'person' => $params['order_sheet_num'] ?? '',
            'premises' => $params['dept_premises_id'] ?? ''
        ];
    }

    /**
     * 微信支付宝扫码支付
     */
    public static function qrcodePay($params)
    {
        $log = SupportLog::channel('pay');
        $log->info("PAY_PARAMS", json_decode(json_encode($params), true));
        $params['order_amount_pay'] = floatval($params['order_amount_pay']);
        $qrcodeNbr = $params['qrcode_nbr'];
        $prefix = substr($qrcodeNbr, 0, 2);
        // 模拟数据
//         $result = [
//             'return_code'=>'SUCCESS',
//             'result_code' => 'SUCCESS'
//         ];
//        $result=[
//            'code'=> '10000',
//            'msg' => 'Success'
//        ];
//         return $result;
        // 微信支付
        if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
            $payData = [
                'out_trade_no' => $params['orderGroupId'],
                'body' => '万悦康养订单',
                'total_fee' => $params['order_amount_pay'] * 100,
                'auth_code' => $params['qrcode_nbr'],
            ];
            try {
                $config = config('payment.wxpay');
                $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/wxpay';
                $wxReturn = Pay::wechat($config)->pos($payData);
                $log->info("WXPAY_RETURN", json_decode(json_encode($wxReturn), true));
                $result = self::findWxpay($params['orderGroupId'], 0);
            } catch (GatewayException $g) {
                $result = self::findWxpay($params['orderGroupId'], 0);
            } catch (\Exception $e) {
                $log->error("WXPAY", ['msg' => $e->getMessage()]);
                $result = self::findWxpay($params['orderGroupId'], 0);
//                throw new BusinessException("支付失败");
            }
            try {
                $log->info("WXPAY_RETURN", json_decode(json_encode($result), true));
            } catch (\Exception $e) {
            }


        } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
            $payData = [
                'out_trade_no' => $params['orderGroupId'],
                'total_amount' => $params['order_amount_pay'],
                'subject' => '万悦康养订单',
                'auth_code' => $params['qrcode_nbr'],
            ];
            try {
                $config = config('payment.alipay');
                $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/alipay';
                $alipayReturn = Pay::alipay($config)->pos($payData);
                $log->info("WXPAY_RETURN", json_decode(json_encode($alipayReturn), true));
                $result = self::findAlipay($params['orderGroupId'], 0);
            } catch (GatewayException $g) {
                $result = self::findAlipay($params['orderGroupId'], 0);
            } catch (\Exception $e) {
                $log->error("ALIPAY", ['msg' => $e->getMessage()]);
                throw new BusinessException("支付失败：" . $e->getMessage());
//                $result['key'] = 'value';
            }

            try {
                $log->info("ALIPAY_RETURN", json_decode(json_encode($result), true));
            } catch (\Exception $e) {
            }
        } else {
            throw new BusinessException("付款码无效");
        }

        return $result;
    }

    /**
     * @Desc 查询微信支付
     * @Author Gorden
     * @Date 2024/8/16 14:55
     *
     * @param $orderId
     * @param $nbr 循环次数
     * @return mixed|void
     * @throws BusinessException
     */
    public static function findWxpay($orderId, $nbr = 0)
    {
        try {
            $result = Pay::wechat(config('payment.wxpay'))->find($orderId, 'pos');
            $result = json_decode(json_encode($result), true);
            SupportLog::channel('pay')->info("FIND_WXPAY_RESULT", $result);
        } catch (\Exception $e) {
            SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => $e->getMessage()]);
        }

        if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
            SupportLog::channel('pay')->info("FIND_WXPAY_SUCCESS", ['nbr' => $nbr, 'order_id' => $orderId]);
            return $result;
        } else {
            if ($nbr > 0) {
                SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => '订单查询失败', 'order_id' => $orderId]);
                return ['msg' => '订单查询失败'];
            }
            sleep(3);
            SupportLog::channel('pay')->error("FIND_WXPAY", ['nbr' => $nbr, 'order_id' => $orderId]);
            return self::findWxpay($orderId, $nbr + 1);
        }
    }

    /**
     * @Desc 查询支付宝订单
     * @Author Gorden
     * @Date 2024/8/16 15:16
     *
     * @param $orderId
     * @param $nbr 循环次数
     * @return mixed|void
     * @throws BusinessException
     */
    public static function findAlipay($orderId, $nbr = 0)
    {
        try {
            $result = Pay::alipay(config('payment.alipay'))->find($orderId);
            $result = json_decode(json_encode($result), true);
            SupportLog::channel('pay')->info("FIND_ALIPAY_RESULT", $result);
        } catch (\Exception $e) {
            SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => $e->getMessage()]);
        }

        if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
            SupportLog::channel('pay')->info("FIND_ALIPAY_SUCCESS", ['nbr' => $nbr, 'order_id' => $orderId]);
            return $result;
        } else {
            if ($nbr > 0) {
                SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => '订单查询失败', 'order_id' => $orderId]);
                return ['msg' => '订单查询失败'];
            }
            sleep(3);
            SupportLog::channel('pay')->error("FIND_ALIPAY", ['nbr' => $nbr, 'order_id' => $orderId]);
            return self::findAlipay($orderId, $nbr + 1);
        }
    }

    /**
     * 验证产品库存
     */
    public static function checkGoodsStorage($params)
    {
        foreach ($params['goodsContentList'] as $goods) {
            // 减库存,规格和总库存
            if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE', 'COMBINE'])) {
                $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
                $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
                if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
                    $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
                }
                if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
                    throw new BusinessException('库存不足');
                }
            }
            $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
            $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
            if ($goodsRunning->goods_running_storage < 0) {
                throw new BusinessException('库存不足');
            }
        }
    }

    /**
     * 下单时结算的组合支付payDetail
     */
    public static function createPayDetail($params)
    {
        $insertPayDetailData = [
            'join_pay_member_id' => $params['join_order_member_id'],
            'join_pay_order_id' => $params['orderGroupId'],
            'pay_status' => $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
            'pay_category' => !empty($params['submit_goods_classify']) ? $params['submit_goods_classify'] : $params['goods_classify'],
            'pay_amount' => $params['order_amount_pay'],
            'pay_paytimes' => date('Y-m-d H:i:s'),
            'pay_prepayid' => $params['pay_category'],
            'pay_json_request' => json_encode($params),
            'pay_json_response' => $params['pay_json_response'] ?? '[]',
            'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
            'pay_addtimes' => time()
        ];

        PayDetail::insert($insertPayDetailData);
    }

    /**
     * 组合支付，PayDetail
     */
    public static function createPayConstituteDetail($params, $payDetail)
    {
        $qrcodePrepayId = '';
        if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
            $qrcodePrepayId = $params['join_order_member_id'] . '-QRCODE';
        }
        if (!$payDetail || ($payDetail->pay_prepayid != $params['pay_category'] && $payDetail->pay_prepayid != $qrcodePrepayId)) {
            $payDetail = new PayDetail();
            $payDetail->join_pay_member_id = $params['join_order_member_id'];
            $payDetail->join_pay_order_id = $params['orderGroupId'];
            $payDetail->pay_category = $params['goods_classify'] ?? '';
            $payDetail->pay_prepayid = $params['pay_category'];
            $payDetail->pay_json_request = json_encode($params);
            $payDetail->pay_addtimes = time();
        }
        if ($payDetail->pay_prepayid == $qrcodePrepayId) {
            $payDetail->pay_prepayid = $params['pay_category'];
        }
        $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
            'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
        ]);
        $payDetail->pay_amount = $params['order_amount_pay'];
        $payDetail->pay_paytimes = date('Y-m-d H:i:s');
        $payDetail->pay_status = $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING';;
        $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
        $payDetail->save();
    }


    /**
     * 组合支付，PayDetail
     */
    public static function createProductPayConstituteDetail($params)
    {
        $payDetail = new PayDetail();
        $payDetail->join_pay_member_id = $params['join_order_member_id'];
        $payDetail->join_pay_order_id = $params['orderGroupId'];
        $payDetail->pay_category = $params['goods_classify'] ?? '';
        $payDetail->pay_json_request = json_encode($params);
        $payDetail->pay_addtimes = time();
        $payDetail->pay_prepayid = $params['pay_category'];
        $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
            'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
        ]);
        $payDetail->pay_amount = $params['order_amount_pay'];
        $payDetail->pay_paytimes = date('Y-m-d H:i:s');
        $payDetail->pay_status = $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING';
        $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
        $payDetail->save();
    }

    public static function getPayWayByPrepayId($prepayId)
    {
        $payWay = '';
        $categoryArray = explode('-', $prepayId);
        if (isset($categoryArray[1])) {
            $payWay = $categoryArray[1];
        } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
            $payWay = $categoryArray[0];
        }

        return $payWay;
    }

    /**
     * @Desc 支付使用优惠券
     * @Author Gorden
     * @Date 2024/8/28 14:59
     *
     * @param $memberId
     * @param $goods
     * @param $coupon
     * @param $payAmount
     * @return array|mixed
     */
    public static function payUseCoupon($type, $settlementNow, $memberId, $goods, $coupon, $payAmount)
    {
        try {
            foreach ($coupon as $item) {
                if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) {
                    return [];
                }
            }
            $amountBalance = [
                'pay_amount' => $payAmount,
                'welfare_balance' => 0,
                'cut_balance' => 0,
            ];
            foreach ($goods as $good) {
                $result = OrderService::useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance);
                $amountBalance = [
                    'pay_amount' => $result['pay_amount'],
                    'welfare_balance' => $result['welfare_balance'],
                    'cut_balance' => $result['cut_balance'],
                ];
            }

            $couponDetailsIds = Redis::sMembers("ORDER:USE:COUPON:" . $memberId);
            Redis::del("ORDER:USE:COUPON:" . $memberId);
            $useCouponJson = Redis::get("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
            Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);

            return [
                'pay_amount' => $amountBalance['pay_amount'],
                'detail_ids' => $couponDetailsIds,
                'use_coupon_json' => $useCouponJson ?? []
            ];
        } catch (\Exception $e) {
            dump($e->getTrace());
        }
    }

    public static function useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance)
    {
        try {
            $cacheKey = "ORDER:USE:COUPON:" . $memberId;
            $cacheDiscountKey = "ORDER:USE:COUPON:DISCOUNT:" . $memberId;
            $payAmount = $amountBalance['pay_amount'];
            $welfareBalance = $amountBalance['welfare_balance'];
            $cutBalance = $amountBalance['cut_balance'];
            $goodsId = $good['goods_id'];
            $money = $good['goods_sales_price'] * $good['nbr'];

            $discountData = Redis::get($cacheDiscountKey);
            if (empty($discountData)) {
                $discountData = [];
            } else {
                $discountData = json_decode($discountData, true);
            }
            foreach ($coupon as $couponId) {
                $couponDetail = Db::table('coupon_detail')->leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
                    ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
                    ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
                    ->where('coupon_goods.join_coupon_goods_id', $goodsId)
//                    ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id'])
                    ->where('join_goods_coupon_id', $couponId)
                    ->where('coupon_detail.join_coupon_detail_member_id', $memberId)
                    ->where('coupon_detail.coupon_detail_gain_datetime', '<=', date('Y-m-d H:i:s'))
                    ->where('coupon_detail.coupon_detail_deadline_datetime', '>=', date('Y-m-d H:i:s'))
                    ->where('coupon_detail.coupon_detail_status', 'ACTIVED');
//                if ($settlementNow == 'Y' && $type == 'pay') {
//                    $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
//                } else {
//                    $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
//                }
                $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC')
                    ->first();
                if (!$couponDetail) {
                    continue;
                }
                $updateData = [
                    'coupon_detail_status' => 'USED',
                    'coupon_detail_used_datetime' => date('Y-m-d H:i:s'),
                ];
//                if ($settlementNow == 'Y') {
//                    $updateData = [
//                        'coupon_detail_status' => 'USED',
//                        'coupon_detail_used_datetime' => date('Y-m-d H:i:s'),
//                    ];
//                } else {
//                    $updateData = [
//                        'coupon_detail_status' => 'WAITING',
//                    ];
//                }
                // 计算优惠券包含的优惠商品的件数和总价
                $countAndAmount = self::countAndAmount($goods, $couponId);
                // 如果是计件
                if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) {
                    continue;
                }
                if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
                        $payAmount = $payAmount - $couponDetail->coupon_value;
                        // json记录
                        $discountData[$couponId] = [
                            'coupon_id' => $couponId,
                            'coupon_value' => $couponDetail->coupon_value,
                            'coupon_classify' => $couponDetail->coupon_classify,
                            'coupon_detail_id' => [$couponDetail->coupon_detail_id]
                        ];
                        Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));

                        CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
                    }
                } elseif ($couponDetail->coupon_classify == '折扣券') {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    if ($couponDetail->coupon_category == 'PIECE' || $couponDetail->coupon_category == 'PROMOTION' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
                        $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2);
                        $payAmount = $payAmount - $zhekouAmount;
                        // json记录
                        $discountData[$couponId] = [
                            'coupon_id' => $couponId,
                            'coupon_value' => $zhekouAmount,
                            'coupon_classify' => $couponDetail->coupon_classify,
                            'coupon_detail_id' => [$couponDetail->coupon_detail_id]
                        ];
                        Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
                        CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
                    }
                } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
                    if ($good['nbr'] > 1) {
                        $diyongAmount = $good['goods_sales_price'];
                        $payAmount = $payAmount - $diyongAmount;
                    } elseif (ceil($good['nbr']) == 1) {
                        $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2);
                        $payAmount = $payAmount - $diyongAmount;
                    }
                    // json记录
                    $discountData[$couponId] = [
                        'coupon_id' => $couponId,
                        'coupon_value' => $diyongAmount,
                        'coupon_classify' => $couponDetail->coupon_classify,
                        'coupon_detail_id' => [$couponDetail->coupon_detail_id]
                    ];
                    Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
                } elseif ($couponDetail->coupon_classify == '福利券') {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
                    $fuliAmount = 0;
                    if (!empty($couponDetail->coupon_value)) {
                        $fuliAmount = $couponDetail->coupon_value;
                    }

                    if ($fuliAmount >= $countAndAmount['amount']) {
                        $preferentialAmount = $countAndAmount['amount'];
                    } else {
                        $preferentialAmount = $fuliAmount;
                    }
                    $payAmount = $payAmount - $preferentialAmount;

                    // json记录
                    $discountData[$couponId] = [
                        'coupon_id' => $couponId,
                        'coupon_value' => $preferentialAmount,
                        'coupon_classify' => $couponDetail->coupon_classify,
                        'coupon_detail_id' => [$couponDetail->coupon_detail_id]
                    ];
                    Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
                } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) {
                    if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    Redis::sAdd($cacheKey, $goodsId);
                    $kaAmount = 0;
                    if (!empty($discountData[$couponId]['coupon_value'])) {
                        $kaAmount = $discountData[$couponId]['coupon_value'];
                    }
                    if ($good['nbr'] > 1) {
                        $payAmount = $payAmount - $good['goods_sales_price'];
                        $kaAmount = $good['goods_sales_price'];
                    } else {
                        $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr'];
                        $kaAmount = $good['goods_sales_price'] * $good['nbr'];
                    }

                    // json记录
                    $discountData[$couponId] = [
                        'coupon_id' => $couponId,
                        'coupon_value' => $kaAmount,
                        'coupon_classify' => $couponDetail->coupon_classify,
                        'coupon_detail_id' => [$couponDetail->coupon_detail_id]
                    ];
                    Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
                }
            }

            if ($payAmount < 0) {
                $payAmount = 0;
            }
            $amountBalance = [
                'pay_amount' => round($payAmount, 2),
                'welfare_balance' => 0,
                'cut_balance' => 0
            ];
            return $amountBalance;
        } catch (\Exception $e) {
            Redis::del("ORDER:USE:COUPON:" . $memberId);
            Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
            dump($e->getTrace());
        }
    }

    /**
     * @Desc 选择优惠券，计算
     * @Author Gorden
     * @Date 2024/8/28 14:18
     *
     * @param $memberId
     * @param $goods
     * @param $good
     * @param $coupon
     * @param $amountBalance
     * @return array|void
     */
    public static function chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance, $orderId)
    {
        $couponDetailIds = [];
        if (!empty($orderId)) {
            $order = Order::where('order_id', $orderId)->first();
            if (!empty($order->order_discount_json)) {
                $orderDiscountJson = json_decode($order->order_discount_json, true);
                foreach ($orderDiscountJson as $orderCoupon) {
                    if ($coupon[0] == $orderCoupon['coupon_id']) {
                        $couponDetailIds = $orderCoupon['coupon_detail_id'];
                    }
                }
            }
        }
        try {
            $cacheKey = "ORDER:USE:COUPON:" . $memberId;
            $payAmount = $amountBalance['pay_amount'];
            $welfareBalance = $amountBalance['welfare_balance'];
            $cutBalance = $amountBalance['cut_balance'];
            $goodsId = $good['goods_id'];
            $money = $good['goods_sales_price'] * $good['nbr'];
            foreach ($coupon as $couponId) {
                $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
                    ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
                    ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
                    ->whereIn('coupon_detail_id', $couponDetailIds)
                    ->orWhere(function ($query) use ($goodsId, $couponId, $memberId) {
                        $query->where('coupon_goods.join_coupon_goods_id', $goodsId)
                            ->where('join_goods_coupon_id', $couponId)
                            ->where('coupon_detail.join_coupon_detail_member_id', $memberId)
                            ->where('coupon_detail.coupon_detail_gain_datetime', '<=', date('Y-m-d H:i:s'))
                            ->where('coupon_detail.coupon_detail_deadline_datetime', '>=', date('Y-m-d H:i:s'))
                            ->where('coupon_detail.coupon_detail_status', 'ACTIVED');
                    });

//                    ->where('coupon_goods.join_coupon_goods_id', $goodsId)
//                    ->where('join_goods_coupon_id', $couponId)
//                    ->where('coupon_detail.join_coupon_detail_member_id', $memberId)
//                    ->where('coupon_detail.coupon_detail_gain_datetime', '<=', date('Y-m-d H:i:s'))
//                    ->where('coupon_detail.coupon_detail_deadline_datetime', '>=', date('Y-m-d H:i:s'))
//                    ->where('coupon_detail.coupon_detail_status', 'ACTIVED');
//                if ($settlementNow == 'Y') {
//                    $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
//                } else {
//                    $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
//                }
                $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC')
                    ->first();
                if (!$couponDetail) {
                    continue;
                }
                // 计算优惠券包含的优惠商品的件数和总价
                $countAndAmount = self::countAndAmount($goods, $couponId);
                // 如果是计件
                if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) {
                    continue;
                }
                if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
                        $payAmount = $payAmount - $couponDetail->coupon_value;
                    }
                }
//                elseif ($couponDetail->coupon_classify == '满减券') {
//                    if (Redis::sIsMember($cacheKey, $couponId)) {
//                        continue;
//                    }
//                    Redis::sAdd($cacheKey, $couponId);
//                    // 计件
//                    if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] >= $couponDetail->coupon_minimum_limit) {
//                        $goodsIds = array_splice($countAndAmount['goodsIds'], 0, $couponDetail->coupon_value);
//                        $amount = 0;
//                        $goodsNbr = 0;
//                        foreach ($goods as $countAndAmountGood) {
//                            if (in_array($countAndAmountGood['goods_id'], $goodsIds) && $goodsNbr < $couponDetail->coupon_value) {
//                                if ($goodsNbr + $countAndAmountGood['nbr'] <= $couponDetail->coupon_value) {
//                                    $amount = $amount + round($countAndAmountGood['goods_sales_price'] * $countAndAmountGood['nbr'], 2);
//                                    $goodsNbr += $countAndAmountGood['nbr'];
//                                } elseif ($goodsNbr + $countAndAmountGood['nbr'] > $couponDetail->coupon_value) {
//                                    $amount = $amount + round($countAndAmountGood['goods_sales_price'] * ($couponDetail->coupon_value - $goodsNbr), 2);
//                                    $goodsNbr = $couponDetail->coupon_value - $goodsNbr;
//                                }
//                            }
//                        }
//                        $payAmount = $payAmount - $amount;
//                    }else if ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit) { // 金额
//                        $payAmount = $payAmount - $couponDetail->coupon_value;
//                    }
//                }
                elseif ($couponDetail->coupon_classify == '折扣券') {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    if ($couponDetail->coupon_category == 'PIECE' || $couponDetail->coupon_category == 'PROMOTION' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
                        $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2);
                        $payAmount = $payAmount - $zhekouAmount;
                    }
                } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    if ($good['nbr'] > 1) {
                        $diyongAmount = $good['goods_sales_price'];
                        $payAmount = $payAmount - $diyongAmount;
                    } elseif (ceil($good['nbr']) == 1) {
                        $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2);
                        $payAmount = $payAmount - $diyongAmount;
                    }
                } elseif ($couponDetail->coupon_classify == '福利券') {
                    if (Redis::sIsMember($cacheKey, $couponId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    $fuliAmount = 0;
                    if (!empty($couponDetail->coupon_value)) {
                        $fuliAmount = $couponDetail->coupon_value;
                    }
                    if ($fuliAmount >= $countAndAmount['amount']) {
                        $preferentialAmount = $countAndAmount['amount'];
                    } else {
                        $preferentialAmount = $fuliAmount;
                    }
                    $payAmount = $payAmount - $preferentialAmount;
                } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) {
                    if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) {
                        continue;
                    }
                    Redis::sAdd($cacheKey, $couponId);
                    Redis::sAdd($cacheKey, $goodsId);
                    if ($good['nbr'] > 1) {
                        $payAmount = $payAmount - $good['goods_sales_price'];
                    } else {
                        $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr'];
                    }

                }
            }

            if ($payAmount < 0) {
                $payAmount = 0;
            }
            $amountBalance = [
                'pay_amount' => round($payAmount, 2),
                'welfare_balance' => $welfareBalance,
                'cut_balance' => $cutBalance
            ];
            return $amountBalance;
        } catch (\Exception $e) {
            Redis::del("ORDER:USE:COUPON:" . $memberId);
            Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
            Log::error('优惠券使用失败', ['msg' => $e->getMessage()]);
        }
    }

    public static function countAndAmount($goods, $couponId)
    {
        try {
            $goodsIds = array_column($goods, 'goods_id');
            $couponGoods = CouponGoods::whereIn('join_coupon_goods_id', $goodsIds)
                ->where('join_goods_coupon_id', $couponId)
//                ->select('join_coupon_goods_id', 'join_coupon_goods_sku_id')
                ->get()
                ->toArray();
            $count = 0;
            $amount = 0;
            $goodsIds = [];
            foreach ($couponGoods as $couponGood) {
                foreach ($goods as $good) {
//                    if ($good['goods_id'] == $couponGood['join_coupon_goods_id'] && $good['sku_id'] == $couponGood['join_coupon_goods_sku_id']) {
                    if ($good['goods_id'] == $couponGood['join_coupon_goods_id']) {
                        $count += $good['nbr'];
                        $amount += $good['goods_sales_price'] * $good['nbr'];
                        $goodsIds[] = $good['goods_id'];
                    }
                }
            }

            return compact('count', 'amount', 'goodsIds');
        } catch (\Exception $e) {
            dump($e->getTrace());
        }
    }

    /**
     * @Desc
     * @Author Gorden
     * @Date 2024/9/11 11:11
     *
     * @param MemberBenefit $benefit
     * @return false[]|true[]
     */
    public static function checkPackageBenefit(MemberBenefit $benefit)
    {
        $result = ['sheet' => true, 'order' => true];
        // 除此权益外，套包的其他权益是否用完了  where('join_benefit_package_id', $benefit->join_benefit_package_id)
        $benefits = MemberBenefit::where('join_benefit_order_id', $benefit->join_benefit_order_id)
            ->where('member_benefit_id', '<>', $benefit->member_benefit_id)
            ->get()
            ->toArray();
        foreach ($benefits as $benefitItem) {
            if ($benefitItem['join_benefit_package_id'] == $benefit->join_benefit_package_id) {
                if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {
                    return ['sheet' => false, 'order' => false];
                }
            }
        }
        foreach ($benefits as $benefitItem) {
            if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {
                $result['order'] = false;
                return $result;
            }
        }

        return $result;
    }

    /**
     * @Desc 拆单提成
     * @Author Gorden
     * @Date 2024/9/29 16:27
     *
     * @return void
     */
    public static function splitOrderCommission($params)
    {
        $orders = Order::where('order_groupby', $params['orderGroupId'])->get()->toArray();
        if (!empty($orders)) {
            foreach ($orders as $orderItem) {
                $params['member_id'] = $orderItem['join_order_member_id'];
                $params['orderId'] = $orderItem['order_id'];
                Event::dispatch('commission.order', $params);
            }
        }
    }

    public static function splitOrderStatisticsInOut($params)
    {
        $orders = Order::where('order_groupby', $params['orderGroupId'])->get()->toArray();
        if (!empty($orders)) {
            foreach ($orders as $orderItem) {
                $params['member_id'] = $orderItem['join_order_member_id'];
                $params['orderId'] = $orderItem['order_id'];
                $params['inout_category'] = '标准订单';
                Event::dispatch('statistics.inout.in', $params);
            }
        }
    }

    /**
     * 检查产品限额
     */
    public static function checkGoodsLimit($goods, $memberId)
    {
        foreach ($goods as $good) {
            $goodsLimit = 'no';
            $goodsModel = Goods::where('goods_id', $good['goods_id'])->select('goods_attribute_json')->first();
            if (!empty($goodsModel) && !empty($goodsModel->goods_attribute_json)) {
                $goodsAttributeJson = json_decode($goodsModel->goods_attribute_json, true);
                if (!empty($goodsAttributeJson['max-limit'])) {
                    $goodsLimit = $goodsAttributeJson['max-limit'];
                    if ($goodsLimit != 0 && $goodsLimit != '' && $good['nbr'] > $goodsLimit) {
                        return false;
                    }
                }
            }

            $sheetNbr = 0;
            if ($goodsLimit != 'no') {
                $sheetNbr = OrderSheet::where('join_sheet_member_id', $memberId)
                    ->where('join_sheet_goods_id', $good['goods_id'])
                    ->where('order_sheet_status', '<>', 'CANCEL')
                    ->sum('order_sheet_num');
                if ($goodsLimit != 0 && $goodsLimit != '' && $good['nbr'] + $sheetNbr > $goodsLimit) {
                    return false;
                }
            }
        }

        return true;
    }


    public static $couponClassify = [
        'wipe' => '抹零',
        'custom' => '自定义优惠金额'
    ];

    public static $payWay = [
        'WXPAY' => '微信支付',
        'ALIPAY' => '支付宝',
        'CASH' => '账户余额',
        'CARD' => '储值卡',
        'WELFARE' => '福利账户',
        'MONEY' => '现金',
        'OFFLINE' => '线下支付',
        'OFFLINE_WXPAY' => '微信支付(线下)',
        'OFFLINE_ALIPAY' => '支付宝(线下)',
        'QRCODE' => '付款码',
        'NONE' => '付零',
        'VIP' => 'VIP账户'
    ];

    public static $orderClassify = [
        'GOODS' => '产品订单',
        'CHNMED' => '服务订单',
        'CHNNCD' => '服务订单',
        'SERVICE' => '服务订单',
        'DEVICE' => '设备订单',
        'SPECIAL' => '专题业务订单',
        'PACKAGE' => '套包订单',
        'RECHARGE' => '充值订单',
        'DESHES' => '餐饮订单',
        'MEALS' => '餐饮订单',
        'VIP' => '康养城订单',
        'PARTNER' => '合伙人订单',
        'REFERRER' => '康养推荐官订单',
        'COMBINE' => '新客专享订单'
    ];

    /**
     * @Desc 更新订单 sheet
     * @Author Gorden
     * @Date 2024/10/21 11:18
     *
     * @param Order $order
     * @param $status
     * @return void
     */
    public static function updateSheet(Order $order, $status)
    {
        $sheets = OrderSheet::where('join_sheet_order_id', $order->order_id)->get()->toArray();
        foreach ($sheets as $sheet) {
            $sheetPricePay = round(($order->order_amount_pay / $order->order_amount_total) * $sheet['order_sheet_price'], true);
            OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->update([
                'order_sheet_status' => $status,
                'order_sheet_price_pay' => $sheetPricePay,
                'order_sheet_pay' => $sheetPricePay * $sheet['order_sheet_num']
            ]);
        }
    }
}