<?php
/**
 * @package merchant
 *
 * @author xaboy
 * @day 2020/5/30
 *
 *
 */

namespace app\common\repositories\merchant\order;

use app\common\dao\merchant\order\OrderMerchantDao;
use app\common\dao\system\merchant\MerchantDao;
use app\common\dao\user\UnionUsersDao;
use app\common\model\merchant\order\OrderMerchant;
use app\common\model\system\merchant\Merchant;
use app\common\repositories\BaseRepository;
use app\common\repositories\merchant\MerchantRepository;
use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\user\UnionUsersRepository;
use app\common\repositories\user\UserOfflineRechargeRepository;
use app\common\repositories\user\UserRepository;
use app\controller\api\entropybarter\User;
use app\controller\api\user\Im;
use app\traits\GzcApiRequest;
use Carbon\Carbon;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

/**
 * Class OrderMerchantRepository
 * @package app\common\repositories\merchant\order
 * @author php迷途小书童
 * @created 2021/1/16 10:41
 */
class OrderMerchantRepository extends BaseRepository
{
    use GzcApiRequest;

    /**
     * OrderMerchantRepository constructor.
     * @param OrderMerchantDao $dao
     */
    public function __construct(OrderMerchantDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @return array
     * @author php迷途小书童
     * @created 2021/1/16 10:41
     */
    public function getList(array $where, $page, $limit)
    {
        $query = $this->dao->search($where);
        $query1 = $this->dao->search($where);
        $statistics = $query1->field('sum(money) money,sum(service_money) service_money,sum(pension) pension')
            ->where('paid', 1)
            ->whereNull('refund_time')
            ->find();

        $count = $query->count();
        $list = $query->with(['merchant', 'merchant' => function ($query) {
            return $query->field('mer_id,mer_name,mer_avatar');
        }])->page($page, $limit)->select();
        $stat = [
            [
                'className' => 'el-icon-s-goods',
                'count' => $statistics->money,
                'field' => '元',
                'name' => '总支付金额'
            ],
            [
                'className' => 'el-icon-s-goods',
                'count' => $statistics->service_money,
                'field' => '元',
                'name' => '服务商返利'
            ],
            [
                'className' => 'el-icon-s-order',
                'count' => $statistics->pension ?: 0,
                'field' => '元',
                'name' => '养老金'
            ]
        ];
        return compact('count', 'list', 'stat', 'where');
    }

    /**
     * @return array
     * @author php迷途小书童
     * @created 2021/1/16 10:41
     */
    public function getMerchantList($uid, array $where, $page, $limit)
    {
        $merId = Db::name('merchant')->where('uid', $uid)->value('mer_id');
        $query = $this->dao->merchantSearch($merId, $where);
        $query1 = $this->dao->merchantSearch($merId, $where);
        $statistics = $query1->field('sum(money) money,sum(available) available,sum(swipe_fee) swipe_fee')
            ->where('mer_id', $merId)
            ->where('paid', 1)
            ->whereNull('refund_time')
            ->find();

        $count = $query->count();
        $list = $query->with(['merchant', 'merchant' => function ($query) {
            return $query->field('mer_id,mer_name,mer_avatar');
        }])->page($page, $limit)->select()->each(function ($item) {
            $item->actual = bcsub($item->money, ($item->available + $item->swipe_fee), 2);
//            switch($item->trade_type) {
//                case 'ALI':
//                    $item->broadcast = '支付宝收款'.$item->actual.'元';
//                    break;
//                case 'WX':
//                    $item->broadcast = '微信收款'.$item->actual.'元';
//                    break;
//                default:break;
//            }
            //语音内容
            $broadcast = systemConfig('broadcast');
            $item->broadcast = strtr($broadcast, ['{money}' => $item->actual]);
            return $item;
        });
        $stat = [
            [
                'className' => 'el-icon-s-goods',
                'count' => $statistics->money,
                'field' => '元',
                'name' => '实付金额'
            ],
            [
                'className' => 'el-icon-s-goods',
                'count' => bcsub($statistics->money, ($statistics->available + $statistics->swipe_fee), 2),
                'field' => '元',
                'name' => '实到金额'
            ],
            [
                'className' => 'el-icon-s-order',
                'count' => $statistics->swipe_fee ?: 0,
                'field' => '元',
                'name' => '手续费'
            ]
        ];
        return compact('count', 'list', 'stat', 'where');
    }

    /**
     * @return array
     * @author php迷途小书童
     * @created 2021/1/16 10:41
     */
    public function getMerchantListAdmin($merId, array $where, $page, $limit)
    {
        //        $merId=Db::name('merchant')->where('uid',$uid)->value('mer_id');
        $query = $this->dao->merchantSearch($merId, $where);
        $query1 = $this->dao->merchantSearch($merId, $where);
        $statistics = $query1->field('sum(money) money,sum(available) available,sum(swipe_fee) swipe_fee')
            ->where('mer_id', $merId)
            ->where('paid', 1)
            ->whereNull('refund_time')
            ->find();
        $count = $query->count();
        $list = $query->with(['merchant', 'merchant' => function ($query) {
            return $query->field('mer_id,mer_name,mer_avatar');
        }])->page($page, $limit)->select()->each(function ($item) {
            $item->actual = bcsub($item->money, ($item->available + $item->swipe_fee), 2);
            //            switch($item->trade_type) {
            //                case 'ALI':
            //                    $item->broadcast = '支付宝收款'.$item->actual.'元';
            //                    break;
            //                case 'WX':
            //                    $item->broadcast = '微信收款'.$item->actual.'元';
            //                    break;
            //                default:break;
            //            }
            //语音内容
            $broadcast = systemConfig('broadcast');
            $item->broadcast = strtr($broadcast, ['{money}' => $item->actual]);
            return $item;
        });
        $stat = [
            [
                'className' => 'el-icon-s-goods',
                'count' => $statistics->money,
                'field' => '元',
                'name' => '实付金额'
            ],
            [
                'className' => 'el-icon-s-goods',
                'count' => bcsub($statistics->money, ($statistics->available + $statistics->swipe_fee), 2),
                'field' => '元',
                'name' => '实到金额'
            ],
            [
                'className' => 'el-icon-s-order',
                'count' => $statistics->swipe_fee ?: 0,
                'field' => '元',
                'name' => '手续费'
            ]
        ];
        return compact('count', 'list', 'stat', 'where');
    }

    /**
     * 获取单条订单信息
     * @return array|\think\Model|null
     * @author php迷途小书童
     * @created 2021/1/16 10:45
     */
    public function getOne(string $out_trade_no)
    {
        $where = ['out_trade_no' => $out_trade_no];
        return ($this->dao->getWhere($where));
    }

    /**
     * 获取单条订单信息
     * @return array|\think\Model|null
     * @author php迷途小书童
     * @created 2021/1/16 10:45
     */
    public function getOneById($id)
    {
        return ($this->dao->get($id));
    }

    /**
     * 创建订单
     * @return mixed
     * @author php迷途小书童
     * @created 2021/1/16 14:57
     */
    public function createOrder(array $params)
    {
        try {


            $give_money = Db::name('recharge')
                ->where('price', '<=', $params['money'])
                ->where('mer_id', $params['mer_id'])
                ->max('give') ?: 0;
//            $storeOrderRepository = app()->make(StoreOrderRepository::class);

            $base_commission = merchantConfig($params['mer_id'], 'base_commission');
            if (!$base_commission) {
                //若商家返佣比例不存在 则使用平台配置
                $base_commission = merchantConfig(0, 'extension_one_rate');
            }
            if($params['mer_id'] == 3425) $base_commission = 0;
            if($params['mer_id'] == 3447) $base_commission = 0;
            $merchant_data = Db::name('merchant')->where('mer_id', $params['mer_id'])->find();
            $is_dacang = 0;
            $avaiable = 0;
            $service_money = 0;
            $souxufees = 0;
//        if($merchant_data['hf_type']!=2&&$merchant_data['merchant_type']!=2){
//            if($merchant_data['merchant_type']==3){
//                $is_dacang=1;
//                //可分总佣金
//                $avaiable = bcmul($params['money'], bcdiv($base_commission, '100', 3), 2);
//                $pension=bcmul($avaiable,'0.5','2');
//                //手续费
//                $mer_money = bcsub($params['money'], $avaiable, 2);
//                $souxufees = bcmul($mer_money, bcdiv(merchantConfig('0', 'yanglao'), 100, 10),5);
//                $service_money=bcsub($avaiable,$pension,2);
//            }elseif($merchant_data['merchant_type']==1){
//                $is_dacang=2;
//                //可分总佣金
//                $avaiable = bcmul($params['money'], bcdiv($base_commission, '100', 3), 2);
//                $pension=bcmul($avaiable,'0.5','2');
//                //手续费
//                $mer_money = bcsub($params['money'], $avaiable, 2);
//                $souxufees = bcmul($mer_money, bcdiv(merchantConfig('0', 'yanglao'), 100, 10),5);
//                $service_money=bcsub($avaiable,$pension,2);
//            }
//        }else{
//            //sat刷卡手续费比例
//            $souxufee = systemConfig('yanglao');
//            $souxufees = bcmul($params['money'], $souxufee * 0.01,5);
//            $souxufees = round($souxufees,2);
//            $money = bcsub($params['money'], $souxufees, 2);
//            $avaiable = bcmul($money,  $base_commission * 0.01, 2);
//
//            //服务商分账的钱
//            $service_money = bcsub($avaiable, $pension, 2);
//        }
            //////10.12
            //线下手续费比例
            $souxufee = systemConfig('yanglao');
            //总可分佣金
            $avaiable = sprintf("%01.2f", $params['money'] * ($base_commission * 0.01));//四舍五入保留两位小数;
            //养老金
            $pension = sprintf("%01.2f", $avaiable * 0.3);
            if($params['mer_id']==496){
                //把一壶茶电子商务公司的收款码养老金调成2%
                $pension = sprintf("%01.2f", $params['money'] * 0.02);
                if($avaiable < $pension){
                    $avaiable=$pension;
                }
            }
//            $pension = $storeOrderRepository->ch_rebate($params['mer_id'], $params['money']);
            //商户货款=付款金额-返佣金额
            $mer_money = sprintf("%01.2f", $params['money'] - $avaiable);//四舍五入保留两位小数
            //手续费 仅商户货款的手续费 商户货款 * （线下手续费 * 0.01）
//            if($params['mer_id']==496) {
            //手续费 改成扣商户的
                $souxufees = sprintf("%01.2f", $params['money'] * ($souxufee * 0.01));
//            }else{
//                $souxufees = sprintf("%01.2f", $mer_money * ($souxufee * 0.01));
//            }
            //平台的钱 总可分佣金额 - 养老金
            $service_money = sprintf("%01.2f", $avaiable - $pension);

            //手续费
//            $souxufees = bcmul($params['money'], $souxufee * 0.01, 5);
//            $souxufees = round($souxufees, 2);
//            $money = bcsub($params['money'], $souxufees, 2);
//        $avaiable = bcmul($money,  $base_commission * 0.01, 2);
            ////////10.12
            //服务商分账的钱
//            $service_money = bcsub($avaiable, $pension, 2);

//            $souxufees = round($souxufees, 2);

            //trade_type微信支付:WX 支付宝支付:ALI 银联二维码支付:UNIONQR
            $paramOrder = [
                'merchant_user_id' => $params['merchant_user_id'],
                'mer_id' => $params['mer_id'],
                'merch_no' => $params['merch_no'],
                'pay_user_id' => $params['pay_user_id'],
                'nickname' => $params['nickname'],
                'avatar' => $params['avatar'],
                'out_trade_no' => $this->getNewOrderId($params['trade_type']),
                'money' => $params['money'],//付款金额
                'available' => $avaiable,//总可分佣金
                'service_money' => $service_money,//平台金额
                'give_money' => $give_money,
                'pension' => $pension, //养老金
                'swipe_fee' => $souxufees, //手续费
                'trade_type' => $params['trade_type'],
                'is_dacang' => $is_dacang,
                'mer_money' => $mer_money ?? 0,
                'mer_fanyong' => $avaiable ?? 0,
                'qr_num' => $params['qr_num'] ?? 0,
            ];
            if ($paramOrder['nickname'] == null) {
                switch ($paramOrder['trade_type']) {
                    case 'WX':
                        $paramOrder['nickname'] = 'WX' . time();
                        break;
                    case 'ALI':
                        $paramOrder['nickname'] = 'ZFB' . time();
                        break;
                    default:
                        $paramOrder['nickname'] = time();
                        break;
                }
            }
            if ($paramOrder['avatar'] == null) {
                $paramOrder['avatar'] = 'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png';
            }
            $order = Db::transaction(function () use ($paramOrder) {
                $merchantOrder = $this->dao->create($paramOrder);
                return $merchantOrder;
            });
            return $order;
        } catch (\Exception $e) {
            Db::name('log')->insert(['data' => '线下订单创建出错：' . $e->getFile() . '：' . $e->getLine() . '【' . $e->getMessage() . '】']);
        }
    }

    public function createOrder_276(array $params)
    {
        $pay_money = $params['money'];
        $souxufee = floatval(systemConfig('yanglao'));
        $souxufees = 0;
        if ($souxufee) {
            $souxufees = $params['money'] * $souxufee * 0.01;
        }
        $params['money'] = bcsub($params['money'], $souxufees, 2);
        if ($params['mer_id'] == 236) {
            $pension = bcmul($params['money'], bcmul('10', '0.01', 2), 2);
            $service_money = bcmul($params['money'], bcmul('45', '0.01', 2), 2);
        } elseif ($params['mer_id'] == 290) {
            $pension = bcmul($params['money'], bcmul('2', '0.01', 2), 2);
            $service_money = bcmul($params['money'], bcmul('50', '0.01', 2), 2);
        } else {
            $pension = bcmul($params['money'], bcmul('2', '0.01', 2), 2);
            $service_money = bcmul($params['money'], bcmul('38', '0.01', 2), 2);
        }

        //可分佣总金额
        $avaiable = bcadd($service_money, $pension, 2);
        //trade_type微信支付:WX 支付宝支付:ALI 银联二维码支付:UNIONQR
        $paramOrder = [
            'merchant_user_id' => $params['merchant_user_id'],
            'mer_id' => $params['mer_id'],
            'merch_no' => $params['merch_no'],
            'pay_user_id' => $params['pay_user_id'],
            'nickname' => $params['nickname'],
            'avatar' => $params['avatar'],
            'out_trade_no' => $this->getNewOrderId($params['trade_type']),
            'money' => $pay_money,
            'available' => $avaiable,
            'service_money' => $service_money,
            'give_money' => 0,
            'pension' => $pension,
            'swipe_fee' => $souxufees,
            'trade_type' => $params['trade_type'],
        ];
        if ($paramOrder['nickname'] == null) {
            switch ($paramOrder['trade_type']) {
                case 'WX':
                    $paramOrder['nickname'] = 'WX' . time();
                    break;
                case 'ALI':
                    $paramOrder['nickname'] = 'ZFB' . time();
                    break;
                default:
                    $paramOrder['nickname'] = time();
                    break;
            }
        }
//        Db::name('log')->insert(['data' => json_encode($paramOrder)]);
        if ($paramOrder['avatar'] == null) {
            $paramOrder['avatar'] = 'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png';
        }
        $order = Db::transaction(function () use ($paramOrder) {
            $merchantOrder = $this->dao->create($paramOrder);
            return $merchantOrder;
        });
        return $order;
    }

    /**
     * 更新订单
     * @return mixed
     * @author php迷途小书童
     * @created 2021/1/16 14:57
     */
    public function updateOrder($order, $params)
    {
        $update = Db::transaction(function () use ($order, $params) {
            return $this->dao->update($order->id, $params);
        });
        return $update;
    }

    /**
     * 获取唯一订单号
     * @return string
     * @author php迷途小书童
     * @created 2021/1/16 14:57
     */
    public function getNewOrderId($trade_type)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = $trade_type . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
        return $orderId;
    }

