| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593 | <?phpnamespace app\admin\controller\order;use app\admin\service\member\MemberService;use app\admin\service\order\OrderService;use app\admin\service\order\PayDetailService;use app\admin\validate\order\OrderValidate;use app\controller\Curd;use app\model\Appointment;use app\model\CouponDetail;use app\model\Goods;use app\model\GoodsComponent;use app\model\GoodsRunning;use app\model\GoodsSku;use app\model\Member;use app\model\MemberAccount;use app\model\MemberBenefit;use app\model\Order;use app\model\OrderExpress;use app\model\OrderSheet;use app\model\PayDetail;use app\model\SysDept;use support\Db;use support\exception\BusinessException;use support\Redis;use support\Request;use support\Response;use Webman\Event\Event;class ServicesController extends Curd{    public function __construct()    {        $this->model = new Order();        $this->validate = true;        $this->validateClass = new OrderValidate();    }    /**     * @Desc 列表     * @Author Gorden     * @Date 2024/3/28 15:01     *     * @param Request $request     * @return Response     * @throws \support\exception\BusinessException     */    public function select(Request $request): Response    {        $timeType = $request->get('time_type', 'add');        [$where, $format, $limit, $field, $order] = $this->selectInput($request);        if (!empty($where['order_addtimes']) && $timeType == 'add') {            $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);            $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);        }        $where['order_classify'] = ['in', 'SERVICE,CHNMED,CHNNCD'];        $order = $request->get('order', 'desc');        $field = $field ?? 'order_addtimes';        if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {            $where['order_is_complete'] = 'N';            $where['order_category'] = ['<>', 'RETURN'];        }        $orderId = trim($request->get('order_id', ''));        $orderIds = [];        if (!empty($orderId)) {            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')                ->whereIn('order_classify', ['SERVICE', 'CHNMED', 'CHNNCD'])                ->pluck('order_id')                ->toArray();        }        $goodsName = trim($request->get('goods_name', ''));        if (!empty($goodsName)) {            $goodsIds = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD'])                ->where('goods_name', 'like', '%' . $goodsName . '%')                ->pluck('goods_id')                ->toArray();            $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();            if (!empty($where['order_id'])) {                $orderIds = array_intersect($orderIds, $goodsOrderIds);            } else {                $orderIds = $goodsOrderIds;            }        }        // 付款时间        $payOrderIds = [];        if ($timeType == 'pay' && !empty($where['order_addtimes'])) {            $payTimeStart = strtotime($where['order_addtimes'][0]);            $payTimeEnd = strtotime($where['order_addtimes'][1]);            unset($where['order_addtimes']);            $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['SERVICE', 'CHNMED', 'CHNNCD']);        }        if (!empty($orderId) && $timeType == 'pay') {            $orderIds = array_intersect($orderIds, $payOrderIds);            $where['order_id'] = ['in', implode(',', $orderIds)];        } elseif (!empty($orderId)) {            $where['order_id'] = ['in', implode(',', $orderIds)];        } elseif ($timeType == 'pay') {            $where['order_id'] = ['in', implode(',', $payOrderIds)];        }        $query = $this->doSelect($where, $field, $order);        return $this->doFormat($query, $format, $limit);    }    protected function doSelect(array $where, string $field = null, string $order = 'desc')    {        $model = $this->model->with([            'sheets' => function ($query) {                $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');            },            'member' => function ($query) {                $query->select('member_id', 'member_mobile');            },            'cert' => function ($query) {                $query->select('join_cert_member_id', 'member_cert_name');            },//            'return' => function ($query) use ($where){//                if (isset($where['return'])){//                    dump($where['return']);//                    $query = $query->where('order_return_status',$where['return']);//                }//                $query->select('orders_return_id', 'join_return_order_id', 'order_return_status');//            },            'express' => function ($query) {                $query->select('join_express_order_id', 'order_express_type');            }        ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id');        // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');        foreach ($where as $column => $value) {            if (is_array($value)) {                if ($value[0] === 'like' || $value[0] === 'not like') {                    $model = $model->where($column, $value[0], "%$value[1]%");                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {                    $model = $model->where($column, $value[0], $value[1]);                } elseif ($value[0] == 'in' && !empty($value[1])) {                    $valArr = $value[1];                    if (is_string($value[1])) {                        $valArr = explode(",", trim($value[1]));                    }                    $model = $model->whereIn($column, $valArr);                } elseif ($value[0] == 'not in' && !empty($value[1])) {                    $valArr = $value[1];                    if (is_string($value[1])) {                        $valArr = explode(",", trim($value[1]));                    }                    $model = $model->whereNotIn($column, $valArr);                } elseif ($value[0] == 'null') {                    $model = $model->whereNull($column);                } elseif ($value[0] == 'not null') {                    $model = $model->whereNotNull($column);                } elseif ($value[0] !== '' || $value[1] !== '') {                    $model = $model->whereBetween($column, $value);                }            } else {                $model = $model->where($column, $value);            }        }        if ($field) {            $model = $model->orderBy($field, $order);        }        $model = $model->select('order.*', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_refund_json', 'order_return.order_return_remark');        return $model;    }    public function afterQuery($items)    {        foreach ($items as &$item) {            $sheetDeng = '';            $item['sheet'] = $item['sheets'][0] ?? [];            if (!empty($item['sheet'])) {                $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();                if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {                    $sheetDeng = ' 等餐品';                }                $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';                $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';                $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);            }            unset($item['sheets']);            $item['order_return_amount'] = 0;            if (isset($item['orders_return_id'])) {                $item['return'] = [                    'orders_return_id' => $item['orders_return_id'],                    'join_return_order_id' => $item['join_return_order_id'],                    'order_return_status' => $item['order_return_status'],                    'order_return_apply_json' => $item['order_return_apply_json'],                    'order_return_remark' => $item['order_return_remark']                ];                if (!empty($item['order_return_refund_json'])) {                    $refundJson = json_decode($item['order_return_refund_json'], true);                    if (isset($refundJson['amount'])) {                        $item['order_return_amount'] = $refundJson['amount'];                    }                }            }            $item['have_success_paydetail'] = 'N';            if (PayDetail::where('join_pay_order_id', $item['order_groupby'])                ->whereJsonContains('join_pay_object_json->order_id', $item['order_id'])                ->where('pay_status', 'SUCCESS')                ->exists()) {                $item['have_success_paydetail'] = 'Y';            }            $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);        }        return $items;    }    /**     * @Desc 下单+支付     * @Author Gorden     * @Date 2024/9/23 16:15     *     * @param Request $request     * @return Response     */    public function insert(Request $request): Response    {        $params = $request->post();        // 判断餐品是否连带着服务或实体        $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));        $premises = [];        if (!empty($params['dept_premises_id'])) {            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();        }        $params['goods_classify'] = $goodsClassifys[0];        Db::beginTransaction();        try {            // 使用优惠券            $couponUseJson = [];            if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {                $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);                if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {                    throw new BusinessException("计算优惠后,实付金额错误!");                }                // 组装优惠券使用数据,存主表优惠里                if (!empty($couponResult['use_coupon_json'])) {                    $couponUseJson = $couponResult['use_coupon_json'];                }            }            // 存储优惠信息            $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));            // 验证库存            foreach ($params['goodsContentList'] as $goods) {                // 减库存,规格和总库存                if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {                    $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('库存不足');                }            }            // 余额、福利、储值卡 验证短信            if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {                $code = $params['sms_code'];                if (!$code) {                    throw new BusinessException('验证码错误,请重新输入');                }                $member = Member::find($params['join_order_member_id']);                $mobile = $member->member_mobile;                $key = "SMS:CODE:ORDER_PAY:" . $mobile;                $redisCode = Redis::get($key);                if ($redisCode != $code && $code != '123456') {                    throw new BusinessException('验证码错误,请重新输入');                }                Redis::del($key);            }            // 验证线下付款密码            if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {                $password = $params['offline_password'];                if ($password != '666888') {                    throw new BusinessException('密码错误,请重新输入');                }            }            // 下单账户            if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {                if (Member::where('member_mobile', $params['mobile'])->exists()) {                    throw new BusinessException('会员已存在');                }                $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');                // 创建会员                MemberService::createMember($params);            } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {                $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');            }            if (empty($params['join_order_member_id'])) {                throw new BusinessException('检查下单账户');            }            $qrcodePayAmount = 0;            $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');            $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');            $systemStatus = 'SENDING';  // 待发货            // 立即结算            if ($params['settlement_now'] == 'Y') {                if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {                    $params['order_is_complete'] = 'Y';                    $systemStatus = 'DONE';                }                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {                    $params['order_is_complete'] = 'N';                    $systemStatus = "WAITING";                }            }            if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {                if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {                    $params['pay_category'] = $params['pay_category_sub'];                }                $params['order_status_system'] = $systemStatus;                $params['order_status_payment'] = 'SUCCESS';            } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') {    // 余额支付                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'CASH')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                if ($params['order_amount_pay'] > $account->member_account_surplus) {                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);                    $account->member_account_surplus = 0;                    $account->member_account_added = $cut;                } else {                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                }                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();                if ($params['pay_constitute'] == 'N') {                    $params['order_status_system'] = $systemStatus;                    $params['order_status_payment'] = 'SUCCESS';                }            } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') {    // 余额支付                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'VIP')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                if ($params['order_amount_pay'] > $account->member_account_surplus) {                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);                    $account->member_account_surplus = 0;                    $account->member_account_added = $cut;                } else {                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                }                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();                if ($params['pay_constitute'] == 'N') {                    $params['order_status_system'] = $systemStatus;                    $params['order_status_payment'] = 'SUCCESS';                }            } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') {  // 福利账户                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'WELFARE')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $account->member_account_surplus = floatval($account->member_account_surplus);                if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {                    throw new BusinessException('账户余额不足');                }                if ($params['pay_constitute'] == 'N') {                    $params['order_status_system'] = $systemStatus;                    $params['order_status_payment'] = 'SUCCESS';                }                // 福利账户 300 、 700                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {                    $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])                        ->get()                        ->toArray();                    $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');                    $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->where('pay_category', 'REFUND')                        ->get()                        ->toArray();                    $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');                    $paySum = 0;                    foreach ($payDetailArray as $key => $item) {                        if (isset($refundPayDetailArray[$key])) {                            $paySum = $paySum + ($item - $refundPayDetailArray[$key]);                            continue;                        }                        $paySum = $paySum + $item;                    }                    if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {                        Db::rollBack();                        return json_fail('超出福利限额');                    }                } else {                    $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])                        ->get()                        ->toArray();                    $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');                    $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->where('pay_category', 'REFUND')                        ->get()                        ->toArray();                    $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');                    $paySum = 0;                    foreach ($payDetailArray as $key => $item) {                        if (isset($refundPayDetailArray[$key])) {                            $paySum = $paySum + ($item - $refundPayDetailArray[$key]);                            continue;                        }                        $paySum = $paySum + $item;                    }                    if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {                        throw new BusinessException('超出福利限额');                    }                }                $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();            } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') {  // 储值卡账户                $cardNbr = $params['card_nbr'];                if (!$cardNbr) {                    throw new BusinessException('账户异常');                }                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_nbr', $cardNbr)                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                if ($params['order_amount_pay'] > $account->member_account_surplus) {                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);                    $account->member_account_surplus = 0;                    $account->member_account_added = $cut;                } else {                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                }                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();                if ($params['pay_constitute'] == 'N') {                    $params['order_status_system'] = $systemStatus;                    $params['order_status_payment'] = 'SUCCESS';                }            }            if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) {     // 付款码                if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {                    $params['order_status_system'] = $systemStatus;                    $params['order_status_payment'] = 'SUCCESS';                }                // 不组合或者组合后需要付款码的金额>0                if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {                    $result = OrderService::qrcodePay($params);                    $result = json_encode($result);                    $params['pay_json_response'] = $result;                    $result = json_decode($result, true);                    $prefix = substr($params['qrcode_nbr'], 0, 2);                    if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {                        $params['pay_category'] = 'WXPAY';                        if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {                            $params['order_status_system'] = 'PAYING';                            $params['order_status_payment'] = 'PENDING';                            $params['order_is_complete'] = 'N';//                            Db::rollBack();//                            return json_fail('支付失败');                        } else {                            $params['order_status_system'] = $systemStatus;                            $params['order_status_payment'] = 'SUCCESS';                        }                    } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {                        $params['pay_category'] = 'ALIPAY';                        if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {                            $params['order_status_system'] = 'PAYING';                            $params['order_status_payment'] = 'PENDING';                            $params['order_is_complete'] = 'N';//                            Db::rollBack();//                            return json_fail('支付失败');                        } else {                            $params['order_status_system'] = $systemStatus;                            $params['order_status_payment'] = 'SUCCESS';                        }                    } else {                        throw new BusinessException('付款码无效');                    }                }            }            $orderConfigJson = [];            // 优惠            if (!empty($params['preferential'])) {                $orderConfigJson['preferential'] = $params['preferential'];            }            // 配送方式            if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店                $orderConfigJson['premises'] = $params['dept_premises_id'];            }            if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {                $params['submit_premises_id'] = $premises->dept_id;            }            $params['order_config_json'] = json_encode($orderConfigJson);            // 写入订单            $this->insertMain($params);            Db::commit();            // 触发事件            if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {                Event::dispatch('order.complete', $params);            }            // 触发事件            if ($params['order_status_payment'] == 'SUCCESS') {                // 上级提成                OrderService::splitOrderCommission($params);                // 入收支明细表                OrderService::splitOrderStatisticsInOut($params);            }            if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {                _syslog("订单", "支付异常,检查是否有轮询");                // 恢复优惠券到已占用                if (!is_array($couponUseJson)) {                    $couponUseJson = json_decode($couponUseJson, true);                }                $this->changeOrderCouponStatus($couponUseJson, 'WAITING');                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);            }            _syslog("订单", "创建订单成功");            return json_success('创建订单成功');        } catch (BusinessException $e) {            Db::rollBack();            dump($e->getMessage());            dump($e->getTrace());            _syslog("订单", $e->getMessage());            return json_fail($e->getMessage());        } catch (\Exception $e) {            Db::rollBack();            dump($e->getMessage());            dump($e->getTrace());            _syslog("订单", "创建订单失败");            return json_fail('创建订单失败');        }    }    /**     * 组合支付下单     */    public function insertConstitute(Request $request): Response    {        $params = $request->post();        $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));        $premises = [];        if (!empty($params['dept_premises_id'])) {            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();        }        Db::beginTransaction();        try {            // 使用优惠券            $couponUseJson = [];            if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {                $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);                if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {                    throw new BusinessException("计算优惠后,实付金额错误!");                }                // 组装优惠券使用数据,存主表优惠里                if (!empty($couponResult['use_coupon_json'])) {                    $couponUseJson = $couponResult['use_coupon_json'];                }            }            // 存储优惠信息            $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));            $orderAmountPay = $params['order_amount_pay'];            $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');            // 验证金额            $constituteAmount = 0;            foreach ($params['pay_category_constitute_list'] as $item) {                $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);            }            if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {                throw new BusinessException('组合支付金额与应付金额不一致');            }            $params['goods_classify'] = $goodsClassifys[0];            // 验证库存            OrderService::checkGoodsStorage($params);            // 余额、福利、储值卡 验证短信            if (!empty($params['pay_category_constitute'])                && !in_array('OFFLINE', $params['pay_category_constitute'])                && !in_array('MONEY', $params['pay_category_constitute'])                && !in_array('QRCODE', $params['pay_category_constitute'])                && (in_array('CASH', $params['pay_category_constitute'])                    || in_array('CARD', $params['pay_category_constitute'])                    || in_array('WELFARE', $params['pay_category_constitute']))) {                $code = $params['sms_code'];                if (!$code) {                    throw new BusinessException("验证码错误,请重新输入");                }                $member = Member::find($params['join_order_member_id']);                $mobile = $member->member_mobile;                $key = "SMS:CODE:ORDER_PAY:" . $mobile;                $redisCode = Redis::get($key);                if ($redisCode != $code && $code != '123456') {                    throw new BusinessException("验证码错误,请重新输入");                }                Redis::del($key);            }            // 验证线下付款密码            if (!empty($params['pay_category_constitute'])                && in_array('OFFLINE', $params['pay_category_constitute'])                || (in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']))) {                $password = $params['offline_password'];                if ($password != '666888') {                    throw new BusinessException("密码错误,请重新输入");                }            }            // 下单账户            if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {                if (Member::where('member_mobile', $params['mobile'])->exists()) {                    throw new BusinessException("会员已存在");                }                $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');                // 创建会员                MemberService::createMember($params);            } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {                $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');            }            if (empty($params['join_order_member_id'])) {                throw new BusinessException("检查下单账户");            }            $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');            $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');            $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');            $systemStatus = 'SENDING';  // 待发货            // 立即结算            if ($params['settlement_now'] == 'Y') {                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {                    $params['order_is_complete'] = 'N';                    $systemStatus = "WAITING";                }            }            $params['pay_detail_item'] = [];            $wxAndAliPayStatus = 'Y';            if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {      // 线下支付                $params['order_status_system'] = $systemStatus;                $params['order_status_payment'] = 'SUCCESS';                $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';                // 线下支付金额                if (isset($constituteList['OFFLINE'])) {                    $params['order_amount_pay'] = $constituteList['OFFLINE'];                    // 生成支付记录                    $params['pay_detail_item'][] = $params;//                    OrderService::createPayDetail($params);                }                $params['order_amount_pay'] = $orderAmountPay;            }            if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {      // 现金支付                $params['order_status_system'] = $systemStatus;                $params['order_status_payment'] = 'SUCCESS';                $params['pay_category'] = 'MONEY';                // 现金支付金额                if (isset($constituteList['MONEY'])) {                    $params['order_amount_pay'] = $constituteList['MONEY'];                    // 生成支付记录                    $params['pay_detail_item'][] = $params;//                    OrderService::createPayDetail($params);                }                $params['order_amount_pay'] = $orderAmountPay;            }            if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) {    // 余额支付                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'CASH')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException("账户异常");                }                $amount = $account->member_account_surplus + $account->member_account_added;                if (isset($constituteList['CASH'])) {                    $params['order_amount_pay'] = $constituteList['CASH'];                    $params['pay_category'] = $params['join_order_member_id'] . '-CASH';                }                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException("账户余额不足");                }//                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {//                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;//                    $params['order_amount_pay'] = $amount;//                }//                if ($params['order_amount_pay'] > $account->member_account_surplus) {//                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);//                    $account->member_account_surplus = 0;//                    $account->member_account_added = $cut;//                } else {//                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];//                }//                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];//                $account->save();                // 余额账户扣款数据                $params['waitToPayAccount']['cash'] = [                    'group_id' => $params['orderGroupId'],                    'member_id' => $params['join_order_member_id'],                    'amount' => $constituteList['CASH'],                    'nbr' => $params['join_order_member_id'] . '-CASH'                ];                $params['order_status_system'] = $systemStatus;                $params['order_status_payment'] = 'SUCCESS';                // 生成支付记录                $params['pay_detail_item'][] = $params;                $params['order_amount_pay'] = $orderAmountPay;            }            if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) {    // 储值卡账户                $cardNbr = $params['card_nbr'];                if (!$cardNbr) {                    throw new BusinessException("储值卡账户异常");                }                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_nbr', $cardNbr)                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException("储值卡账户异常");                }                $amount = $account->member_account_surplus + $account->member_account_added;                // 储值卡账户支付金额                if (isset($constituteList['CARD'])) {                    $params['order_amount_pay'] = $constituteList['CARD'];                    $params['pay_category'] = $cardNbr;                }                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException("储值卡账户余额不足");                }//                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {//                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;//                    $params['order_amount_pay'] = $amount;//                }////                if ($params['order_amount_pay'] > $account->member_account_surplus) {//                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);//                    $account->member_account_surplus = 0;//                    $account->member_account_added = $cut;//                } else {//                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];//                }//                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];//                $account->save();                // 储值卡账户扣款数据                $params['waitToPayAccount']['card'] = [                    'group_id' => $params['orderGroupId'],                    'member_id' => $params['join_order_member_id'],                    'amount' => $constituteList['CARD'],                    'nbr' => $params['join_order_member_id'] . '-CARD'                ];                $params['order_status_system'] = $systemStatus;                $params['order_status_payment'] = 'SUCCESS';                // 生成支付记录                $params['pay_detail_item'][] = $params;                $params['order_amount_pay'] = $orderAmountPay;            }            //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])            // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){     // 付款码            if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) {     // 付款码                // 需要付款码的金额>0                if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {                    // 付款码支付金额                    $params['order_amount_pay'] = $constituteList['QRCODE'];                    // 调支付                    $result = OrderService::qrcodePay($params);                    $result = json_encode($result);                    $params['pay_json_response'] = $result;                    $result = json_decode($result, true);                    $prefix = substr($params['qrcode_nbr'], 0, 2);                    if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {                        $params['pay_category'] = 'WXPAY';                        if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {                            // 标记支付状态                            $wxAndAliPayStatus = 'N';                            $params['order_status_system'] = 'PAYING';                            $params['order_status_payment'] = 'PENDING';                            $params['order_is_complete'] = 'N';//                            Db::rollBack();//                            return json_fail('支付失败');                        } else {                            $params['order_status_system'] = $systemStatus;                            $params['order_status_payment'] = 'SUCCESS';                        }                    } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {                        $params['pay_category'] = 'ALIPAY';                        if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {                            // 标记支付状态                            $wxAndAliPayStatus = 'N';                            $params['order_status_system'] = 'PAYING';                            $params['order_status_payment'] = 'PENDING';                            $params['order_is_complete'] = 'N';//                            Db::rollBack();//                            return json_fail('支付失败');                        } else {                            $params['order_status_system'] = $systemStatus;                            $params['order_status_payment'] = 'SUCCESS';                        }                    } else {                        throw new BusinessException("二维码错误");                    }                    // 生成支付记录                    $params['pay_detail_item'][] = $params;//                    OrderService::createPayDetail($params);                    // 账户支付的金额                    $params['order_amount_pay'] = $orderAmountPay;                }            }            $orderConfigJson = [];            // 优惠            if (!empty($params['preferential'])) {                $orderConfigJson['preferential'] = $params['preferential'];            }            // 配送方式            if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店                $orderConfigJson['premises'] = $params['dept_premises_id'];            }            $params['order_config_json'] = json_encode($orderConfigJson);            // 写入订单            $this->insertMain($params, $wxAndAliPayStatus);            Db::commit();            // 触发事件            if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {                Event::dispatch('order.complete', $params);            }            // 触发事件            if ($params['order_status_payment'] == 'SUCCESS') {                // 上级提成                OrderService::splitOrderCommission($params);                // 入收支明细表                OrderService::splitOrderStatisticsInOut($params);            }            if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {                _syslog("订单", "支付异常,检查是否有轮询");                // 恢复优惠券到已占用                if (!is_array($couponUseJson)) {                    $couponUseJson = json_decode($couponUseJson, true);                }                $this->changeOrderCouponStatus($couponUseJson, 'WAITING');                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);            }            _syslog("订单", "创建订单成功");            return json_success('创建订单成功');        } catch (BusinessException $e) {            Db::rollBack();            dump($e->getMessage());            _syslog("订单", $e->getMessage());            return json_fail($e->getMessage());        } catch (\Exception $e) {            Db::rollBack();            dump($e->getMessage());            _syslog("订单", "创建订单失败");            return json_fail('创建订单失败');        }    }    public function pay(Request $request)    {        $params = $request->post();        // 余额、福利、储值卡 验证短信        if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {            $code = $params['sms_code'];            if (!$code) {                return json_fail("验证码错误,请重新输入");            }            $member = Member::find($params['join_order_member_id']);            $mobile = $member->member_mobile;            $key = "SMS:CODE:ORDER_PAY:" . $mobile;            $redisCode = Redis::get($key);            if ($redisCode != $code && $code != '123456') {                return json_fail("验证码错误,请重新输入");            }            Redis::del($key);        }        // 验证线下付款密码        if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {            $password = $params['offline_password'];            if ($password != '666888') {                return json_fail("密码错误,请重新输入");            }        }        $order = Order::where('order_id', $params['order_id'])->first();        $oldOrderStatus = $order->order_status_system;        if (!$order) {            return json_fail('订单异常');        }        if ($order->order_status_system != 'PAYING') {            return json_fail('订单不是可支付状态');        }        if (!empty($order->order_config_json)) {            $orderConfigJson = json_decode($order->order_config_json, true);            if (isset($orderConfigJson['premises'])) {                $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();                if (!empty($premises)) {                    $params['submit_premises_id'] = $premises->dept_id;                }            }        }        $params['orderId'] = $params['order_id'];        $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');        $order->order_groupby = $params['orderGroupId'];        $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])            ->select('goods_id', 'goods_name', 'goods_classify')            ->first();        if (!$goods) {            return json_fail('产品数据异常');        }        $goods = $goods->toArray();        $params['goods_classify'] = $goods['goods_classify'] ?? '';        $systemStatus = 'SENDING';  // 待发货        // 立即结算        if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {            $order->order_is_complete = 'Y';            $systemStatus = 'DONE';        }        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {            $params['order_is_complete'] = 'N';            $systemStatus = "WAITING";        }//        if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {//            $systemStatus = "WAITING";//        }        Db::beginTransaction();        try {            // 使用优惠券            $couponUseJson = [];            $discountJson = [];            if (!empty($order->order_discount_json)) {                $discountJson = json_decode($order->order_discount_json, true);                foreach ($discountJson as $item) {                    if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {                        throw new BusinessException("计算优惠后,实付金额错误!");                    }                }                $couponUseJson = $discountJson;                $this->changeOrderCouponStatus($couponUseJson, 'USED');                // 释放下单时选的优惠券//                $order->order_discount_json = $this->releaseCoupon($discountJson);            }            if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {                $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);                if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {                    throw new BusinessException("计算优惠后,实付金额错误!");                }                // 组装优惠券使用数据,存主表优惠里                if (!empty($couponResult['use_coupon_json'])) {                    $couponUseJson = $couponResult['use_coupon_json'];                }            }            // 存储优惠信息            if (empty($discountJson)) {                $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));            }            // 组合支付时,付款码应收金额            $qrcodePayAmount = 0;            if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {                $order->order_status_system = $systemStatus;                $order->order_status_payment = 'SUCCESS';                if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {                    $params['pay_category'] = $params['pay_category_sub'];                }            } else if ($params['pay_category'] == 'CASH') {    // 余额支付                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'CASH')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;                    $params['order_amount_pay'] = $amount;                }                if ($params['order_amount_pay'] > $account->member_account_surplus) {                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);                    $account->member_account_surplus = 0;                    $account->member_account_added = $cut;                } else {                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                }                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {                    $order->order_status_system = $systemStatus;                    $order->order_status_payment = 'SUCCESS';                }            } else if ($params['pay_category'] == 'VIP') {    // 余额支付                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'VIP')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;                    $params['order_amount_pay'] = $amount;                }                if ($params['order_amount_pay'] > $account->member_account_surplus) {                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);                    $account->member_account_surplus = 0;                    $account->member_account_added = $cut;                } else {                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                }                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {                    $order->order_status_system = $systemStatus;                    $order->order_status_payment = 'SUCCESS';                }            } else if ($params['pay_category'] == 'WELFARE') {  // 福利账户                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'WELFARE')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $account->member_account_surplus = floatval($account->member_account_surplus);                if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {                    throw new BusinessException('账户余额不足');                }                if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {                    $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;                    $params['order_amount_pay'] = $account->member_account_surplus;                }                if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {                    $order->order_status_system = $systemStatus;                    $order->order_status_payment = 'SUCCESS';                }                // 福利账户 300 、 700                if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {                    $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])                        ->get()                        ->toArray();                    $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');                    $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->where('pay_category', 'REFUND')                        ->get()                        ->toArray();                    $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');                    $paySum = 0;                    foreach ($payDetailArray as $key => $item) {                        if (isset($refundPayDetailArray[$key])) {                            $paySum = $paySum + ($item - $refundPayDetailArray[$key]);                            continue;                        }                        $paySum = $paySum + $item;                    }                    if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {                        throw new BusinessException('超出福利限额');                    } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {                        $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);                        $params['order_amount_pay'] = (700 - $paySum);                    }                } else {                    $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])                        ->get()                        ->toArray();                    $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');                    $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])                        ->where('pay_status', 'SUCCESS')                        ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')                        ->where('pay_category', 'REFUND')                        ->get()                        ->toArray();                    $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');                    $paySum = 0;                    foreach ($payDetailArray as $key => $item) {                        if (isset($refundPayDetailArray[$key])) {                            $paySum = $paySum + ($item - $refundPayDetailArray[$key]);                            continue;                        }                        $paySum = $paySum + $item;                    }                    if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {                        throw new BusinessException('超出福利限额');                    } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {                        $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);                        $params['order_amount_pay'] = (300 - $paySum);                    }                }                $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();            } else if ($params['pay_category'] == 'CARD') {  // 储值卡账户                $cardNbr = $params['card_nbr'];                if (!$cardNbr) {                    throw new BusinessException('账户异常');                }                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_nbr', $cardNbr)                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {                    $qrcodePayAmount = $params['order_amount_pay'] - $amount;                    $params['order_amount_pay'] = $amount;                }                if ($params['order_amount_pay'] > $account->member_account_surplus) {                    $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);                    $account->member_account_surplus = 0;                    $account->member_account_added = $cut;                } else {                    $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];                }                $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];                $account->save();                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {                    $order->order_status_system = $systemStatus;                    $order->order_status_payment = 'SUCCESS';                }            }            if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) {     // 付款码                // 提交过来的支付分类                $submitPayCategory = $params['pay_category'];                // 账户支付的金额                $accountAmount = $params['order_amount_pay'];                if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {                    // 组合支付,改成需要付款码需要支付的金额                    $params['order_amount_pay'] = $qrcodePayAmount;                }                // 去支付                $result = OrderService::qrcodePay($params);                $result = json_encode($result);                $params['pay_json_response'] = $result;                $result = json_decode($result, true);                $prefix = substr($params['qrcode_nbr'], 0, 2);                if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {                    $params['pay_category'] = 'WXPAY';                    if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {                        $order->order_status_system = $oldOrderStatus;                        $order->order_status_payment = 'PENDING';                        $order->order_is_complete = 'N';//                        Db::rollBack();//                        return json_fail('支付失败');                    } else {                        $order->order_status_system = $systemStatus;                        $order->order_status_payment = 'SUCCESS';                    }                } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {                    $params['pay_category'] = 'ALIPAY';                    if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {                        $order->order_status_system = $oldOrderStatus;                        $order->order_status_payment = 'PENDING';                        $order->order_is_complete = 'N';//                        Db::rollBack();//                        return json_fail('支付失败');                    } else {                        $order->order_status_system = $systemStatus;                        $order->order_status_payment = 'SUCCESS';                    }                } else {                    throw new BusinessException('付款码无效');                }                // 账户支付的金额                $params['order_amount_pay'] = $accountAmount;            }            $orderConfigJson = [];            if (!empty($order->order_config_json)) {                $orderConfigJson = json_decode($order->order_config_json, true);            }            $orderConfigJson['preferential'] = $params['preferential'] ?? '';            $order->order_config_json = json_encode($orderConfigJson);            $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;            // 主订单            $order->save();            // sheet            if ($order->order_status_payment == 'SUCCESS') {                OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([                    'order_sheet_status' => $systemStatus,                ]);            }            // payDetail            // 不组合支付,那就只有一条支付记录 先删,再加            PayDetail::where('join_pay_order_id', $order->order_groupby)                ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])                ->delete();            $payData = [                'pay_amount' => $params['order_amount_pay']            ];            if ($order->order_status_payment == 'SUCCESS') {                $payData['pay_paytimes'] = date('Y-m-d H:i:s');                $payData['pay_status'] = 'SUCCESS';            }            if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {                $payData['pay_prepayid'] = $params['pay_category'];                $payData['pay_json_response'] = $params['pay_json_response'];            } else if ($params['pay_category'] == 'CASH') {                $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';            } else if ($params['pay_category'] == 'WELFARE') {                $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';            } else if ($params['pay_category'] == 'VIP') {                $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';            } else if ($params['pay_category'] == 'CARD') {                $payData['pay_prepayid'] = $params['card_nbr'];            } else if ($params['pay_category'] == 'OFFLINE') {                $payData['pay_prepayid'] = 'OFFLINE';            } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {                $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';            } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {                $payData['pay_prepayid'] = 'OFFLINE_WXPAY';            } else if ($params['pay_category'] == 'MONEY') {                $payData['pay_prepayid'] = 'MONEY';            }            $payData['join_pay_member_id'] = $params['join_order_member_id'];            $payData['join_pay_order_id'] = $order->order_groupby;            $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';            $payData['pay_category'] = $params['goods_classify'] ?? '';            $payData['pay_paytimes'] = date('Y-m-d H:i:s');            $payData['pay_json_request'] = json_encode($params);   // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}            $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? (!empty($params['pay_json_response']) ? $params['pay_json_response'] : json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])) : '[]';            $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';            $payData['pay_addtimes'] = time();            PayDetail::insert($payData);            $writeOffDate = [];            $applyData = [];            // 有预约单,状态已完成            $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();            if ($order->order_status_payment == 'SUCCESS' && $appointment) {                $writeOffDate = OrderService::generateWriteOffData($params);                $applyData = OrderService::generateAppointmentApplyData($params);                $appointment->appointment_status = 'DONE';                $appointment->appointment_done_datetime = date('Y-m-d H:i:s');                $appointment->appointment_done_json = json_encode($writeOffDate);                if (empty($appointment->appointment_apply_datetime)) {                    $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');                }                if (empty($appointment->appointment_apply_json)) {                    $appointment->appointment_apply_json = json_encode($applyData);                }                if (empty($appointment->appointment_datetime)) {                    $appointment->appointment_datetime = date('Y-m-d');                }                $appointment->save();            }            // // 买的单个服务            if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {                foreach ($params['goodsContentList'] as $goods) {                    $params['join_sheet_goods_id'] = $goods['goods_id'];                    if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {                        $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');                        $params['order_sheet_num'] = $goods['nbr'];                        // 预约表                        for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {                            $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');                            // 入预约记录                            $this->insertAppointment($params, $writeOffDate, $applyData);                        }                        $goods['skuId'] = $goods['sku_id'];                        $goods['category'] = $goods['goods_classify'];                        // 权益表                        $this->insertMemberBenefit($params, $goods);                    } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') {  // 一个套餐买多个                        $params['packageId'] = $goods['goods_id'];                        $components = GoodsComponent::with([                            'goods' => function ($query) {                                $query->select('goods_id', 'goods_name', 'goods_classify');                            }                        ])->where('join_component_master_goods_id', $params['packageId'])                            ->get()                            ->toArray();                        foreach ($components as $component) {                            $componentJson = json_decode($component['goods_component_json'], true);                            $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];                            $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');                            $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];                            for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {                                $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');                                // 入预约记录                                $this->insertAppointment($params, $writeOffDate);                            }                            $goods['goods_id'] = $component['join_component_goods_id'];                            $goods['goods_name'] = $component['goods']['goods_name'];                            $goods['goods_classify'] = $component['goods']['goods_classify'];                            $goods['skuId'] = $goods['sku_id'];                            $goods['category'] = 'SERVICE';                            // 权益表                            $this->insertMemberBenefit($params, $goods);                        }                    }                }            }            Db::commit();            // 触发事件            if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {                // 完成订单                Event::dispatch('order.complete', $params);                // 会员升级//                Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);            }            if ($order->order_status_payment == 'SUCCESS') {                // 上级提成                Event::dispatch('commission.order', $params);                // 入收支明细表                $params['inout_category'] = '标准订单';                Event::dispatch('statistics.inout.in', $params);            }            // 打小票            if ($order->order_status_payment == 'SUCCESS') {                if (!empty($premises) && !empty($premises->dept_id)) {                    $voteData = [                        'func' => 'procActionToPrinter',                        'sign' => '',                        'data' => [                            'printer_premises' => $premises->dept_id,                            'printer_device' => ["收银"],                            'printer_action' => 'ExecPrintOrder',                            'printer_data' => [                                'order_id' => $params['orderId'],                                'order_batch' => ''                            ]                        ]                    ];//                    dump("小票参数", $voteData);                    http_post_json(getenv('VOTE_MENU_URL'), $voteData);                }            }            if ($order->order_status_payment != 'SUCCESS') {                _syslog("订单", "支付异常,检查是否有轮询");                // 恢复优惠券到已占用                if (!is_array($couponUseJson)) {                    $couponUseJson = json_decode($couponUseJson, true);                }                // 如果下单时就填了,不用恢复                if (empty($discountJson)) {                    $this->changeOrderCouponStatus($couponUseJson, 'WAITING');                }                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);            }            _syslog("订单", "订单支付成功");            return json_success('支付成功');        } catch (BusinessException $e) {            dump($e->getMessage());            Db::rollBack();            _syslog("订单", "订单支付失败:" . $e->getMessage());            return json_fail("支付失败:" . $e->getMessage());        } catch (\Exception $e) {            dump($e->getMessage());            Db::rollBack();            _syslog("订单", "订单支付失败");            return json_fail('支付失败');        }    }    /**     * 组合支付     */    public function payConstitute(Request $request)    {        $params = $request->post();        // 余额、福利、储值卡 验证短信        if (!empty($params['pay_category_constitute']) && !in_array('OFFLINE', $params['pay_category_constitute']) && !in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']) && (in_array('CASH', $params['pay_category_constitute']) || in_array('CARD', $params['pay_category_constitute']) || in_array('WELFARE', $params['pay_category_constitute']))) {            $code = $params['sms_code'];            if (!$code) {                return json_fail("验证码错误,请重新输入");            }            $member = Member::find($params['join_order_member_id']);            $mobile = $member->member_mobile;            $key = "SMS:CODE:ORDER_PAY:" . $mobile;            $redisCode = Redis::get($key);            if ($redisCode != $code && $code != '123456') {                return json_fail("验证码错误,请重新输入");            }            Redis::del($key);        }        // 验证线下付款密码        if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {            $password = $params['offline_password'];            if ($password != '666888') {                return json_fail("密码错误,请重新输入");            }        }        $order = Order::where('order_id', $params['order_id'])->first();        if (!$order) {            return json_fail('订单异常');        }        if ($order->order_status_system != 'PAYING') {            return json_fail('订单不是可支付状态');        }        if (!empty($order->order_config_json)) {            $orderConfigJson = json_decode($order->order_config_json, true);            if (isset($orderConfigJson['premises'])) {                $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();                if (!empty($premises)) {                    $params['submit_premises_id'] = $premises->dept_id;                }            }        }        $params['orderId'] = $params['order_id'];        $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');        $order->order_groupby = $params['orderGroupId'];        $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])            ->select('goods_id', 'goods_name', 'goods_classify')            ->first();        if (!$goods) {            return json_fail('产品数据异常');        }        $goods = $goods->toArray();        $params['goods_classify'] = $goods['goods_classify'];        $systemStatus = 'SENDING';  // 待发货        // 立即结算        if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {            $order->order_is_complete = 'Y';            $systemStatus = 'DONE';        }        if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {            $params['order_is_complete'] = 'N';            $systemStatus = "WAITING";        }        $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();        Db::beginTransaction();        try {// 使用优惠券            $couponUseJson = [];            $discountJson = [];            if (!empty($order->order_discount_json)) {                $discountJson = json_decode($order->order_discount_json, true);                foreach ($discountJson as $item) {                    if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {                        throw new BusinessException("计算优惠后,实付金额错误!");                    }                }                $couponUseJson = $discountJson;                $this->changeOrderCouponStatus($couponUseJson, 'USED');                // 释放下单时选的优惠券//                $order->order_discount_json = $this->releaseCoupon($discountJson);            }            if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {                $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);                if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {                    throw new BusinessException("计算优惠后,实付金额错误!");                }                // 组装优惠券使用数据,存主表优惠里                if (!empty($couponResult['use_coupon_json'])) {                    $couponUseJson = $couponResult['use_coupon_json'];                }            }            // 存储优惠信息            if (empty($discountJson)) {                $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));            }            $orderAmountPay = $params['order_amount_pay'];            $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额            $constituteAmount = 0;            foreach ($params['pay_category_constitute_list'] as $item) {                $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);            }            if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {                throw new BusinessException('组合支付金额与应付金额不一致');            }            $wxAndAliPayStatus = 'Y';            $waitToPayAccount = [];            // 清除订单的支付记录,重建            PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();            if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) {  //线下付款                $order->order_status_system = $systemStatus;                $order->order_status_payment = 'SUCCESS';                $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';                // 线下支付金额                if (isset($constituteList['OFFLINE'])) {                    $params['order_amount_pay'] = $constituteList['OFFLINE'];                    // 生成支付记录                    $params['order_status_payment'] = 'PENDING';                    OrderService::createProductPayConstituteDetail($params);                    $params['order_status_payment'] = 'SUCCESS';                }                $params['order_amount_pay'] = $orderAmountPay;            }            if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {  //现金付款                $order->order_status_system = $systemStatus;                $order->order_status_payment = 'SUCCESS';                $params['pay_category'] = 'MONEY';                // 线下支付金额                if (isset($constituteList['MONEY'])) {                    $params['order_amount_pay'] = $constituteList['MONEY'];                    // 生成支付记录                    $params['order_status_payment'] = 'PENDING';                    OrderService::createProductPayConstituteDetail($params);                    $params['order_status_payment'] = 'SUCCESS';                }                $params['order_amount_pay'] = $orderAmountPay;            }            if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) {    // 余额支付                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_classify', 'CASH')                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    throw new BusinessException('账户异常');                }                if (isset($constituteList['CASH'])) {                    $params['order_amount_pay'] = $constituteList['CASH'];                    $params['pay_category'] = $params['join_order_member_id'] . '-CASH';                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                // 余额账户扣款数据                $waitToPayAccount['cash'] = [                    'group_id' => $params['orderGroupId'],                    'member_id' => $params['join_order_member_id'],                    'amount' => $constituteList['CASH'],                    'nbr' => $params['join_order_member_id'] . '-CASH'                ];                // 生成支付记录                $params['order_status_payment'] = 'PENDING';                OrderService::createProductPayConstituteDetail($params);                $params['order_status_payment'] = 'SUCCESS';                $params['order_amount_pay'] = $orderAmountPay;                $order->order_status_system = $systemStatus;                $order->order_status_payment = 'SUCCESS';            }            if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) {    // 储值卡账户                $cardNbr = $params['card_nbr'];                if (!$cardNbr) {                    throw new BusinessException('账户异常');                }                $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])                    ->where('member_account_nbr', $cardNbr)                    ->where('member_account_status', 'ACTIVED')                    ->first();                if (!$account) {                    Db::rollBack();                    return json_fail('账户异常');                }                // 储值卡账户支付金额                if (isset($constituteList['CARD'])) {                    $params['order_amount_pay'] = $constituteList['CARD'];                    $params['pay_category'] = $cardNbr;                }                $amount = $account->member_account_surplus + $account->member_account_added;                if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {                    throw new BusinessException('账户余额不足');                }                // 储值卡账户扣款数据                $waitToPayAccount['card'] = [                    'group_id' => $params['orderGroupId'],                    'member_id' => $params['join_order_member_id'],                    'amount' => $constituteList['CARD'],                    'nbr' => $params['join_order_member_id'] . '-CARD'                ];                // 生成支付记录                $params['order_status_payment'] = 'PENDING';                OrderService::createProductPayConstituteDetail($params);                $params['order_status_payment'] = 'SUCCESS';                $params['order_amount_pay'] = $orderAmountPay;                $order->order_status_system = $systemStatus;                $order->order_status_payment = 'SUCCESS';            }            if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) {     // 付款码                if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {                    // 付款码支付金额                    $params['order_amount_pay'] = $constituteList['QRCODE'];                    // 调支付                    $result = OrderService::qrcodePay($params);                    $result = json_encode($result);                    $params['pay_json_response'] = $result;                    $result = json_decode($result, true);                    $prefix = substr($params['qrcode_nbr'], 0, 2);                    if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {                        $params['pay_category'] = 'WXPAY';                        if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {                            // 标记支付状态                            $wxAndAliPayStatus = 'N';                            $order->order_status_system = 'PAYING';                            $order->order_status_payment = 'PENDING';                            $order->order_is_complete = 'N';                            $params['order_status_payment'] = 'PAYING';                        } else {                            $order->order_status_system = $systemStatus;                            $order->order_status_payment = 'SUCCESS';                            $params['order_status_payment'] = 'SUCCESS';                        }                    } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {                        $params['pay_category'] = 'ALIPAY';                        if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {                            // 标记支付状态                            $wxAndAliPayStatus = 'N';                            $order->order_status_system = 'PAYING';                            $order->order_status_payment = 'PENDING';                            $order->order_is_complete = 'N';                            $params['order_status_payment'] = 'PAYING';                        } else {                            $order->order_status_system = $systemStatus;                            $order->order_status_payment = 'SUCCESS';                            $params['order_status_payment'] = 'SUCCESS';                        }                    } else {                        throw new BusinessException('付款码无效');                    }                }                // 生成支付记录                OrderService::createProductPayConstituteDetail($params);                // 账户支付的金额                $params['order_amount_pay'] = $orderAmountPay;            }            $orderConfigJson = [];            if (!empty($order->order_config_json)) {                $orderConfigJson = json_decode($order->order_config_json, true);            }            $orderConfigJson['preferential'] = $params['preferential'] ?? '';            $order->order_config_json = json_encode($orderConfigJson);            $order->order_amount_pay = $params['order_amount_pay'];            // 主订单            $order->save();            // sheet            if ($order->order_status_payment == 'SUCCESS') {                OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([                    'order_sheet_status' => $systemStatus,                ]);            }            if ($wxAndAliPayStatus == 'Y') {                PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([                    'pay_status' => 'SUCCESS',                    'pay_paytimes' => date('Y-m-d H:i:s')                ]);                // 扣款                foreach ($waitToPayAccount as $item) {                    $accountNbr = $item['nbr'];                    $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();                    $account->member_account_expend = $account->member_account_expend + $item['amount'];                    if ($account->member_account_surplus < $item['amount'] && strpos($accountNbr, 'CASH') !== false) {                        $account->member_account_added = $account->member_account_added - ($item['amount'] - $account->member_account_surplus);                        $account->member_account_surplus = 0;                    } else {                        $account->member_account_surplus = $account->member_account_surplus - $item['amount'];                    }                    $account->save();                }            }            $writeOffDate = [];            $applyData = [];            // 有预约单,状态已完成            $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first();            if ($order->order_status_payment == 'SUCCESS' && $appointment) {                $writeOffDate = OrderService::generateWriteOffData($params);                $applyData = OrderService::generateAppointmentApplyData($params);                $appointment->appointment_status = 'DONE';                $appointment->appointment_done_datetime = date('Y-m-d H:i:s');                $appointment->appointment_done_json = json_encode($writeOffDate);                if (empty($appointment->appointment_apply_datetime)) {                    $appointment->appointment_apply_datetime = date('Y-m-d H:i:s');                }                if (empty($appointment->appointment_apply_json)) {                    $appointment->appointment_apply_json = json_encode($applyData);                }                if (empty($appointment->appointment_datetime)) {                    $appointment->appointment_datetime = date('Y-m-d');                }                $appointment->save();            }            // 买单个服务            if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {                foreach ($params['goodsContentList'] as $goods) {                    $params['join_sheet_goods_id'] = $goods['goods_id'];                    if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {                        $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');                        $params['order_sheet_num'] = $goods['nbr'];                        // 预约表                        for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {                            $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');                            // 入预约记录                            $this->insertAppointment($params, $writeOffDate, $applyData);                        }                        $goods['skuId'] = $goods['sku_id'];                        $goods['category'] = $goods['goods_classify'];                        // 权益表                        $this->insertMemberBenefit($params, $goods);                    } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') {  // 一个套餐买多个                        $params['packageId'] = $goods['goods_id'];                        $components = GoodsComponent::with([                            'goods' => function ($query) {                                $query->select('goods_id', 'goods_name', 'goods_classify');                            }                        ])->where('join_component_master_goods_id', $params['packageId'])                            ->get()                            ->toArray();                        foreach ($components as $component) {                            $componentJson = json_decode($component['goods_component_json'], true);                            $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];                            $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');                            $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];                            for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {                                $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');                                // 入预约记录                                $this->insertAppointment($params, $writeOffDate);                            }                            $goods['goods_id'] = $component['join_component_goods_id'];                            $goods['goods_name'] = $component['goods']['goods_name'];                            $goods['goods_classify'] = $component['goods']['goods_classify'];                            $goods['skuId'] = $goods['sku_id'];                            $goods['category'] = 'SERVICE';                            // 权益表                            $this->insertMemberBenefit($params, $goods);                        }                    }                }            }            Db::commit();            // 触发事件            if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {                // 完成订单                Event::dispatch('order.complete', $params);                // 会员升级//                Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);            }            if ($order->order_status_payment == 'SUCCESS') {                // 上级提成                Event::dispatch('commission.order', $params);                // 入收支明细表                $params['inout_category'] = '标准订单';                Event::dispatch('statistics.inout.in', $params);            }            // 打小票            if ($order->order_status_payment == 'SUCCESS') {                if (!empty($premises) && !empty($premises->dept_id)) {                    $voteData = [                        'func' => 'procActionToPrinter',                        'sign' => '',                        'data' => [                            'printer_premises' => $premises->dept_id,                            'printer_device' => ["收银"],                            'printer_action' => 'ExecPrintOrder',                            'printer_data' => [                                'order_id' => $params['orderId'],                                'order_batch' => ''                            ]                        ]                    ];//                    dump("小票参数", $voteData);                    http_post_json(getenv('VOTE_MENU_URL'), $voteData);                }            }            if ($order->order_status_payment != 'SUCCESS') {                _syslog("订单", "支付异常,检查是否有轮询");                // 恢复优惠券到已占用                if (!is_array($couponUseJson)) {                    $couponUseJson = json_decode($couponUseJson, true);                }                // 如果下单时就填了,不用恢复                if (empty($discountJson)) {                    $this->changeOrderCouponStatus($couponUseJson, 'WAITING');                }                // 清除支付记录,恢复账户金额//                $this->restoreAccount($params['pay_detail_item']);                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);            }            _syslog("订单", "订单支付成功");            return json_success('支付成功');        } catch (\Exception $e) {            dump($e->getMessage());            Db::rollBack();            _syslog("订单", "订单支付失败");            return json_fail('支付失败');        }    }    /**     * @Desc     * @Author Gorden     * @Date 2024/6/7 10:30     *     * @param $params     * @return void     * @throws BusinessException     */    public function insertMain($params, $wxAndAliPayStatus = 'Y')    {        try {            if (empty($params['order_extend_json'])) {                $params['order_extend_json'] = [];            } else {                if (is_json($params['order_extend_json'])) {                    $params['order_extend_json'] = json_decode($params['order_extend_json'], true);                }            }            // 账户扣款            if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {                foreach ($params['waitToPayAccount'] as $account) {                    $this->deductAmount($account['nbr'], $account['amount']);                }            }            // 推荐人            $params['order_extend_json']['referee'] = $params['referee'] ?? '';            foreach ($params['goodsContentList'] as $goods) {                $discountJson = [];                if (!empty($params['order_discount_json'])) {                    $discountJson = json_decode($params['order_discount_json'], true);                    foreach ($discountJson as &$item) {                        if (!empty($item['coupon_value'])) {                            $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $item['coupon_value'], 2);                        }                    }                }                $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');                $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);//                $amountPay = round(floatval($goods['goods_sales_price']) * $goods['nbr'] * $params['order_ratio'], 2);                $data = [                    'order_id' => $orderId,                    'order_groupby' => $params['orderGroupId'],                    'join_order_member_id' => $params['join_order_member_id'],                    'order_name' => date('Y-m-d H:i:s') . '-订单',                    'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],                    'order_amount_pay' => $amountPay,                    'order_category' => $goods['goods_classify'],                    'order_classify' => $goods['goods_classify'],                    'order_is_complete' => $params['order_is_complete'] ?? 'N',                    'order_status_system' => $params['order_status_system'],                    'order_status_payment' => $params['order_status_payment'],                    'order_status_storage' => $params['order_status_storage'],                    'order_platform' => $params['order_platform'],                    'order_remark' => $params['order_remark'] ?? '',                    'order_discount_json' => json_encode($discountJson),                    'order_config_json' => $params['order_config_json'] ?? '[]',                    'order_express_json' => $params['order_express_json'] ?? '[]',                    'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',                    'order_addtimes' => time()                ];                Order::insert($data);                $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);                $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);                $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);                $this->insertExpressOne($params, $orderId);                // 写到权益里                if ($params['order_status_payment'] == 'SUCCESS') {                    $this->insertBenefitOne($params, $goods, $orderId);                }            }        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException('订单创建信息失败');        }    }    /**     * @Desc 扣除账户金额     * @Author Gorden     * @Date 2024/9/26 14:16     *     * @param $accountNbr     * @param $amount     * @return void     */    public function deductAmount($accountNbr, $amount)    {        try {            $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();            $account->member_account_expend = $account->member_account_expend + $amount;            if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {                $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);                $account->member_account_surplus = 0;            } else {                $account->member_account_surplus = $account->member_account_surplus - $amount;            }            $account->save();        } catch (\Exception $e) {            _syslog("下单扣款", "扣款失败");            throw new BusinessException("账户扣款失败");        }    }    /**     * @Desc 打小票     * @Author Gorden     * @Date 2024/9/24 9:35     *     * @param $params     * @param $premises     * @param $orderId     * @return void     */    public function printerTicket($params, $premises, $orderId)    {        // 打小票        if ($params['order_status_payment'] == 'SUCCESS') {            if (!empty($premises) && !empty($premises->dept_id)) {                $voteData = [                    'func' => 'procActionToPrinter',                    'sign' => '',                    'data' => [                        'printer_premises' => $premises->dept_id,                        'printer_device' => ["收银"],                        'printer_action' => 'ExecPrintOrder',                        'printer_data' => [                            'order_id' => $orderId,                            'order_batch' => ''                        ]                    ]                ];                http_post_json(getenv('VOTE_MENU_URL'), $voteData);            }        }    }    /**     * @Desc 单商品权益     * @Author Gorden     * @Date 2024/9/24 8:42     *     * @param $params     * @param $goods     * @return void     * @throws BusinessException     */    public function insertBenefitOne($params, $goods, $orderId)    {        $params['orderId'] = $orderId;        $writeOffDate = [];        $applyData = [];        if ($params['order_status_payment'] == 'SUCCESS') {            $params['orderId'] = $orderId;            $params['join_sheet_goods_id'] = $goods['goods_id'];            if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD']) && $params['delivery'] == 'ARRIVAL') {                $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');                $params['join_sheet_goods_sku_id'] = $goods['sku_id'];                $params['goods_id'] = $goods['goods_id'];                $params['order_sheet_num'] = $goods['nbr'];                // 预约表                for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {                    $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');                    // 入预约记录                    $this->insertAppointment($params, $writeOffDate, $applyData);                }                $goods['skuId'] = $goods['sku_id'];                $goods['category'] = $goods['goods_classify'];                // 权益表                $this->insertMemberBenefit($params, $goods);            }        }    }    /**     * @Desc     * @Author Gorden     * @Date 2024/6/7 10:25     *     * @param $params     * @return void     * @throws BusinessException     */    public function insertSheet($params)    {        try {            $orderSheetIds = [];            foreach ($params['goodsContentList'] as $goods) {                //{"unit": "份", "table": null, "premises": "15"}                $price = floatval($goods['goods_sales_price']);                $extendJson['unit'] = $goods['sku_name'];                if (isset($params['submit_premises_id'])) {                    $extendJson['premises'] = $params['submit_premises_id'];                }                if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {                    $extendJson['table'] = null;                }                $data = [                    'join_sheet_member_id' => $params['join_order_member_id'],                    'join_sheet_order_id' => $params['orderId'],                    'join_sheet_goods_id' => $goods['goods_id'],                    'join_sheet_goods_sku_id' => $goods['sku_id'],                    'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',                    'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',                    'order_sheet_num' => $goods['nbr'],                    'order_sheet_price' => $goods['goods_sales_price'],                    'order_sheet_amount' => $price * $goods['nbr'],                    'order_sheet_pay' => $price * $goods['nbr'],                    'order_sheet_task_status' => 'NONE',                    'order_sheet_remark' => $params['order_remark'] ?? '',                    'order_sheet_addtimes' => time(),                    'order_sheet_extend_json' => json_encode($extendJson)                ];                $orderSheetId = OrderSheet::insertGetId($data);                $orderSheetIds[] = $orderSheetId;                // 减库存,规格和总库存                if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {                    $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('库存不足');                    }                    $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);                    $goodsSku->save();                }                $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('库存不足');                }                $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];                $goodsRunning->save();            }//            return $orderSheetIds;        } catch (\support\exception\BusinessException $e) {            dump($e->getMessage() . '||' . $e->getLine());            throw new BusinessException($e->getMessage());        } catch (\Exception $e) {            dump($e->getMessage() . '||' . $e->getLine());            throw new BusinessException('订单创建失败');        }    }    /**     * @Desc 单条入库     * @Author Gorden     * @Date 2024/9/23 10:19     *     * @param $params     * @return array     * @throws BusinessException     */    public function insertSheetOne($params, $goods, $orderId, $amountPay)    {        try {            $orderSheetIds = [];//            foreach ($params['goodsContentList'] as $goods) {            //{"unit": "份", "table": null, "premises": "15"}            $price = floatval($goods['goods_sales_price']);            $extendJson['unit'] = $goods['sku_name'];            if (isset($params['submit_premises_id'])) {                $extendJson['premises'] = $params['submit_premises_id'];            }            if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {                $extendJson['table'] = null;            }            $data = [                'join_sheet_member_id' => $params['join_order_member_id'],                'join_sheet_order_id' => $orderId,                'join_sheet_goods_id' => $goods['goods_id'],                'join_sheet_goods_sku_id' => $goods['sku_id'],                'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',                'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',                'order_sheet_num' => $goods['nbr'],                'order_sheet_price' => $goods['goods_sales_price'],                'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),                'order_sheet_amount' => $price * $goods['nbr'],                'order_sheet_pay' => $amountPay,                'order_sheet_task_status' => 'NONE',                'order_sheet_remark' => $params['order_remark'] ?? '',                'order_sheet_addtimes' => time(),                'order_sheet_extend_json' => json_encode($extendJson)            ];            $orderSheetId = OrderSheet::insertGetId($data);            $orderSheetIds[] = $orderSheetId;            // 减库存,规格和总库存            if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {                $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('库存不足');                }                $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);                $goodsSku->save();            }            $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('库存不足');            }            $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];            $goodsRunning->save();//            }            return $orderSheetIds;        } catch (\support\exception\BusinessException $e) {            dump($e->getMessage() . '||' . $e->getLine());            throw new BusinessException($e->getMessage());        } catch (\Exception $e) {            dump($e->getMessage() . '||' . $e->getLine());            throw new BusinessException('订单创建失败');        }    }    /**     * @Desc     * @Author Gorden     * @Date 2024/6/7 10:35     *     * @param $params     * @return void     * @throws BusinessException     */    public function insertPayDetail($params)    {        try {            if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {                $payPrepayid = $params['pay_category'];            } else if ($params['pay_category'] == 'OFFLINE') {                $payPrepayid = 'OFFLINE';            } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {                $payPrepayid = 'OFFLINE_ALIPAY';            } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {                $payPrepayid = 'OFFLINE_WXPAY';            } else if ($params['pay_category'] == 'MONEY') {                $payPrepayid = 'MONEY';            } else {                $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];            }            $data = [                'join_pay_member_id' => $params['join_order_member_id'],                'join_pay_order_id' => $params['orderGroupId'],                'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',                'pay_category' => $params['goods_classify'],                'pay_amount' => $params['order_amount_pay'],                'pay_prepayid' => $payPrepayid,                'pay_paytimes' => date('Y-m-d H:i:s'),                'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',                'pay_json_request' => json_encode($params),                'pay_json_response' => $params['pay_json_response'] ?? '[]',                'pay_remark' => $params['order_remark'] ?? '',                'pay_addtimes' => time(),            ];            PayDetail::insert($data);        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException('创建支付记录失败');        }    }    /**     * @Desc 单条入库     * @Author Gorden     * @Date 2024/6/7 10:35     *     * @param $params     * @return void     * @throws BusinessException     */    public function insertPayDetailOne($params, $orderId, $amountPay, $goods)    {        try {            if (!empty($params['pay_detail_item'])) {                foreach ($params['pay_detail_item'] as $item) {                    $data = [                        'join_pay_member_id' => $item['join_order_member_id'],                        'join_pay_order_id' => $item['orderGroupId'],                        'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',                        'pay_category' => $goods['goods_classify'],                        'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),                        'pay_prepayid' => $item['pay_category'],                        'pay_paytimes' => date('Y-m-d H:i:s'),                        'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',                        'pay_json_request' => json_encode($item),                        'pay_json_response' => $item['pay_json_response'] ?? '[]',                        'pay_remark' => $item['order_remark'] ?? '',                        'pay_addtimes' => time(),                    ];                    PayDetail::insert($data);                }            } else {                if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {                    $payPrepayid = $params['pay_category'];                } else if ($params['pay_category'] == 'OFFLINE') {                    $payPrepayid = 'OFFLINE';                } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {                    $payPrepayid = 'OFFLINE_ALIPAY';                } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {                    $payPrepayid = 'OFFLINE_WXPAY';                } else if ($params['pay_category'] == 'MONEY') {                    $payPrepayid = 'MONEY';                } else {                    $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];                }                $data = [                    'join_pay_member_id' => $params['join_order_member_id'],                    'join_pay_order_id' => $params['orderGroupId'],                    'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',                    'pay_category' => $goods['goods_classify'],                    'pay_amount' => $amountPay,                    'pay_prepayid' => $payPrepayid,                    'pay_paytimes' => date('Y-m-d H:i:s'),                    'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',                    'pay_json_request' => json_encode($params),                    'pay_json_response' => $params['pay_json_response'] ?? '[]',                    'pay_remark' => $params['order_remark'] ?? '',                    'pay_addtimes' => time(),                ];                PayDetail::insert($data);            }        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException('创建支付记录失败');        }    }    /**     * @Desc     * @Author Gorden     * @Date 2024/6/7 10:50     *     * @param $params     * @return void     * @throws BusinessException     */    public function insertAppointment($params, $writeOffDate, $applyData = [])    {        try {            $data = [                'appointment_id' => $params['appointmentId'],                'join_appointment_member_id' => $params['join_order_member_id'],                'join_appointment_goods_id' => $params['join_sheet_goods_id'],                'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],                'join_appointment_order_id' => $params['orderId'],                'join_appointment_member_benefit_id' => $params['benefitId'],                'appointment_classify' => $params['goods_classify'],                'appointment_status' => 'INIT',                'appointment_category' => 'NORMAL',                'appointment_platform' => 'SYSTEM',                'appointment_addtimes' => time(),                'appointment_datetime' => '',                'appointment_apply_datetime' => '',                'appointment_apply_json' => '[]',                'appointment_done_datetime' => '',                'appointment_remark' => $params['order_remark'] ?? '',                'appointment_done_json' => '[]'            ];            Appointment::insert($data);        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException("创建权益记录失败");        }    }    /**     * @Desc     * @Author Gorden     * @Date 2024/6/7 11:05     *     * @param $params     * @param $goods     * @return void     * @throws BusinessException     */    public function insertMemberBenefit($params, $goods)    {        try {            $data = [                'member_benefit_id' => $params['benefitId'],                'join_benefit_member_id' => $params['join_order_member_id'],                'join_benefit_package_id' => $params['packageId'] ?? '',                'join_benefit_goods_id' => $goods['goods_id'],                'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',                'join_benefit_order_id' => $params['orderId'],                'member_benefit_status' => 'ACTIVED',                'member_benefit_category' => $goods['category'],                'member_benefit_name' => $goods['goods_name'],                'member_benefit_limit_count' => $params['order_sheet_num'],                'member_benefit_used_count' => 0,                'member_benefit_remark' => $params['order_remark'] ?? '',                'member_benefit_addtimes' => time()            ];            MemberBenefit::insert($data);        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException('创建会员权益失败');        }    }    public function saveExpress($params, $orderId)    {        try {            $express = new OrderExpress();            $express->order_express_type = $params['order_express_type'];            $express->join_express_order_id = $orderId;            $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;            $express->order_express_goods = $params['order_express_goods'];            $express->order_express_city = $params['order_express_city'];            $express->order_express_address = $params['order_express_address'];            $express->order_express_mobile = $params['order_express_mobile'] ?? '';            $express->order_express_telephone = $params['order_express_telephone'] ?? '';            $express->order_express_person = $params['order_express_person'] ?? '';            $express->order_express_company = $params['dept_premises_id'] ?? '';            $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';            $express->order_express_addtimes = time();            $express->save();        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException('物流信息保存失败');        }    }    /**     * @Desc 修改优惠券状态     * @Author Gorden     * @Date 2024/9/19 9:03     *     * @param $coupon     * @param $status     * @return void     */    private function changeOrderCouponStatus($coupon, $status)    {        if (!empty($coupon) && is_array($coupon)) {            $updateData['coupon_detail_status'] = $status;            if ($status == 'ACTIVED' || $status == 'WAITING') {                $updateData['coupon_detail_used_datetime'] = '';            } elseif ($status == 'USED') {                $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');            }            foreach ($coupon as $item) {                if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {                    foreach ($item['coupon_detail_id'] as $detailId) {                        CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])                            ->where('coupon_detail_id', $detailId)->update($updateData);                    }                }            }        }    }    private function discountRecord($orderDiscountJson, $params)    {        $json = [];        if (!empty($orderDiscountJson)) {            $json = json_decode($orderDiscountJson, true);        }        try {            if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {                if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {                    throw new BusinessException("抹零后实际支付金额错误");                }                $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];                $couponClassifyDesc = $couponClassify = '抹零';            } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {                if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {                    throw new BusinessException("餐厅前台优惠后实际支付金额错误");                }                $couponClassifyDesc = $couponClassify = '餐厅前台优惠';            } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {                if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {                    throw new BusinessException("折扣后实际支付金额错误");                }                $couponClassify = '折扣';                $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';                $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];            } else {                return $json;            }            $json[date('Y-m-d H:i:s')] = [                'coupon_id' => $params['coupon_id'] ?? null,                'coupon_value' => $params['order_discount_amount'] ?? '',                'coupon_classify' => $couponClassify,                'coupon_detail_id' => [$couponClassifyDesc],                'coupon_classify_en' => $params['preferential']            ];            return $json;        } catch (BusinessException $e) {            throw new BusinessException($e->getMessage());        } catch (\Exception $e) {            dump($e->getMessage());            throw new BusinessException("优惠数据错误");        }    }    /**     * @Desc 入配送记录     * @Author Gorden     * @Date 2024/9/23 10:45     *     * @param $params     * @return void     * @throws BusinessException     */    public function insertExpressOne($params, $orderId)    {        if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {            $params['order_express_type'] = '配送';            // 入配送            $this->saveExpress($params, $orderId);        } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {            $params['order_express_type'] = '自提';            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();            if (!$premises) {                throw new BusinessException('自提门店不存在');            }            $params['order_express_city'] = $premises->dept_city;            $params['order_express_address'] = $premises->dept_address;            $params['order_express_telephone'] = $premises->dept_telephone;            $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);            $this->saveExpress($params, $orderId);        } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {            $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();            $params['order_express_type'] = '到店';            if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {                $params['order_express_type'] = '堂食';            }            if (!$premises) {                throw new BusinessException('门店不存在');            }            $params['order_express_city'] = $premises->dept_city;            $params['order_express_address'] = $premises->dept_address;            $params['order_express_telephone'] = $premises->dept_telephone;            $this->saveExpress($params, $orderId);        }    }    /**     * @Desc 释放下单时选的优惠券     * @Author Gorden     * @Date 2024/9/19 9:56     *     * @param $coupon     * @return false|string     */    private function releaseCoupon($coupon)    {        if (!empty($coupon) && is_array($coupon)) {            $updateData = [                'coupon_detail_status' => 'ACTIVED',                'coupon_detail_used_datetime' => ''            ];            foreach ($coupon as $key => $item) {                if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {                    foreach ($item['coupon_detail_id'] as $detailId) {                        if (substr($detailId, 0, 4) == 'CUDT') {                            CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])                                ->where('coupon_detail_id', $detailId)                                ->where('coupon_detail_status', 'WAITING')                                ->update($updateData);                        }                    }                    unset($coupon[$key]);                }            }        }        return json_encode($coupon);    }}
 |