<?php

namespace app\admin\service\order;

use app\model\PayDetail;
use support\Db;

class PayDetailService
{
    public static function checkPaying()
    {
        Db::beginTransaction();
        try {
            $timeUnix = strtotime("-30 minutes");
            $payDetails = PayDetail::where('pay_status', 'WAITING')
                ->where('pay_addtimes', '<', $timeUnix)
                ->get();
            foreach ($payDetails as $payDetail) {
                // 订单主表
                PayDetail::where('pay_id', $payDetail->pay_id)->update([
                    'pay_status' => 'CANCEL',
                ]);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
        }
    }

    /**
     * @Desc 搜索指定时间的付款订单ID
     * @Author Gorden
     * @Date 2024/10/24 15:12
     *
     * @param $timeStart
     * @param $timeEnd
     * @return array
     */
    public static function getPayOrderId($timeStart, $timeEnd, $category = [])
    {
        $payDetails = PayDetail::whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) >= ? ', [$timeStart])
            ->whereRaw('CAST(UNIX_TIMESTAMP(pay_paytimes) as SIGNED) <= ? ', [$timeEnd])
            ->where('pay_status', 'SUCCESS')
            ->when(!empty($category), function ($query) use ($category) {
                $query->whereIn('pay_category', $category);
            })
            ->select('join_pay_object_json')
            ->get()
            ->toArray();

        $orderIds = [];
        foreach ($payDetails as $detail) {
            if (!empty($detail['join_pay_object_json']) && is_json($detail['join_pay_object_json'])) {
                $payObjectJson = json_decode($detail['join_pay_object_json'], true);
                if (!empty($payObjectJson['order_id']) && !in_array($payObjectJson['order_id'], $orderIds)) {
                    $orderIds[] = $payObjectJson['order_id'];
                }
            }
        }

        return $orderIds;
    }

    /**
     * @Desc 获取支付方式
     * @Author Gorden
     * @Date 2024/10/24 16:12
     *
     * @param $groupId
     * @param $orderId
     * @return array
     */
    public static function getPayWay($groupId, $orderId)
    {
        $payDetails = PayDetail::where('join_pay_order_id', $groupId)
            ->where(function ($query) use ($orderId) {
                $query->whereJsonContains('join_pay_object_json->order_id', $orderId)
                    ->orWhere('join_pay_object_json', '')
                    ->orWhereNull('join_pay_object_json');
            })->where('pay_category', '<>', 'REFUND')
            ->where('pay_prepayid','<>','')
            ->where('pay_status', 'SUCCESS')
            ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
            ->get()
            ->toArray();

        $data = [];
        if (count($payDetails) > 1) {
            $data['payWay'] = "组合支付";
        }

        foreach ($payDetails as $detail) {
            $data['pay_paytimes'] = $detail['pay_paytimes'];
            $data['pay_status'] = $detail['pay_status'];
            $data['pay_amount'] = $detail['pay_amount'];
            $data['pay_category'] = $detail['pay_category'];
//            $payWay = '';
//            if (in_array($detail['pay_prepayid'], ['WXPAY', 'ALIPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY', 'OFFLINE'])) {
//                $payWay = $detail['pay_prepayid'];
//            } else {
//                $prepayid = explode('-', $detail['pay_prepayid']);
//                if (!empty($prepayid[1]) && in_array($prepayid[1], ['CASH', 'WELFARE', 'QRCODE', 'NONE'])) {
//                    $payWay = $prepayid[1];
//                }
//            }
            $payWay = self::getPayWayByPrepayId($detail['pay_prepayid']);
            if (empty($payWay)) {
                $data['payWay'] = '';
                return $data;
            }
            $payWay = OrderService::$payWay[$payWay];
            if (!empty($data['payWay']) && $data['payWay'] == '组合支付') {
                $data['payWayDesc'] = $payWay . '(￥' . $detail['pay_amount'] . '),';
            } else {
                $data['payWay'] = $payWay;
            }
        }

        return $data;
    }

    /**
     * @Desc 根据prepayId 获取 支付方式
     * @Author Gorden
     * @Date 2024/10/28 14:04
     *
     * @param $prepayId
     * @return mixed|string
     */
    public static function getPayWayByPrepayId($prepayId)
    {
        $payWay = '';
        if (in_array($prepayId, ['WXPAY', 'ALIPAY', 'OFFLINE_WXPAY', 'OFFLINE_ALIPAY', 'MONEY', 'OFFLINE'])) {
            $payWay = $prepayId;
        } else {
            $prepayIdArr = explode('-', $prepayId);
            if (!empty($prepayIdArr[1]) && in_array($prepayIdArr[1], ['CASH', 'WELFARE', 'QRCODE', 'NONE','VIP'])) {
                $payWay = $prepayIdArr[1];
            }elseif (count($prepayIdArr) == 1){
                $payWay = 'CARD';
            }
        }

        return $payWay;
    }
}