    /**
     * 回调处理
     * @return bool
     * @author php迷途小书童
     * @created 2021/1/16 15:12
     */
    public function doNotify($params)
    {
        $order = $this->dao->getWhere(['out_trade_no' => $params['out_trade_no']]);
        if (!$order)
            return false;
        if ($order->paid == 1)
            return true;

        $userRepository = app()->make(UserRepository::class);
        //修改订单状态
        Db::transaction(function () use ($order, $userRepository, $params) {
            $actuallyPaid = $order->money;//实付金额
            $mer_id = $order->mer_id;

            $order->paid = 1;
            $order->status = 1;
            $order->pay_time = date('Y-m-d H:i:s');
            $order->update_time = date('Y-m-d H:i:s');

            switch ($order->trade_type) {
                case 'WX':
                    $where = ['wechat_user_id' => $order->pay_user_id];
                    $order->weixin_no = $params['weixin_no'];
                    break;
                case 'ALI':
                    $where = ['ali_user_id' => $order->pay_user_id];
                    break;
            }
            $order->save();

            $MerchantRepository = app()->make(MerchantDao::class);
            $MerchantRepository->addrenqi($order->mer_id);
            //给线下用户积分
            Db::name('union_users')->where('unionid', $order->pay_user_id)->inc('recharge', $order->money)->update();
            //给商家通证金额和积分
            $this->Tongzheng_integral($order->available, $mer_id, $order->id);

            Merchant::getDB()->where('mer_id', $order->mer_id)->inc('sales', 1)->update();
//            //给线下充值用户余额
//            Db::name("merchant_user")
//                ->where('id', $order->merchant_user_id)
//                ->inc('money',$order->money)
//                ->update();
            $user = $userRepository->getOne($where);
            $this->doBind($user, $order);
            $this->doBroadcast($actuallyPaid, $mer_id);

            return true;
        });

        return true;
    }

    public function doNotifyHF($params)
    {
        $order = $this->dao->getWhere(['trade_no' => $params['order_no']]);
//        $order=json_decode(json_encode($order));

        if (!$order)
            return false;
        if ($order->paid == 1)
            return true;
        try {
            Db::name("log")->insert(['data' => '找到了订单']);//日志记录
            Db::name("log")->insert(['data' => json_encode($order)]);//日志记录
            Db::name("log")->insert(['data' => $order->pay_user_id]);
            $userRepository = app()->make(UserRepository::class);
            switch ($order->trade_type) {
                case 'WX':
                    $where = ['wechat_user_id' => $order->pay_user_id];
                    break;
                case 'ALI':
                    $where = ['ali_user_id' => $order->pay_user_id];
                    break;
            }
            $uid = Db::name('user')->where($where)->value('uid');
            $address = Db::name('user_address')->field('code_list,village_id')->where('uid',$uid)->where('is_default',1)->find();
            Db::name('order_merchant')->where(['trade_no' => $params['order_no']])->update([
                'uid' => $uid,
                'user_address_ids'=> !empty($address) ? $address['code_list'] . ',' . $address['village_id'] : ''
            ]);
            Db::name("log")->insert(['data' => '修改地址成功了']);//日志记录
            //修改订单状态
            Db::transaction(function () use ($order, $userRepository, $params) {
                Db::name("log")->insert(['data' => '2' . json_encode($order)]);
                $actuallyPaid = $order->money;//实付金额
                $pay_user_id = $order->pay_user_id;
                $mer_id = $order->mer_id;
                $id = $order->id;
                $order->paid = 1;
                $order->status = 1;
                $order->pay_time = date('Y-m-d H:i:s');
                $order->update_time = date('Y-m-d H:i:s');


                switch ($order->trade_type) {
                    case 'WX':
                        $where = ['wechat_user_id' => $order->pay_user_id];
                        $order->weixin_no = $params['out_trans_id'];
                        break;
                    case 'ALI':
                        $where = ['ali_user_id' => $order->pay_user_id];
                        break;
                }

                $order->save();

                $order = Db::name('order_merchant')->where(['trade_no' => $params['order_no']])->find();
                $merchant = Db::name('merchant')->where('mer_id', $mer_id)->find();
                if ($merchant['merchant_type'] == 2) {
                    return $this->DistributionCommission($order);
                }
                $order_data = [
                    'order_sn' => $order['out_trade_no'],
                    'order_id' => $order['id'],
                    'pay_price' => $order['money'],
                    'uid' => $order['uid'],
                    'mer_id' => $order['mer_id']
                ];
                $flag = 1;
                $this->offLineOrder($order['id']);
                if ($order['mer_id'] == 496) {
                    //一壶茶电子商务
                    // 8会员300  10高级会员3000 14合伙人商品10000 15股权商品10000 16合伙人+股权商品2000
                    $type=0;
                    switch ($order['money']){
                        case 300:
                            $type=8;
                            break;
                        case 3000:
                            $type=10;
                            break;
                    }
                    if ($type)
                        app()->make(StoreOrderRepository::class)->gongfuhuiyuan($order_data, 0, $type);
                }


                // 增加消费分 待释放
                if ($merchant['consumption_score'] == 1) {
                    $merchantRepository = app()->make(MerchantRepository::class);
                    $merchantRepository->consumptionScoreLog($order['mer_id'], 0, $order['money'], '用户到店消费', 3, 1, $order['id'], 1);
                    //商户表增加相应消费分
                    Db::name('merchant')->where('mer_id', $order['mer_id'])->inc('score', $order['money']);
                }


                Db::name("log")->insert(['data' => '3' . json_encode($order)]);
                Db::name("log")->insert(['data' => '订单修改完成']);//日志记录
                $MerchantRepository = app()->make(MerchantDao::class);
                $MerchantRepository->addrenqi($mer_id);
                //给线下用户积分
                Db::name('union_users')->where('unionid', $pay_user_id)->inc('recharge', $actuallyPaid)->update();
                //给商家通证金额和积分
                $this->Tongzheng_integral($actuallyPaid, $mer_id, $id);

                Merchant::getDB()->where('mer_id', $mer_id)->inc('sales', 1)->update();

                // $user = $userRepository->getOne($where);
                $user = Db::name('user')->where($where)->find();
                if($user){
                    $this->feidacang_fenyong($user, $order_data, 0);
                }
                $this->feidacang_fenyong_mer($user, $order_data, 0);
                // 增加商户分润
                $mer_fanyongbili = merchantConfig($order_data['mer_id'], 'base_commission');
                if ($mer_fanyongbili == 0) {
                    $mer_fanyongbili = merchantConfig(0, 'extension_one_rate');
                }
                $commission = bcmul($order_data['pay_price'], bcdiv($mer_fanyongbili, '100', 2), 2);
                $orderRepository = app()->make(StoreOrderRepository::class);
                $orderRepository->con_log_fenrun($merchant['uid'],$commission,$order_data['order_id'],10,'扫码下单产生分润值',1);
                $user = $userRepository->getOne($where);
                $order = (object)$order;
                $this->doBind($user, $order, $flag);//锁客
                Db::name("log")->insert(['data' => '绑定用户完成']);//日志记录
                // $this->doBroadcast($actuallyPaid, $mer_id);

                return true;
            });
        } catch (\Exception $e) {
            Db::name('log')->insert(['data' => '分配佣金错误：' . $e->getFile() . '：' . $e->getLine() . '【' . $e->getMessage() . '】']);
        }
        return true;
    }

    public function DistributionCommission($order)
    {
        try {
//            //有推荐者给奖励
            $res = 1;
            $res1 = 1;
//            $top=Db::name('merchant')->alias('m')->leftJoin('user u','u.uid=m.recommender')->where('m.mer_id',$order['mer_id'])->field('u.*')->find();
//            if($top['uid']){
//                $number=bcmul($order['money'],bcmul('30',0.01,2),2);
//                $top_data=[
//                    'uid'=>$top['uid'],
//                    'link_id'=>$order['id'],
//                    'pm'=>'1',
//                    'title'=>'推荐商户奖励',
//                    'category'=>'now_money',
//                    'type'=>'commission',
//                    'number'=>$number,
//                    'mark'=>'消费'.$order['money'].'获得推荐奖励'.$number,
//                    'status'=>'1',
//                    'type_shop'=>'0',
//                    'source'=>1,
//                    'order_sn'=>$order['out_trade_no'],
//                    'mer_id'=>$order['mer_id'],
//                ];
//                $res1=Db::name('user_bill')->insert($top_data);
//            }

            //用户注册了给养老金
//            if($order['uid']!=0){
////                $user=Db::name('user')->where('uid',$order['uid'])->find();
//                //环信im处理
////                $this->hxim($user['uid'],$order['mer_id']);
//                //用户
            $user_yanglao = [
                'uid' => $order['uid'],
                'link_id' => $order['id'],
                'pm' => '1',
                'title' => '养老金',
                'category' => 'now_money',
                'type' => 'commission',
                'number' => $order['pension'],
                'mark' => '消费' . $order['money'] . '获得' . $order['pension'] . '养老金',
                'status' => '1',
                'type_shop' => 10,
                'mer_id' => $order['mer_id'],
                'source' => 1,
                'order_sn' => $order['out_trade_no'],
                'commission_type' => 5
            ];
            $res1 = Db::name('user_bill')->insert($user_yanglao);
//                $user=Db::name('user')->where('uid',$order['uid'])->find();
//                $number=bcmul($order['money'],bcmul('30',0.01,2),2);
//                if(!empty($user['spread_uid'])){
//                    $top_data=[
//                    'uid'=>$user['spread_uid'],
//                    'link_id'=>$order['id'],
//                    'pm'=>'1',
//                    'title'=>'推广获得佣金',
//                    'category'=>'now_money',
//                    'type'=>'commission',
//                    'number'=>$number,
//                    'mark'=>'消费'.$order['money'].'获得推荐奖励'.$number,
//                    'status'=>'1',
//                    'type_shop'=>'0',
//                    'source'=>1,
//                    'order_sn'=>$order['out_trade_no'],
//                    'mer_id'=>$order['mer_id'],
//                    'commission_type'=>3,
//                ];
//                $res=Db::name('user_bill')->insert($top_data);
//                }
//            }
            $user = app()->make(User::class);

            $User_order = [
                'money' => $order['money'],
                'order_no' => $order['out_trade_no'],
                'uid' => $order['uid'],
                'id' => $order['id'],
                'mer_id' => $order['mer_id']
            ];
            $user->order($User_order, '2');
            $this->doBroadcast($order['money'], $order['mer_id']);
            if ($res && $res1) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $exception) {
            Db::name('log')->insert(['data' => '分配佣金错误：' . $exception->getFile() . '：' . $exception->getLine() . '【' . $exception->getMessage() . '】']);
        }
    }

    /**
     * @remarks 给商家通证金额和积分
     * @author Tang
     * @created 2021/8/26 9:18
     */
    public function Tongzheng_integral($money, $mer_id, $order_id, $pay_type = 1)
    {
        $integral = bcdiv($money, '5', 2);
        Db::name('merchant')->where('mer_id', $mer_id)->inc('tz_integral', $integral)->update();
        Db::name('merchant')->where('mer_id', $mer_id)->inc('tz_money', $money)->update();
        //通证金 star
        $title = '获得通证金';
        if ($pay_type == 1) {
            $make = '用户到店消费获得通证金';
        }
        $this->merchant_tz_log($money, $title, 2, $mer_id, $make, $order_id, $pay_type);
        //通证金 star
        //积分 star
        $title = '获得通证积分';
        if ($pay_type == 1) {
            $make = '用户到店消费获得通证积分';
        }
        $this->merchant_tz_log($integral, $title, 1, $mer_id, $make, $order_id, $pay_type);
        //积分 end
    }

    /**
     * @remarks //执行通证金的添加日志
     * @author Tang
     * @created 2021/8/26 9:17
     */

    public function merchant_tz_log($money, $title, $type, $mer_id, $make, $order_id, $pay_type)
    {
        $inserData = [
            'money' => $money,
            'title' => $title,
            'type' => $type,
            'mer_id' => $mer_id,
            'make' => $make,
            'order_id' => $order_id,
            'pay_type' => $pay_type
        ];
        Db::name('merchant_tz_log')->insert($inserData);
    }


    /**
     * 语音播报（收款音响百励华）
     * @author lin
     * @created 2021/3/25 17:38
     */
    public function doBroadcast($actuallyPaid, $mer_id)
    {
        Log::info('语音播报音响');
        try {
            //商户sn编号
            $sn = Db::name('merchant_yx')
                ->where('mer_id', $mer_id)
                ->where('status', 1)
                ->find();
            //语音内容

            $broadcast = merchantConfig($mer_id, 'broadcast_user');
            if (!$broadcast) {
                $broadcast = systemConfig('broadcast');
//            $broadcast = '储蓄宝用户到店消费{money}元';
            }

            $broadcast = strtr($broadcast, ['{money}' => $actuallyPaid]);
            $redis = new \Redis();
            $redis->pconnect('10.28.5.50', '6380');
            $redis->auth('zKiDUex5YC');
            $redis->select(1);
            $task = [
                'sn' => $sn['sn'],
                'data' => $broadcast,
            ];
            Log::info(serialize($task));
            $redis->publish('yx', serialize($task));
        } catch (\Throwable $e) {
            Log::info($e->getMessage());
        }
    }

    /**
     * 线下充值绑定用户加金额
     * @author php迷途小书童
     * @created 2021/2/1 10:58
     */
    public function doBind($user, $order, $flag = 0)
    {
        $unionUsersRepository = app()->make(UnionUsersRepository::class);
        $userRepository = app()->make(UserRepository::class);
        $unionUser = $unionUsersRepository->getWhere(['unionid' => $order->pay_user_id]);
        $userOfflineRechargeRepository = app()->make(UserOfflineRechargeRepository::class);
        if ($user) {
            Db::name('order_merchant')->where('id', $order->id)->update(['binds' => 1, 'uid' => $user->uid]);
            //锁定商户
            if (!$user->mer_id || !$user->locktime) {
                //锁住
                Db::name('user')->where('uid', $user->uid)->update(['mer_id' => $order->mer_id, 'locktime' => date('Y-m-d H:i:s')]);

                //获取锁客商户的uid
                $mer_data = Db::name('merchant')->where('mer_id', $order->mer_id)->field('uid,mer_id')->find();
                $merchant_user = $userRepository->getOne(['uid' => $mer_data["uid"]]);

                //跨店锁客分发
                $orders = OrderMerchant::getDB()->where('pay_user_id', $order->pay_user_id)->where('status', 1) ->whereNotIn('mer_id', [$order->mer_id])->where('binds',0)->select();
                foreach ($orders as $kd_order) {
                    $pv = Db::name('user_sign_gongxian')->where('mer_id', $kd_order->mer_id)->where('order_id', $kd_order->id)->value('pv');//拿到原来的pv值记录
                    //商户锁客收益：PV的5%==14元X5%=0.7元 （加入到用户佣金，可以从用户佣金中提现，商户显示锁客收益总额）
                    $suo_commission = bcmul($pv, '0.5', 2);
                    if ($suo_commission >= 0.01 && $pv) {
                        $mark = "用户获得商户锁客跨店收益" . $suo_commission . '佣金';
                        $title = "商户跨店佣金";
                        $source = 1;
                        $commission_type = 3;
                        $this->add_bill($title, $suo_commission, $merchant_user->uid, $mark, $commission_type, $kd_order->order_sn, $kd_order->id, $kd_order->mer_id, $source, 1);
                    } else {
                        Db::name('log')->insert(['data' => '订单号：' . $kd_order->order_sn . '付款额度较低或 商家、平台设置的返佣比例较低，商户锁客跨店佣金低于0.01无法入库 特此记录！']);
                    }
                }

                // $mer_fanyongbili = merchantConfig($order->mer_id, 'base_commission');
                // //如果商户返佣比例设置的是0怎查系统设设置的分佣比例
                // if ($mer_fanyongbili == 0) {
                //     $mer_fanyongbili = merchantConfig(0, 'extension_one_rate');
                // }
                // //如果系统设置的是0就不执行！
                // if ($mer_fanyongbili == 0) {
                //     Db::name('log')->insert(['data' => '订单号：' . $order->order_sn . ' 订单因商家、平台没有设置返佣比例无任何奖励特此记录！']);
                //     return '';
                // }
                // $order_sn = $order->order_sn ?? '';
                // $order_id = $order->order_id ?? '';
                // //可分总佣金
                // $divisible_commission = bcmul($order->money, bcdiv($mer_fanyongbili, '100', 2), 2);//让利部分
                // $pv = bcmul($divisible_commission, '0.7', 2);//商家让利部分30%给消费者做养老金，70%做业绩PV

                // //商户锁客收益：PV的5%==14元X5%=0.7元 （加入到用户佣金，可以从用户佣金中提现，商户显示锁客收益总额）
                // $mer_data = Db::name('merchant')->where('mer_id', $order->mer_id)->field('uid,mer_id')->find();
                // $merchant_user = $userRepository->getOne(['uid' => $mer_data["uid"]]);

                // $suo_commission = bcmul($pv, '0.5', 2);
                // if ($suo_commission >= 0.01) {
                //     $mark = "用户获得商户锁客跨店收益" . $suo_commission . '佣金';
                //     $title = "商户跨店佣金";
                //     $source = 1;
                //     $commission_type = 3;
                //     $this->add_bill($title, $suo_commission, $merchant_user->uid, $mark, $commission_type, $order_sn, $order_id, $order->mer_id, $source, 1);
                // } else {
                //     Db::name('log')->insert(['data' => '订单号：' . $order->order_sn . '付款额度较低或 商家、平台设置的返佣比例较低，佣金低于0.01无法入库 特此记录！']);
                // }
            }

            $userOfflineRechargeRepository->paySuccess($order->id, $order->out_trade_no, $user->uid, $order->mer_id, $order->money, $order->give_money, $order->pension, $order->available, $order->pay_user_id);
        } else {
            try {
                Db::transaction(function () use ($order, $user, $unionUser) {
                    $unionData = [
                        'unionid' => $order->pay_user_id,
                        'nickname' => $order->nickname ?: time(),
                        'avatar' => $order->avatar ?: 'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png',
                        'is_lock' => 1,
                        'lock_mer_id' => $order->mer_id,
                        'lock_time' => date('Y-m-d H:i:s'),
                        'balance' => $order->money,
                        'give_money' => $order->give_money,
                        'pension' => $order->pension,
                        'type' => $order->trade_type == 'WX' ? 1 : 2,
                    ];
                    $unionUsersDao = app()->make(UnionUsersDao::class);
                    if (!$unionUser) {
                        $unionUsersDao->create($unionData);
                    } else {
                        $updateData = [
                            'nickname' => $order->nickname ?: time(),
                            'avatar' => $order->avatar ?: 'https://cdn.bjtdba.com/vod/image/2025-01-21/20250121180855764.png',
                            'balance' => Db::raw('balance+' . $order->money),
                            'give_money' => Db::raw('give_money+' . $order->give_money),
                            'pension' => Db::raw('pension+' . $order->pension),
                            'update_time' => date('Y-m-d H:i:s')
                        ];
                        $unionUsersDao->update($unionUser->id, $updateData);
                    }
                });
            } catch (\Throwable $e) {
                Log::info($e->getMessage());
            }
        }
        if ($flag == 0) {
            $this->serviceReturn($order);
        }
    }

    /**
     * 用户授权后绑定用户加金额
     * @author php迷途小书童
     * @created 2021/2/1 10:58
     */
    public function doBindUser($user, $type)
    {
        $unionUsersRepository = app()->make(UnionUsersRepository::class);
        switch ($type) {
            case 1:
                $unionUser = $unionUsersRepository->getWhere(['unionid' => $user->wechat_user_id]);
                break;
            case 2:
                $unionUser = $unionUsersRepository->getWhere(['unionid' => $user->ali_user_id]);
                break;
            default:
                return true;

        }
        $userOfflineRechargeRepository = app()->make(UserOfflineRechargeRepository::class);
        if (!$user->mer_id) {
            $user->mer_id = $unionUser->lock_mer_id;

            $user->save();
        }
        $unionUser->uid = $user->uid;
        $unionUser->save();
        try {
            $userOfflineRechargeRepository->userBindSuccess($unionUser);
        } catch (\Throwable $e) {
            Log::info($e->getMessage());
        }

    }

    /**
     * 用户授权后绑定用户加金额
     * 小程序
     */
    public function doBindUserMp($user, $type)
    {
        $unionUsersRepository = app()->make(UnionUsersRepository::class);
        switch ($type) {
            case 1:
                $unionUser = $unionUsersRepository->getWhere(['unionid' => $user['wechat_user_id']]);
                break;
            case 2:
                $unionUser = $unionUsersRepository->getWhere(['unionid' => $user['ali_user_id']]);
                break;
            default:
                return true;
        }
        $userOfflineRechargeRepository = app()->make(UserOfflineRechargeRepository::class);
        if (!$user['mer_id']) {
            $user['mer_id'] = $unionUser->lock_mer_id ?? $unionUser['lock_mer_id'];
            $userRepository = app()->make(UserRepository::class);
            if ($type == 1) {
                $userRepository->where("wechat_user_id", $user['wechat_user_id'])->save($user);
            }
        }
        $unionUser->uid = $user['uid'];
        $unionUser->save();
        try {
            $userOfflineRechargeRepository->userBindSuccess($unionUser);
        } catch (\Throwable $e) {
            Log::info($e->getMessage());
        }

    }

    /**
     * 给服务商返利
     * @author php迷途小书童
     * @created 2021/2/7 21:37
     */
    public function serviceReturn($order)
    {
        Log::info('服务商返利开始');
        try {
            $params = [
                'order_sn' => $order->out_trade_no,
                'order_id' => $order->id,
                'uid' => $order->uid,
                'unionid' => $order->pay_user_id,
                'mer_id' => $order->mer_id,
                'total_price' => $order->money,
                'extension_one' => $order->available,
                'cart_id' => 0,
            ];
            Log::info(json_encode($params));
            app()->make(StoreOrderRepository::class)->rebate($params, 1);
            Db::name('user_bill')->where('order_sn', $order->out_trade_no)->where('link_id', $order->id)->update(['status' => 1]);
        } catch (\Throwable $e) {
            Log::info($e->getMessage());
        }
    }

    /**
     * 退款回调处理
     * @author php迷途小书童
     * @created 2021/1/30 10:22
     */
    public function doRefundNotify($order_no)
    {
        $order = $this->dao->getWhere(['refund_no' => $order_no]);
        if (!$order)
            return false;
        //修改订单状态
        Db::transaction(function () use ($order) {
            $order->paid = 1;
            $order->status = 2;
            $order->pay_time = Carbon::now();
            return $order->save();
        });
        return true;
    }

    /**
     * 批量入账公证处
     * @author php迷途小书童
     * @created 2021/3/10 16:36
     */
    public function batchGzc($certification, $user, $batchType)
    {
        switch ($batchType) {
            case 'WX':
                $pay_user_id = $user->wechat_user_id;
                break;
            case 'ALI':
                $pay_user_id = $user->ali_user_id;
                break;
            default:
                $pay_user_id = 0;
                break;
        }
        if (!$pay_user_id) return;
        $query = OrderMerchant::getDB()
            ->where('pay_user_id', $pay_user_id)
            ->where('paid', 1)
            ->where('gzc', 0);
        $query->chunk(100, function ($orders) use ($certification) {
            foreach ($orders as $order) {
                $this->doTransactionGzc($certification, $order);
            }
        });
    }

    /**
     * @author php迷途小书童
     * @created 2021/1/31 16:31向公证处入账
     */
    public function doTransactionGzc($certification, $order)
    {
        try {
            $depositInfoList = [];
            $depositInfo = [
                'conName' => $certification['user_name'],//消费者姓名
                'conTel' => $certification['mobile'],//消费者电话
                'conCertType' => 1,//消费者证件类型
                'conCertNo' => $certification['user_card'],//消费者证件号
                'conIsAuth' => 1,//消费者在平台是否已实名
                'amount' => $order->pension,//消费者存入的消费养老金额
                'depositDt' => date('Y-m-d', strtotime($order->pay_time)),//入账时间
            ];
            switch ($order->trade_type) {
                case 'WX':
                    $depositInfo['wechatPaymentAccount'] = $order->pay_user_id;
                    $depositInfo['wechatPaymentFlow'] = $order->weixin_no;
                    $depositInfo['accountType'] = 3;
                    break;
                case 'ALI':
                    $depositInfo['alipayPaymentAccount'] = $order->pay_user_id;
                    $depositInfo['alipayPaymentFlow'] = $order->alipay_no;
                    $depositInfo['accountType'] = 2;
                    break;
            }
            $orderId = $this->getNewOrderId('GZC');
            $datas['transactionSerialNumber'] = $orderId;
            $datas['businessDiff'] = '用户养老金';
            Log::info('发起养老金入账' . $order->out_trade_no);
            array_push($depositInfoList, $depositInfo);
            $response = $this->palceOrderFromServer($datas, $depositInfoList);
            Log::info('养老金入账返回信息' . json_encode($response));
            if ($response['code'] == 0) {
                $order->gzc_platform_no = $orderId;
                $order->gzc_deposit_no = $response['extendData']['depositDetailNo'];
                $order->save();
            }
        } catch (\Throwable $e) {
            Log::info('用户养老金' . $orderId . $e->getMessage());
        }

    }


    /**
     * @param $uid
     * @param $mer_id
     * @author Tang
     * @created 2021/12/10
     */
    public function hxim($uid, $mer_id)
    {
        try {
            $im = new Im();
            $user = Db::name('user')->where('uid', $uid)->find();
            $merchat = Db::name('merchant')->alias('m')->leftJoin('user u', 'm.uid=u.uid')->where('m.mer_id', $mer_id)->field('u.*,m.mer_name')->find();
            if ($user['im'] == 0) {//没有环信账户 创建
                $im->createImUser($user['account'], $user['nickname']);
                $user_account = $user['account'];
            } else {//有环信账户 跳过创建 下一步
                $user_account = $user['account'];
            }
            if ($merchat['im'] == 0) {//没有环信账户 创建
                $im->createImUser($merchat['account'], $merchat['nickname']);
                $merchat_account = $merchat['account'];
            } else {//有环信账户 跳过创建 下一步
                $merchat_account = $merchat['account'];
            }
            $group_id = Db::name("im_group")->where(['uid' => $merchat_account, 'type' => 'p'])->value('groupid');
            //判断是否有群
            if ($group_id) {//有则加入
                $im->createGroupUser($group_id, $user_account, $user['uid']);
            } else {
                $group_id = $im->createGroup($merchat_account, $merchat['mer_name'] . '-商户群', 'p');

                $im->createGroupUser($group_id, $user_account, $user['uid']);

            }
        } catch (\Exception $e) {
            Db::name("log")->insert(array('data' => '环信错误' . $e->getMessage()));//日志记录
        }
    }


    public function dacang_fenyong($order, $pay_status)
    {
        try {
//            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . ' ：：：：大仓订单支付进来了']);
            if ($pay_status == 1) {
                return '';
            }
            $mer_fanyongbili = merchantConfig($order['mer_id'], 'base_commission');
            $top_data = Db::name('user')->where('uid', $order['uid'])->field('spread_uid')->find();
            //如果商户返佣比例设置的是0怎查系统设设置的分佣比例
            if ($mer_fanyongbili == 0) {
                $mer_fanyongbili = merchantConfig(0, 'extension_one_rate');
            }
            //如果系统设置的是0就不执行！
            if ($mer_fanyongbili == 0) {
//                Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . ' 大仓订单因商家、平台没有设置返佣比例无任何奖励特此记录！']);
                return '';
            }
            $order_sn = $order['order_sn'] ?? '';
            $order_id = $order['order_id'] ?? '';
            //可分总佣金
            $divisible_commission = bcmul($order['pay_price'], bcdiv($mer_fanyongbili, '100', 2), 2);
            /**
             * 各自的比例开始
             */
            //用户养老金比例
            $yonghu_bili = '0.5';
            //用户推荐人，消费者的推荐人
            $yonghu_tuijian = '0.15';
            //大仓利润
            $da_cang_lirun = '0.15';
            //商家流水分佣
            $mer_luishui_fenyong = '0.025';
            /**
             * 各自的比例结束
             */

            //用户可拿的养老金
            $user_yanglaojin = bcmul($divisible_commission, $yonghu_bili, 2);
            if ($user_yanglaojin > 0.01) {
                $mark = "消费获得养老金" . $user_yanglaojin;
                $title = "养老金";
                $source = 1;
                $commission_type = 5;
                $this->add_bill($title, $user_yanglaojin, $order["uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
            } else {
                Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，养老金低于0.01无法入库 特此记录！']);
            }
            //用户推荐人佣金
            $tuijian_yongjin = bcmul($divisible_commission, $yonghu_tuijian, 2);
            if ($tuijian_yongjin > 0.01) {
                $mark = "用户在大仓消费获得" . $tuijian_yongjin . '佣金';
                $title = "佣金";
                $source = 1;
                $commission_type = 3;
                $this->add_bill($title, $tuijian_yongjin, $top_data["spread_uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
            } else {
                Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，佣金低于0.01无法入库 特此记录！']);
            }
            //大仓利润
            $lirun_da_cang = bcmul($divisible_commission, $da_cang_lirun, 2);
            if ($lirun_da_cang > 0.01) {
                Db::name('store_order')->where('order_id', $order_id)->update(['da_cang_profit' => $lirun_da_cang]);
            } else {
                Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，大仓利润低于0.01无法入库 特此记录！']);
            }
            //推荐商家流水返佣
            $mer_tuijian_yongjin = bcmul($divisible_commission, $mer_luishui_fenyong, 2);
            if ($mer_tuijian_yongjin > 0.01) {
                Db::name('store_order')->where('order_id', $order_id)->update(['recommended_merchants' => $mer_tuijian_yongjin]);
            } else {
                Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，推荐商家流水返佣低于0.01无法入库 特此记录！']);
            }
        } catch (\Exception $exception) {
            Db::name('log')->insert(['data' => '大仓订单处理失败：' . $exception->getFile() . '：' . $exception->getLine() . '【' . $exception->getMessage() . '】']);
        }
    }

    //按商家让利比例匹配商家获得贡献值和京豆比例
    public function getMerchantContribution($mer_fanyongbili)
    {
        $jd = 0;
        $gonxian = 0;
        $cursor = Db::table('rrx_merchant_contribution')->cursor();
        foreach ($cursor as $online) {
            if($online['start'] <= $mer_fanyongbili && $online['end'] >= $mer_fanyongbili){
                $jd = $online['jd'] ?? 0;
                $gonxian = $online['value'] ?? 0;
            }
        }
        return ['jd'=>$jd,'gonxian'=>$gonxian];
    }

    //推荐人按推荐人等级匹配范围
    public function getUserGroupRate($user_group)
    {
        $rete = '0.03';
        $user_group_rate = Db::name("system_config_value")->where(["config_key"=>"user_group_rate"])->value("value");
        $user_group_rate = json_decode($user_group_rate, true);
        foreach ($user_group_rate as $online) {
            if($online['user_groub'] == $user_group){
                $rete = $online['rate'] ? bcdiv($online['rate'], '100', 2) : '0.03';
            }
        }
        return $rete;
    }

    //商户二维码收款返佣
    public function feidacang_fenyong($user, $order, $pay_status)
    {
        $userRepository = app()->make(UserRepository::class);
        if ($pay_status == 1) {
            return '';
        }
        $top_data = Db::name('user')->where('uid', $order['uid'])->field('spread_uid,mer_id')->find();
        $mer_fanyongbili = merchantConfig($order['mer_id'], 'base_commission');
        //如果商户返佣比例设置的是0怎查系统设设置的分佣比例
        if ($mer_fanyongbili == 0) {
            Db::name('system_config_value')->insert([
                'config_key'  => 'base_commission',
                'value'       => (int)5,
                'mer_id'      => $order['mer_id'],
            ]);
            $mer_fanyongbili = 5;
            // $mer_fanyongbili = merchantConfig(0, 'extension_one_rate');
        }
        if($order['mer_id'] == 3425) $mer_fanyongbili = 0;
        if($order['mer_id'] == 3447) $mer_fanyongbili = 0;
        //如果系统设置的是0就不执行！
        if ($mer_fanyongbili == 0) {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . ' 订单因商家、平台没有设置返佣比例无任何奖励特此记录！']);
            return '';
        }
        $order_sn = $order['order_sn'] ?? '';
        $order_id = $order['order_id'] ?? '';
        $order_type = 10;
        //可分总佣金
        $divisible_commission = bcmul($order['pay_price'], bcdiv($mer_fanyongbili, '100', 2), 2);//让利部分
        $pv = bcmul($divisible_commission, '0.7', 2);//商家让利部分30%给消费者做养老金，70%做业绩PV

        /**
         * 各自的比例开始
         */
        //用户养老金比例30%
        $yonghu_bili = '0.3';
        //用户红包比例
        $yonghu_hongbao = '0.45';
        //用户推荐人养老金比例
        $yonghu_bili_tuijian = '0.05';
        //用户推荐人，消费者的推荐人佣金
        $yonghu_tuijian = $this->getUserGroupRate($user['user_group']);
        //用户推荐人，消费者的推荐人复购金
        $yonghu_fugou = '0.1';
        /**
         * 各自的比例结束
         */

        // 用户---------------------------------------------------------------------------------------------------------------

        //用户可拿的养老金
        $user_yanglaojin = bcmul($divisible_commission, $yonghu_bili, 2);
        if ($user_yanglaojin >= 0.01) {
            $mark = "消费获得养老金" . $user_yanglaojin;
            $title = "养老金";
            $source = 1;
            $commission_type = 5;
            $this->add_bill($title, $user_yanglaojin, $order["uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，养老金低于0.01无法入库 特此记录！']);
        }

        // 用户可以拿到的红包 红包：如果是1.0的老用户 pv的45%放到红包里面。14*45%=6.3元。直至金额满足1.0平台当前用户身份为止就不在反红包了
        $old_vip_limit = Db::name('user_sign_hongbao')->where('uid',$order["uid"])->sum('number') ?? 0;
        // 吴总 2026-02-24 说 线下扫码不再发放红包
        // if($user['is_old']==1){
        //     //添加红包
        //     $hongbao=bcmul($pv, $yonghu_hongbao, 2);
        //     $hongbao_data = [
        //         "uid"           =>$order["uid"],
        //         "number"  =>    $hongbao,
        //         "addtime"       =>time(),
        //         "status"        =>1,
        //         "order_type"    =>$order_type,
        //         "order_id"      =>$order_id,
        //         "mark"          =>"扫码消费获得赠送红包",
        //         "desc"          =>'',
        //         "surplus"       =>$hongbao,
        //         "type"          =>1,
        //         'settlement_time' => date('Y-m-d H:i:s')
        //     ];
        //     Db::name("user_sign_hongbao")->insert($hongbao_data);//添加记录
        //     $user_hongbao = Db::name('user')->where('uid', $order["uid"])->value('hongbao');
        //     $user_hongbao = bcadd($user_hongbao, (float)$hongbao,2);
        //     Db::name('user')->where('uid', $order["uid"])->update(['hongbao'=>$user_hongbao]);
        // }

        ///用户可以拿到PV等值的积分和贡献值
        if ($pv >= 0.01) {
            //积分
            $ins_data['uid'] = $order["uid"];
            $ins_data['continuity_day'] = 0;
            $ins_data['reward_socre'] = $pv;
            $ins_data['signin_time'] = 0;
            $ins_data['addtime'] = time();
            $ins_data['status'] = 1;
            $ins_data['mark'] = "扫码消费获得赠送积分";
            $ins_data['source_type'] = 3;
            $ins_data['settlement_time'] = 0;// 结算时间 真正到了结算时间会结算
            $ins_data['order_id'] = $order_id;
            $ins_data['pm'] = 1;
            $ins_data['order_type'] = $order_type;
            $ins_data['settlement_time'] = date('Y-m-d H:i:s');
            Db::name('user_sign_score')->insertGetId($ins_data);
            $user_score = Db::name('user')->where('uid', $order["uid"])->value('score');
            $user_score = bcadd($user_score, (float)$pv,2);
            Db::name('user')->where('uid', $order["uid"])->update(['score'=>$user_score]);
            //贡献值
            $gongxian_data = [
                "uid"           =>$order["uid"],
                "number"  =>    $pv,
                "addtime"       =>time(),
                "status"        =>1,
                "order_type"    =>$order_type,
                "order_id"      =>$order_id,
                "mark"          =>"扫码消费获得赠送贡献值",
                "desc"          =>'',
                "surplus"       =>$pv,
                "type"          =>1,
                'settlement_time' => date('Y-m-d H:i:s')
            ];
            Db::name("user_sign_gongxian")->insert($gongxian_data);//添加记录
            $user_contribute = Db::name('user')->where('uid', $order["uid"])->value('contribute');
            $user_contribute = bcadd($user_contribute, (float)$pv,2);
            Db::name('user')->where('uid', $order["uid"])->update(['contribute'=>$user_contribute]);
            /** @var StoreOrderRepository $StoreOrderRepository */
            $StoreOrderRepository = app()->make(StoreOrderRepository::class);
            // 用户获得pv值
            $StoreOrderRepository->con_log_pv($order["uid"],$pv,$order_id, $order_type,'扫码消费获得赠送PV值',1);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，积分和贡献值低于0.01无法入库 特此记录！']);
        }

        // 用户推荐人---------------------------------------------------------------------------------------------------------------

        //用户推荐人可拿的养老金
        $user_yanglaojin = bcmul($pv, $yonghu_bili_tuijian, 2);
        if ($user_yanglaojin >= 0.01 && !empty($top_data["spread_uid"])) {
            $mark = "推荐人扫码消费获得养老金" . $user_yanglaojin;
            $title = "养老金";
            $source = 1;
            $commission_type = 5;
            $this->add_bill($title, $user_yanglaojin, $top_data["spread_uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，养老金低于0.01无法入库 特此记录！']);
        }

        //用户推荐人佣金
        $tuijian_yongjin = bcmul($pv, $yonghu_tuijian, 2);
        $tuijian_yongjin_90 = bcmul($tuijian_yongjin, '0.9', 2);
        if ($tuijian_yongjin_90 >= 0.01 && !empty($top_data["spread_uid"])) {
            $mark = "推荐人扫码消费获得" . $tuijian_yongjin_90 . '佣金';
            $title = "佣金";
            $source = 1;
            $commission_type = 3;
            $this->add_bill($title, $tuijian_yongjin_90, $top_data["spread_uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，佣金低于0.01无法入库 特此记录！']);
        }
        // 推荐人获得贡献值
        if($pv >= 0.01 && !empty($top_data["spread_uid"])){
            $gongxian_data = [
                "uid"           =>$top_data["spread_uid"],
                "number"  =>    $pv,
                "addtime"       =>time(),
                "status"        =>1,
                "order_type"    =>$order_type,
                "order_id"      =>$order_id,
                "mark"          =>"推广扫码消费获得赠送贡献值",
                "desc"          =>'',
                "surplus"       =>$pv,
                "type"          =>1,
                'settlement_time' => date('Y-m-d H:i:s')
            ];
            Db::name("user_sign_gongxian")->insert($gongxian_data);//添加记录
            Db::name('user')->where('uid', $top_data["spread_uid"])->inc('contribute',$pv)->update();
        }

        //推荐人获得积分
        $jifen = bcmul($pv, $yonghu_tuijian, 2);
        if($jifen >= 0.01 && !empty($top_data["spread_uid"])){
            $spread_data['uid'] = $top_data["spread_uid"];
            $spread_data['continuity_day'] = 0;
            $spread_data['reward_socre'] = $jifen;
            $spread_data['signin_time'] = 0;
            $spread_data['addtime'] = time();
            $spread_data['status'] = 1;
            $spread_data['mark'] = "推广扫码消费获得赠送积分";
            $spread_data['source_type'] = 3;
            $spread_data['order_id'] = $order_id;
            $spread_data['pm'] = 1;
            $spread_data['order_type'] = $order_type;
            $spread_data['settlement_time'] = date('Y-m-d H:i:s');
            Db::name('user_sign_score')->insertGetId($spread_data);
            Db::name('user')->where('uid', $top_data["spread_uid"])->inc('score',$jifen)->update();
        }
        //用户推荐人获得复购金佣金百分之10
        $tuijian_fugou = bcmul($tuijian_yongjin, $yonghu_fugou, 2);
        if ($tuijian_fugou >= 0.01 && !empty($top_data["spread_uid"])) {
            $bill = [
                'uid'=>$top_data["spread_uid"],
                'number'=>$tuijian_fugou,//数量
                'status'=>1,//复购金状态1-有效 0-失效 -1待确认
                'mark'=>"推荐人扫码消费赠送" . $tuijian_fugou . '复购金',//备注
                'order_id'=>$order_id,//订单id
                'surplus'=>0,//剩余
                'order_type'=>$order_type,//关联订单ID
                'type'=>1,//复购金类型 :1赠送，2消耗
                'settlement_time'=>date('Y-m-d H:i:s'),//添加时间,
                'addtime'=>time(),
            ];
            Db::name('user_sign_fugou')->insert($bill);
            $user_fugou = Db::name('user')->where('uid', $top_data["spread_uid"])->value('fugou');
            $user_fugou = bcadd($user_fugou, (float)$tuijian_fugou,2);
            Db::name('user')->where('uid', $top_data["spread_uid"])->update(['fugou'=>$user_fugou]);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的复购金比例较低，复购金低于0.01无法入库 特此记录！']);
        }
    }





    //商户二维码收款返佣-补发推荐人
    public function feidacang_fenyong_bufa($user, $order, $pay_status)
    {
        $userRepository = app()->make(UserRepository::class);
        if ($pay_status == 1) {
            return '';
        }
        $top_data = Db::name('user')->where('uid', $order['uid'])->field('spread_uid,mer_id')->find();
        $mer_fanyongbili = merchantConfig($order['mer_id'], 'base_commission');
        //如果商户返佣比例设置的是0怎查系统设设置的分佣比例
        if ($mer_fanyongbili == 0) {
            $mer_fanyongbili = merchantConfig(0, 'extension_one_rate');
        }
        //如果系统设置的是0就不执行！
        if ($mer_fanyongbili == 0) {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . ' 订单因商家、平台没有设置返佣比例无任何奖励特此记录！']);
            return '';
        }
        $order_sn = $order['order_sn'] ?? '';
        $order_id = $order['order_id'] ?? '';
        //可分总佣金
        $divisible_commission = bcmul($order['pay_price'], bcdiv($mer_fanyongbili, '100', 2), 2);//让利部分
        $pv = bcmul($divisible_commission, '0.7', 2);//商家让利部分30%给消费者做养老金，70%做业绩PV

        /**
         * 各自的比例开始
         */
        //用户养老金比例30%
        $yonghu_bili = '0.3';
        //用户红包比例
        $yonghu_hongbao = '0.45';
        //用户推荐人养老金比例
        $yonghu_bili_tuijian = '0.05';
        //用户推荐人，消费者的推荐人佣金
        $yonghu_tuijian = $this->getUserGroupRate($user['user_group']);
        //用户推荐人，消费者的推荐人复购金
        $yonghu_fugou = '0.1';
        /**
         * 各自的比例结束
         */

        // 用户推荐人---------------------------------------------------------------------------------------------------------------

        //用户推荐人可拿的养老金
        $user_yanglaojin = bcmul($pv, $yonghu_bili_tuijian, 2);
        if ($user_yanglaojin >= 0.01) {
            $mark = "推荐人扫码消费获得养老金" . $user_yanglaojin;
            $title = "养老金";
            $source = 1;
            $commission_type = 5;
            $this->add_bill($title, $user_yanglaojin, $top_data["spread_uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，养老金低于0.01无法入库 特此记录！']);
        }

        //用户推荐人佣金
        $tuijian_yongjin = bcmul($pv, $yonghu_tuijian, 2);
        $tuijian_yongjin_90 = bcmul($tuijian_yongjin, '0.9', 2);
        if ($tuijian_yongjin_90 >= 0.01) {
            $mark = "推荐人扫码消费获得" . $tuijian_yongjin_90 . '佣金';
            $title = "佣金";
            $source = 1;
            $commission_type = 3;
            $this->add_bill($title, $tuijian_yongjin_90, $top_data["spread_uid"], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，佣金低于0.01无法入库 特此记录！']);
        }

        //用户推荐人获得复购金佣金百分之10
        $tuijian_fugou = bcmul($tuijian_yongjin, $yonghu_fugou, 2);
        if ($tuijian_fugou >= 0.01) {
            $bill = [
                'uid'=>$top_data["spread_uid"],
                'number'=>$tuijian_fugou,//数量
                'status'=>1,//复购金状态1-有效 0-失效 -1待确认
                'mark'=>"推荐人扫码消费赠送" . $tuijian_fugou . '复购金',//备注
                'order_id'=>$order_id,//订单id
                'surplus'=>0,//剩余
                'order_type'=>0,//关联订单ID
                'type'=>1,//复购金类型 :1赠送，2消耗
                'settlement_time'=>date('Y-m-d H:i:s'),//添加时间,
                'addtime'=>time(),
            ];
            Db::name('user_sign_fugou')->insert($bill);
            $user_fugou = Db::name('user')->where('uid', $top_data["spread_uid"])->value('fugou');
            $user_fugou = bcadd($user_fugou, (float)$tuijian_fugou,2);
            Db::name('user')->where('uid', $top_data["spread_uid"])->update(['fugou'=>$user_fugou]);
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的复购金比例较低，复购金低于0.01无法入库 特此记录！']);
        }
    }










    //商户二维码收款商家返佣
    public function feidacang_fenyong_mer($user, $order, $pay_status)
    {
        $userRepository = app()->make(UserRepository::class);
        if ($pay_status == 1) {
            return '';
        }
        $top_data = Db::name('user')->where('uid', $order['uid'])->field('spread_uid,mer_id')->find();
        $mer_fanyongbili = merchantConfig($order['mer_id'], 'base_commission');
        //如果商户返佣比例设置的是0怎查系统设设置的分佣比例
        if ($mer_fanyongbili == 0) {
            $mer_fanyongbili = merchantConfig(0, 'extension_one_rate');
        }
        //如果系统设置的是0就不执行！
        if ($mer_fanyongbili == 0) {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . ' 订单因商家、平台没有设置返佣比例无任何奖励特此记录！']);
            return '';
        }
        $order_sn = $order['order_sn'] ?? '';
        $order_id = $order['order_id'] ?? '';
        //可分总佣金
        $divisible_commission = bcmul($order['pay_price'], bcdiv($mer_fanyongbili, '100', 2), 2);//让利部分
        $pv = bcmul($divisible_commission, '0.7', 2);//商家让利部分30%给消费者做养老金，70%做业绩PV
        //更新值
        Db::name("order_merchant")->where('id', $order_id)->where('out_trade_no', $order_sn)->update(['available'=>$divisible_commission]);

        /**
         * 各自的比例开始
         */
        $getMerchantContribution = $this->getMerchantContribution($mer_fanyongbili);
        //商家贡献值比例
        $mer_gonxian = $getMerchantContribution['gonxian'];
        //  商家京豆比例
        $mer_jd = $getMerchantContribution['jd'];
        //跨店分佣
        $kd = 0.05;
        $order_type = 10;
        /**
         * 各自的比例结束
         */

        $gongxian = Db::name('user_sign_gongxian')->where('order_id', $order_id)->find();
        if(!$gongxian){
            ///用户可以拿到PV等值贡献值
            if ($pv >= 0.01) {
                //贡献值
                $gongxian_data = [
                    "uid"           =>$order["uid"]??0,
                    "number"  =>    $pv,
                    "addtime"       =>time(),
                    "status"        =>1,
                    "order_type"    =>$order_type,
                    "order_id"      =>$order_id,
                    "mark"          =>"扫码消费获得赠送贡献值",
                    "desc"          =>'',
                    "surplus"       =>$pv,
                    "type"          =>1,
                    'settlement_time' => date('Y-m-d H:i:s')
                ];
                Db::name("user_sign_gongxian")->insert($gongxian_data);//添加记录
            } else {
                Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，积分和贡献值低于0.01无法入库 特此记录！']);
            }
        }





        // 商户---------------------------------------------------------------------------------------------------------------

        $mer_data = Db::name('merchant')->where('mer_id', $order['mer_id'])->field('uid,mer_id')->find();
        $userRepository = app()->make(UserRepository::class);
        $merchant_user = $userRepository->getOne(['uid' => $mer_data["uid"]]);

        //商户得到的(京豆和贡献值奖励的倍，后台设置)
        // $gongxian = bcmul($divisible_commission, $mer_gonxian, 2);
        // if ($gongxian >= 0.01) {
            // $gongxian_data = [
            //     "uid"           =>$mer_data["uid"],
            //     "mer_id"        =>$order["mer_id"],
            //     "pv"            =>$pv,
            //     "number"  =>    $gongxian,
            //     "addtime"       =>time(),
            //     "status"        =>1,
            //     "order_type"    =>2,
            //     "order_id"      =>$order_id,
            //     "mark"          =>"用户消费商家获得赠送贡献值",
            //     "desc"          =>'',
            //     "surplus"       =>$gongxian,
            //     "type"          =>1
            // ];
            // Db::name("user_sign_gongxian")->insert($gongxian_data);//添加记录
        //     $merchant_user->contribute = bcadd($merchant_user->contribute, (float)$gongxian,2);
        //     $merchant_user->save();
        // // } else {
        //     Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，贡献值低于0.01无法入库 特此记录！']);
        // }

        //商户得到的(京豆和贡献值奖励的倍，后台设置)
        $jd = bcmul($divisible_commission, $mer_jd, 2);
        if ($jd >= 0.01) {  
            $jd_data = [
                "uid"           =>$mer_data["uid"],
                "mer_id"        =>$order["mer_id"],
                "number"  =>    $jd,
                "addtime"       =>time(),
                "status"        =>1,
                "order_type"    =>$order_type,
                "order_id"      =>$order_id,
                "mark"          =>"用户消费商家获得赠送京豆",
                "desc"          =>'',
                "surplus"       =>$jd,
                "type"          =>1
            ];
            $merchant_user->jingdou = bcadd($merchant_user->jingdou, (float)$jd,2);
            $merchant_user->save();
            Db::name("user_sign_jingdou")->insert($jd_data);//添加记录
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，贡献值低于0.01无法入库 特此记录！']);
        }

        Db::name('log')->insert(['data' => 'PV:' . $pv .' mer_jd:'. $mer_jd.' mer_gonxian:'.$mer_gonxian.' jingdou:'.$merchant_user->jingdou.' contribute:'.$merchant_user->contribute]);

        //跨店
        $kd_yongjin = bcmul($pv, $kd, 2);
        if ($kd_yongjin >= 0.01) {
            $mer_uid = Db::name("merchant")->where("mer_id",$top_data["mer_id"])->find();
            if ($mer_uid){
                $mark = "用户消费获得" . $kd_yongjin . '佣金';
                $title = "商户跨店佣金";
                $source = 1;
                $commission_type = 7;
                $this->add_bill($title, $kd_yongjin, $mer_uid['uid'], $mark, $commission_type, $order_sn, $order_id, $order["mer_id"], $source, 1);
            }
        } else {
            Db::name('log')->insert(['data' => '订单号：' . $order['order_sn'] . '付款额度较低或 商家、平台设置的返佣比例较低，佣金低于0.01无法入库 特此记录！']);
        }
    }












    /**
     * 佣金加入账单
     * @param $title
     * @param $number
     * @param $uid
     * @param $mark
     * @param $commission_type
     * @param $order_sn
     */
    public function add_bill($title, $number, $uid, $mark, $commission_type, $order_sn, $order_id = 0, $mer_id = 0, $source = 0, $status = 1, $type_shop = 10)
    {
//        $old_number=Db::name("user")->where("uid",$uid)->value("brokerage_price");
        if ($uid == 0 || $number == 0) {
            return;
        }
        Log::info("user_bill_log");
        if ($commission_type != 5) {
            $promoter_rate_technology = systemConfig('promoter_rate_technology');
            if (floatval($promoter_rate_technology)) {
                // $number = $number - ($number * $promoter_rate_technology / 100);
                // var_dump(=$number-$number*$promoter_rate_technology)
                // $mark .= ",扣除技术服务费" . $promoter_rate_technology . "%";
            }
        }


//        $number=round($number,2);
        $number = sprintf('%.2f', $number);

        $data = [
            'link_id' => $order_id,
            "uid" => $uid,
            "pm" => 1,
            "title" => $title,
            "category" => "now_money",
            "type" => "commission",
            "number" => $number,
            "balance" => 0,
            "mark" => $mark,
//            "create_time"=>date("Y-m-d H:i:s"),
            "status" => $status,
            "commission_type" => $commission_type,
            "order_sn" => $order_sn,
            "mer_id" => $mer_id,
            "source" => $source,
            "type_shop" => $type_shop
        ];
        if($status == 1) $data['take_time'] = time();
        Db::name("user_bill")->insert($data);

        if ($type_shop == 10) {
            if ($commission_type == 5) {
                $annuity_once = Db::name("user")->where("uid", $uid)->value('annuity_once');
                if ($annuity_once == 0 && $status == 1) {
                    $spreadUid = Db::name('user')->where('uid', $uid)->value('spread_uid');
                    // $userRepository = app()->make(UserRepository::class);
                    // $userRepository->sign_add($spreadUid, systemConfig('ylj_first_score'), 1, '好友首次获得已结算养老金奖励积分', '', '', '');
                    Db::name("user")->where("uid", $uid)->update(['annuity_once' => 1]);

//                    Db::name('user')->where('uid',$spreadUid)->inc('score', systemConfig('ylj_first_score'))->update();
//                    $ins_data['uid'] = $spreadUid;
//                    $ins_data['reward_socre'] = systemConfig('ylj_first_score');
//                    $ins_data['addtime'] = time();
//                    $ins_data['status'] = 1;
//                    $ins_data['mark'] = '好友首次获得已结算养老金奖励积分';
//                    Db::name('user_sign_score')->insert($ins_data);
                }
                Db::name("user")->where("uid", $uid)->inc('annuity', $number)->update();
                Db::name("user")->where("uid", $uid)->inc('annuity_num', 1)->update();
            } else {
                Db::name("user")->where("uid", $uid)->inc('brokerage_price', $number)->update();

            }
        }

    }

    public function offLineOrder($id){
        $check = Db::name("order_merchant")
            -> alias("om")
            -> join("merchant m","om.mer_id = m.mer_id")
            -> field("om.*,m.street_id,m.area_id,m.city_id")
            -> where("id",$id)
            -> find();
        if (!$check) return ['code'=>false,'message' => "订单不存在"];
        if($check['uid'] == 0) return ['code' => true];
        try {
            //可分总佣金
            $config = systemConfig(["yanglaojin_admin","extension_one_rate"]);
            $uid = $check['uid'];
            $order_sn = $check['out_trade_no'];
            $mer_id = $check['mer_id'];
            $orderAddress=[];
            if($mer_id==496){
                app()->make(StoreOrderRepository::class) -> splitCommission_yhc(1,$check['pension'],$uid,$order_sn,$id,$mer_id,1);
            }else{
                app()->make(StoreOrderRepository::class) -> splitCommission(1,$check['mer_fanyong'],$config,$uid,$orderAddress,$order_sn,$id,$mer_id,1);
            }
        }catch (\Exception $e) {

        }
    }
}
