<?php
/**
 * @package merchant
 * @Author: Qinii
 * @Date: 2020/5/28
 */

namespace app\controller\api\store\merchant;

use app\common\model\user\User;
use think\facade\Db;
use think\Request;

class Taskorderguquan
{

    public function assignment()
    {

        /**
         * 业绩25000分配
         * 补贴下面人员
         * 13331043787张吉良55
         *
         * 其余部分做分红
         */
        $data = [
            '13331043787' => 55
        ];

        $result = Db::name("user")
            ->whereIn("account", array_keys($data))
            ->where('is_del', 0)
            ->field('uid, brokerage_price, account, nickname')
            ->select();
        $res = [];
        foreach ($result as $v) {
            $yj_90 = $data[$v['account']] * 0.9;
            $fg_10 = $data[$v['account']] * 0.1;
            Db::name("user")->where("uid", $v['uid'])->inc("brokerage_price", $yj_90)->save();
            Db::name("user")->where("uid", $v['uid'])->inc("total_amount_old", $yj_90)->save();
            Db::name("user")->where("uid", $v['uid'])->inc("amount_old", $yj_90)->save();
            Db::name("user")->where("uid", $v['uid'])->inc("fugou", $fg_10)->save();

            $this->bill_user_log111111($v['uid'], "佣金补贴", $yj_90, "佣金补贴", 8);//股权分佣明细2.0系统
            $this->fugou_user_log($v['uid'], $fg_10, 16, 1, 1);//复购金明细入账
            $res[] = [
                'uid' => $v['uid'],
                'account' => $v['account'],
                'brokerage_price_pre' => $v['brokerage_price'],
                'brokerage_price' => $data[$v['account']],
                'nickname' => $v['nickname']
            ];
        }
        return json($res);

        try {
            // 1. 获取所有用户数据（按level_id正序排序保证父级在前）
            $users = Db::name('user')
                ->where('is_del', '=', 0)
                ->where('status', '=', 1)
                ->where('user_group', '>=', 2)
                ->order('level_id', 'asc')
                ->field('uid,account,nickname,level_id,is_del,status,user_group')
                ->select()
                ->toArray();

            // 2. 构建以UID为键的映射表
            $userMap = [];
            foreach ($users as $user) {
                $user['children'] = []; // 初始化子节点
                $userMap[$user['uid']] = [
                    '用户ID' => $user['uid'],
                    '用户账号' => $user['account'],
                    '用户昵称' => $user['nickname'],
                    '用户身份' => $user['user_group'],
                    '上级用户ID' => $user['level_id'],
                    '直属下级用户人数' => 0,
                    '直属下级用户列表' => $user['children'],
                ];
            }

            // 3. 递归构建树形结构
            $tree = [];
            foreach ($userMap as $uid => &$user) {
                $parentId = $user['上级用户ID'];

                if ($parentId == 0) {
                    // 顶级节点直接加入树
                    $tree[] = &$user;
                } elseif (isset($userMap[$parentId])) {
                    // 非顶级节点加入父节点的children
                    $userMap[$parentId]['直属下级用户列表'][] = &$user;
                    $userMap[$parentId]['直属下级用户人数']++;
                }
            }
            unset($user); // 销毁引用

            return json($tree);
        } catch (\Exception $e) {
            // 记录错误日志
            return json(['code' => 0, 'msg' => '树结构生成失败']);
        }


        $result = [
            'oldOrderExistGongXian' => [],
            'orderExistGongXian' => [],
            'oldOrderExistPv' => [],
            'orderExistPv' => [],
            'gongXianDataOldList' => [],
            'gongXianDataList' => [],
            'pvDataOldList' => [],
            'pvDataList' => [],
            'contributeNot' => [],
            'pvNot' => [],
            'userUpdateSummary' => ['success' => 0, 'failed' => 0, 'skipped' => 0], // 优化: 汇总用户更新结果
            'insertGongXianSummary' => ['success' => 0, 'failed' => 0], // 优化: 汇总贡献插入结果
            'insertPvSummary' => ['success' => 0, 'failed' => 0],         // 优化: 汇总PV插入结果
            'errors' => [],               // 优化: 统一记录错误信息
        ];

        // --- 数据库查询部分 (保持不变，已优化) ---
        // 1. 查询用户
        $userList = Db::name("user")
            ->where('is_del', 0)
            //            ->whereIn('uid', [277, 1593])
            ->column('uid, spread_uid, contribute, per_contribute, pv', 'uid');
        // $userIds = array_keys($userList);

        $oldUserList = Db::name("old_user_jbp")
            ->column('id, amount');

        // 2. 查询老订单
        $userOfGoodsListRaw = Db::name("old_user_of_goods")
            ->where('status', 1)
            // 优化: 如果用户量大，可以考虑只查相关用户的订单
            // ->whereIn('user_id', $userIds)
            ->field('user_id, money, order_id, create_time')
            ->select()
            ->toArray();

        // 3. 查询新订单
        $storeOrderListRaw = Db::name("store_order")
            ->whereIn('status', [0, 1, 2, 3])
            // 优化: 如果用户量大，可以考虑只查相关用户的订单
            // ->whereIn('uid', $userIds)
            ->field('uid, pay_price, mer_id, status, order_id, create_time')
            ->select()
            ->toArray();

        // 4. 查询已存在的贡献值记录
        $gongXianListRaw = Db::name("user_sign_gongxian")
            ->where('status', '<>', -1)
            // 优化: 如果记录非常多，可以分批查询或只查相关用户的
            // ->whereIn('uid', array_merge($userIds, array_column($userList, 'spread_uid'))) // 查询购买者和潜在推广者
            ->field('uid, order_id, number, status, type')
            ->select()
            ->toArray();

        // 5. 查询已存在的PV记录
        $pvListRaw = Db::name("user_pv_log")
            ->where('status', '<>', -1)
            // 优化: 同上
            // ->whereIn('uid', $userIds)
            ->field('uid, order_id, pv, status')
            ->select()
            ->toArray();

        // --- 数据预处理部分
        $existingGongXian = [];
        $existingGongXianByUid = [];
        foreach ($gongXianListRaw as $gx) {
            $existingGongXian[$gx['uid'] . '_' . $gx['order_id']] = ['number' => $gx['number'], 'status' => $gx['status'], 'type' => $gx['type']];
            // TODO 目前老订单id 1-900 新订单ID 4868 - 6255 线下扫码订单 6870 - 8733
            if ((1 <= $gx['order_id'] && $gx['order_id'] <= 900) || (4868 <= $gx['order_id'] && $gx['order_id'] <= 6869)) {
                $existingGongXianByUid[$gx['uid']][] = $gx['order_id'];
            }
        }
        unset($gongXianListRaw);

        $existingPv = [];
        $existingPvByUid = [];
        foreach ($pvListRaw as $pv) {
            $existingPv[$pv['uid'] . '_' . $pv['order_id']] = ['pv' => $pv['pv'], 'status' => $pv['status']];
            // TODO 目前老订单id 1-900 新订单ID 4868 - 6255 线下扫码订单 6870 - 8733
            if ((1 <= $pv['order_id'] && $pv['order_id'] <= 900) || (4868 <= $pv['order_id'] && $pv['order_id'] <= 6869)) {
                $existingPvByUid[$pv['uid']][] = $pv['order_id'];
            }
        }
        unset($pvListRaw);

        $userOfGoodsByUid = [];
        foreach ($userOfGoodsListRaw as $oldOrder) $userOfGoodsByUid[$oldOrder['user_id']][] = $oldOrder;
        unset($userOfGoodsListRaw);

        $storeOrdersByUid = [];
        foreach ($storeOrderListRaw as $order) $storeOrdersByUid[$order['uid']][] = $order;
        unset($storeOrderListRaw);

        // *** 主逻辑处理与数据收集 ***
        $gongXianDataToInsert = []; // 优化: 合并新旧贡献插入列表
        $pvDataToInsert = [];       // 优化: 合并新旧PV插入列表
        $userUpdateData = [];       // 优化: 收集所有需要更新的用户数据 [uid => ['contribute'=>float, 'pv'=>float, 'per_contribute'=>float]]

        // 初始化所有用户的待更新数据
        foreach ($userList as $uid => $user) {
            // 预先设置初始值，确保即使没有订单的用户也能被包含在后续可能的更新逻辑中（如果需要）
            // 如果用户没有任何订单，他们的 contribute 和 pv 应该保持数据库原始值或根据业务逻辑设为0
            // 这里我们先假设如果没有订单，他们的计算值就是0
            $userUpdateData[$uid] = [
                'uid' => $uid,
                'contribute' => 0.0,
                'pv' => 0.0,
                'per_contribute' => 0.0,
            ];
            // 初始化推广者的 per_contribute 累加器
            if (!empty($user['spread_uid'])) {
                $spreadUid = $user['spread_uid'];
                if (!isset($userUpdateData[$spreadUid])) {
                    if (isset($userList[$spreadUid])) {
                        if (!isset($userUpdateData[$spreadUid]['per_contribute'])) {
                            $userUpdateData[$spreadUid]['per_contribute'] = 0.0; // 初始化推广者的累加
                        }
                    } else {
                        // 记录或处理推广者不在当前用户列表的情况
                        $result['errors'][] = "执行{$uid}时，没找到 推荐人 {$spreadUid}";
                        // 可以选择跳过给这个推广者增加 per_contribute
                    }

                } else if (!isset($userUpdateData[$spreadUid]['per_contribute'])) {
                    $userUpdateData[$spreadUid]['per_contribute'] = 0.0; // 初始化推广者的累加
                }
            }
        }

        // 遍历用户列表进行计算和数据收集
        foreach ($userList as $uid => $user) {
            $spreadUid = $user['spread_uid'];
            $existingGongXianByUid[$uid] = $existingGongXianByUid[$uid] ?? [];
            $existingPvByUid[$uid] = $existingPvByUid[$uid] ?? [];
            if (isset($userOfGoodsByUid[$uid])) {
                foreach ($userOfGoodsByUid[$uid] as $oldOrder) {
                    switch ($oldOrder['money']) {
                        case 1180:
                            $totalPv = 700.0;
                            break;
                        case 11800:
                            $totalPv = 7000.0;
                            break;
                        case 10620:
                            $totalPv = 6300.0;
                            break;
                        case 2360:
                            $totalPv = 1400.0;
                            break;
                        case 9440:
                            $totalPv = 5600.0;
                            break;
                        default:
                            $totalPv = round($oldOrder['money'] * 0.7, 2);
                            break;
                    }

                    $settlementTimeOld = $oldOrder['create_time'] ? date('Y-m-d H:i:s', $oldOrder['create_time']) : strtotime($user['create_time']);
                    // --- 收集贡献值插入数据 ---
                    $orderKey = $uid . '_' . $oldOrder['order_id'];
                    // 一个人 同一个订单 可能有多条记录 有问题
                    if (isset($existingGongXian[$orderKey])) {
                        $result['oldOrderExistGongXian'][] = ['uid' => $uid, 'order_id' => $oldOrder['order_id']];
                        $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$oldOrder['order_id']]);
                        if ($existingGongXian[$orderKey]['status'] == 1) {
                            if ($existingGongXian[$orderKey]['type'] == 1) {
                                $userUpdateData[$uid]['contribute'] += $existingGongXian[$orderKey]['number'];
                            } else if ($existingGongXian[$orderKey]['type'] == 2) {
                                $userUpdateData[$uid]['contribute'] -= $existingGongXian[$orderKey]['number'];
                            }
                        }
                        if (!empty($spreadUid) && isset($userUpdateData[$spreadUid])) {
                            $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$oldOrder['order_id']]);
                            if (isset($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']])) {
                                if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['status'] == 1) {
                                    if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['type'] == 1) {
                                        $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['number'];
                                    } else if ($existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['type'] == 2) {
                                        $userUpdateData[$spreadUid]['per_contribute'] -= $existingGongXian[$spreadUid . '_' . $oldOrder['order_id']]['number'];
                                    }
                                }
                            }
                        }
                    } else {
                        if ($totalPv > 0) {
                            $userUpdateData[$uid]['contribute'] += $totalPv;
                            // --- 收集贡献值插入数据 ---
                            $gongXianBase = [
                                "number" => $totalPv, "addtime" => strtotime($settlementTimeOld), "status" => 1,
                                "order_type" => 21, "order_id" => $oldOrder['order_id'],
                                "desc" => '', "surplus" => 0, "type" => 1, 'settlement_time' => $settlementTimeOld
                            ];
                            // 本人
                            $gongXianDataToInsert[] = array_merge(["uid" => $uid, "mark" => "购买会员专区商品赠送贡献值(1.0)"], $gongXianBase);
                            $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$oldOrder['order_id']]);
                            // 推广人
                            if (!empty($user['spread_uid'])) {
                                if (isset($userUpdateData[$spreadUid])) {
                                    $userUpdateData[$spreadUid]['per_contribute'] += $totalPv;
                                    $gongXianDataToInsert[] = array_merge(["uid" => $spreadUid, "mark" => "推广会员专区商品赠送贡献值(1.0)"], $gongXianBase);
                                    $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$oldOrder['order_id']]);
                                }
                            }
                        }
                    }
                    // --- 收集 PV 插入数据 ---
                    if (isset($existingPv[$orderKey])) {
                        $result['oldOrderExistPv'][] = ['uid' => $uid, 'order_id' => $oldOrder['order_id']];
                        if ($existingPv[$orderKey]['status'] == 1) {
                            $userUpdateData[$uid]['pv'] += $existingPv[$orderKey]['pv'];
                        }
                    } else {
                        $userUpdateData[$uid]['pv'] += $totalPv;
                        $pvDataToInsert[] = [
                            "uid" => $uid, "pv" => $totalPv, "addtime" => strtotime($settlementTimeOld), "status" => 1,
                            "order_type" => 21, "order_id" => $oldOrder['order_id'],
                            "mark" => "购买会员专区商品赠送PV(1.0)", 'settlement_time' => $settlementTimeOld
                        ];
                    }
                    if (!empty($existingPvByUid[$uid])) {
                        $existingPvByUid[$uid] = array_diff($existingPvByUid[$uid], [$oldOrder['order_id']]);
                    }
                }
            } // end if isset($userOfGoodsByUid[$uid])

            // --- 处理新订单 ---
            if (isset($storeOrdersByUid[$uid])) {
                foreach ($storeOrdersByUid[$uid] as $order) {
                    $totalPv = 0.0;
                    // ... (if/else logic and switch case for $totalPv calculation - same as before)
                    if ($order['mer_id'] == 496) {
                        switch ($order['pay_price']) {
                            case 1180:
                                $totalPv = 700.0;
                                break;
                            case 11800:
                                $totalPv = 7000.0;
                                break;
                            case 10620:
                                $totalPv = 6300.0;
                                break;
                            case 2360:
                                $totalPv = 1400.0;
                                break;
                            case 9440:
                                $totalPv = 5600.0;
                                break;
                            default:
                                $totalPv = round($order['pay_price'] * 0.7, 2);
                                break;
                        }
                    } else if ($order['status'] == 3) {
                        $totalPv = round($order['pay_price'] * 0.7, 2);
                    }
                    // --- 收集贡献值插入数据 ---
                    $orderKey = $uid . '_' . $order['order_id'];
                    $settlementTimeNew = $order['create_time'] ?: date('Y-m-d H:i:s', $user['create_time']);
                    // --- 收集贡献值插入数据 ---
                    if (isset($existingGongXian[$orderKey])) {
                        $result['orderExistGongXian'][] = ['uid' => $uid, 'order_id' => $order['order_id']];
                        $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$order['order_id']]);
                        // 累加计算值
                        if ($existingGongXian[$orderKey]['status'] == 1) {
                            if ($existingGongXian[$orderKey]['type'] == 1) {
                                $userUpdateData[$uid]['contribute'] += $existingGongXian[$orderKey]['number'];
                            } else if ($existingGongXian[$orderKey]['type'] == 2) {
                                $userUpdateData[$uid]['contribute'] -= $existingGongXian[$orderKey]['number'];
                            }
                        }
                        if (!empty($spreadUid) && isset($userUpdateData[$spreadUid])) {
                            $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$order['order_id']]);
                            if (isset($existingGongXian[$spreadUid . '_' . $order['order_id']])) {
                                if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['status'] == 1) {
                                    if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['type'] == 1) {
                                        $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $order['order_id']]['number'];
                                    } else if ($existingGongXian[$spreadUid . '_' . $order['order_id']]['type'] == 2) {
                                        $userUpdateData[$spreadUid]['per_contribute'] += $existingGongXian[$spreadUid . '_' . $order['order_id']]['number'];
                                    }
                                }
                            }
                        }

                    } else {
                        if ($totalPv > 0) {
                            $userUpdateData[$uid]['contribute'] += $totalPv;
                            $gongXianBase = [ // 优化: 提取公共字段
                                "number" => $totalPv, "addtime" => strtotime($settlementTimeNew), "status" => 1,
                                "order_type" => 22, "order_id" => $order['order_id'],
                                "desc" => '', "surplus" => 0, "type" => 1, 'settlement_time' => $settlementTimeNew
                            ];
                            // 本人
                            $gongXianDataToInsert[] = array_merge(["uid" => $uid, "mark" => "购买商品赠送贡献值(2.0)"], $gongXianBase);
                            $existingGongXianByUid[$uid] = array_diff($existingGongXianByUid[$uid], [$order['order_id']]);
                            // 推广人
                            if (!empty($user['spread_uid'])) {
                                $spreadUid = $user['spread_uid'];
                                if (isset($userUpdateData[$spreadUid])) { // 确保推广者存在
                                    $gongXianDataToInsert[] = array_merge(["uid" => $spreadUid, "mark" => "推广商品赠送贡献值(2.0)"], $gongXianBase);
                                    $userUpdateData[$spreadUid]['per_contribute'] += $totalPv; // 累加推广者业绩
                                    $existingGongXianByUid[$spreadUid] = array_diff($existingGongXianByUid[$spreadUid], [$order['order_id']]);
                                }
                            }
                        }
                    }

                    // --- 收集 PV 插入数据 ---
                    if (isset($existingPv[$orderKey])) {
                        $result['orderExistPv'][] = ['uid' => $uid, 'order_id' => $order['order_id']];
                        if ($existingPv[$orderKey]['status'] == 1) {
                            $userUpdateData[$uid]['pv'] += $existingPv[$orderKey]['pv'];
                        }
                    } else {
                        $userUpdateData[$uid]['pv'] += $totalPv;
                        $pvDataToInsert[] = [
                            "uid" => $uid, "pv" => $totalPv, "addtime" => strtotime($settlementTimeNew), "status" => 1,
                            "order_type" => 22, // 确认 PV log 的 order_type 是否与贡献一致或有区分
                            "order_id" => $order['order_id'],
                            "mark" => "购买商品赠送PV(2.0)", // 标记调整为更通用
                            'settlement_time' => $settlementTimeNew
                        ];
                    }
                    if (!empty($existingPvByUid[$uid])) {
                        $existingPvByUid[$uid] = array_diff($existingPvByUid[$uid], [$order['order_id']]);
                    }
                }
            }
            // end if isset($storeOrdersByUid[$uid])

            // --- 比较计算值与原值 (移到循环外处理) ---
            // （在此处比较并记录到 $result['contributeNot'] / $result['pvNot']）
            // 注意：浮点数比较可能需要容差
            $tolerance = 0.001; // 定义一个小的容差值
            if (abs($userUpdateData[$uid]['contribute'] - (float)$user['contribute']) > $tolerance) {
                $result['contributeNot'][] = [
                    'uid' => $uid,
                    'contribute_old' => (float)$user['contribute'], // 显式转换
                    'contribute_new' => $userUpdateData[$uid]['contribute']
                ];
            }
            if (abs($userUpdateData[$uid]['pv'] - (float)$user['pv']) > $tolerance) {
                $result['pvNot'][] = [
                    'uid' => $uid,
                    'pv_old' => (float)$user['pv'], // 显式转换
                    'pv_new' => $userUpdateData[$uid]['pv']
                ];
            }
            // per_contribute 是累加的，不需要与旧值比较，直接更新

        } // end foreach ($userList as $uid => $user)

        // *** 数据库批量操作 ***
        // 使用事务确保数据一致性
        Db::startTrans();
        try {
            $bill = [];
            foreach ($oldUserList as $item) {
                $bill[] = [
                    'uid' => $item['id'],
                    'link_id' => 0,//关联订单id
                    'pm' => 1,//0：支出，1：获得
                    'title' => '佣金',//账单标题
                    'category' => 'now_money',//明细种类
                    'type' => 'commission',//明细类型
                    'number' => $item['amount'],//明细数字
                    'balance' => 0,//剩余
                    'mark' => '1.0佣金记录',//备注
                    'create_time' => '2025-02-04 00:00:00',//添加时间
                    'status' => 1,//0待确定，1有效，-1无效
                    'commission_type' => 21,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
                    //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
                    //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
                    'order_sn' => 0,//订单号
                    'tripartite' => 0,//
                    'type_shop' => 0,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
                    'mer_id' => 0,//商户id
                    'source' => 0,//1线下 0线上
                    'order_type' => 1,//1自营  2 第三方  订单类型
                    'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
                    'gzc' => 3,//养老金是否已进入公证处log表0：未进入。1：已进入
                    'take_time' => '',//结算时间
                    'district_id' => '',//
                    'street_id' => '',//
                    'month' => '',//月份


                ];
            }
            $chunkedBill = array_chunk($bill, 500);
            foreach ($chunkedBill as $chunk) {
                Db::name('user_bill')->insertAll($chunk);
            }

            if (!empty($existingGongXianByUid)) {
                foreach ($existingGongXianByUid as $uid => $orderList) {
                    if (!empty($orderList)) {
                        Db::name("user_sign_gongxian")
                            ->where('uid', $uid)
                            ->whereIn('order_id', $orderList)
                            ->update(['status' => 0]);
                    }
                }
            }
            if (!empty($existingPvByUid)) {
                foreach ($existingPvByUid as $uid => $orderList) {
                    if (!empty($orderList)) {
                        Db::name("user_pv_log")
                            ->where('uid', $uid)
                            ->whereIn('order_id', $orderList)
                            ->update(['status' => 0]);
                    }
                }
            }
            // --- 批量插入贡献值 ---
            if (!empty($gongXianDataToInsert)) {
                // 分块插入，避免单次插入过多数据 (例如一次500条)
                $chunkedGongXian = array_chunk($gongXianDataToInsert, 500);
                foreach ($chunkedGongXian as $chunk) {
                    $insertedGongXianCount = Db::name('user_sign_gongxian')->insertAll($chunk);
                    $result['insertGongXianSummary']['success'] += $insertedGongXianCount;
                }

                if ($result['insertGongXianSummary']['success'] < count($gongXianDataToInsert)) {
                    $result['insertGongXianSummary']['failed'] = count($gongXianDataToInsert) - $result['insertGongXianSummary']['success'];
                    // 可以考虑记录更详细的失败信息，但这比较复杂，需要知道哪些失败了
                    $result['errors'][] = "GongXian insertion partially failed or failed completely.";
                    // 根据业务决定是否回滚
                    // throw new Exception("GongXian insertion failed");
                }
            } else {
                $result['insertGongXianSummary']['skipped'] = true; // 标记为跳过（无数据）
            }

            // --- 批量插入PV ---
            if (!empty($pvDataToInsert)) {
                $chunkedPv = array_chunk($pvDataToInsert, 500);
                foreach ($chunkedPv as $chunk) {
                    $insertedPvCount = Db::name('user_pv_log')->insertAll($chunk);
                    $result['insertPvSummary']['success'] += $insertedPvCount;
                }
                if ($result['insertPvSummary']['success'] < count($pvDataToInsert)) {
                    $result['insertPvSummary']['failed'] = count($pvDataToInsert) - $result['insertPvSummary']['success'];
                    $result['errors'][] = "PV Log insertion partially failed or failed completely.";
                    // throw new Exception("PV Log insertion failed");
                }
            } else {
                $result['insertPvSummary']['skipped'] = true; // 标记为跳过（无数据）
            }

            // --- 批量更新用户信息 ---
            $usersToUpdate = [];
            // 筛选出实际需要更新的用户数据 (值有变化或 per_contribute > 0)
            foreach ($userUpdateData as $uid => $updateInfo) {
                $originalUser = $userList[$uid]; // 获取原始用户信息
                // 检查 contribute 或 pv 是否变化（使用容差），或者 per_contribute 是否需要更新
                $needsUpdate = false;
                if (abs($updateInfo['contribute'] - (float)$originalUser['contribute']) > $tolerance) $needsUpdate = true;
                if (abs($updateInfo['pv'] - (float)$originalUser['pv']) > $tolerance) $needsUpdate = true;
                // per_contribute 始终更新，因为它是在现有基础上累加的（除非业务定义不同）
                // 如果 per_contribute 数据库设计是直接覆盖，那只有 > 0 时才需要更新
                // 假设是覆盖更新，且只有大于0时才需要更新变动（如果一直是0则不用更新）
                if ($updateInfo['per_contribute'] > 0.0) { // 只有当推广业绩>0时才触发更新
                    // 这里需要确认 per_contribute 是覆盖还是累加?
                    // 如果是数据库累加: Db::name("user")->where('uid', $uid)->inc('per_contribute', $amount)->update(); 需要单独处理
                    // 如果是覆盖: 直接放入 saveAll
                    // 假设是覆盖，我们只更新有变化的或per_contribute > 0 的
                    $needsUpdate = true;
                } else {
                    // 如果 per_contribute 计算结果为0，且 contribute 和 pv 也未变，则不需要更新 per_contribute 字段
                    unset($updateInfo['per_contribute']); // 移除无需更新的 per_contribute
                    if (empty($updateInfo)) $needsUpdate = false; // 如果移除后为空，则不更新
                }

                if ($needsUpdate) {
                    // 确保只包含需要更新的字段，并且包含主键 'uid'
                    $finalUpdateData = ['uid' => $uid];
                    if (isset($updateInfo['contribute'])) $finalUpdateData['contribute'] = $updateInfo['contribute'];
                    if (isset($updateInfo['pv'])) $finalUpdateData['pv'] = $updateInfo['pv'];
                    if (isset($updateInfo['per_contribute']) && $updateInfo['per_contribute'] > 0.0) { // 再次确认只更新大于0的推广业绩
                        $finalUpdateData['per_contribute'] = $updateInfo['per_contribute'];
                    }

                    if (count($finalUpdateData) > 1) { // 确保除了uid还有其他字段要更新
                        $usersToUpdate[] = $finalUpdateData;
                    } else {
                        $result['userUpdateSummary']['skipped']++; // 记录跳过的更新（无变化）
                    }

                } else {
                    $result['userUpdateSummary']['skipped']++; // 记录跳过的更新（无变化）
                }
            }

            if (!empty($usersToUpdate)) {
                // 使用 saveAll 进行批量更新 (要求 PHP >= 7.1.8 for MySQL)
                // saveAll 会根据主键 'uid' 更新对应记录
                $userModel = new User();
                $updatedCount = $userModel->saveAll($usersToUpdate); // TP6 支持 saveAll

                // 注意: saveAll 返回的是成功保存或更新的 *对象集合* 或 *布尔值*，不是影响的行数。
                // 需要检查返回类型并判断成功数量。通常返回集合时 count(集合) 是成功数。
                // 如果是 TP5，可能需要循环 update 或构造复杂 SQL。
                // 假设 TP6 saveAll 成功会返回包含更新后数据的集合或true，失败是false
                if ($updatedCount !== false) {
                    // 这里需要一种方法来确定实际更新了多少条记录。
                    // saveAll 的返回值可能需要进一步处理。
                    // 简单假设：如果返回不是 false，就认为请求中的都成功了（可能不准确）
                    // 更精确的方法是 saveAll 后再查询一次确认。
                    // 这里我们暂时认为 saveAll 返回非 false 即为大部分成功
                    $result['userUpdateSummary']['success'] = count($usersToUpdate); // 乐观估计
                } else {
                    $result['userUpdateSummary']['failed'] = count($usersToUpdate); // 全部失败
                    $result['errors'][] = "User batch update failed using saveAll.";
                    // throw new Exception("User batch update failed");
                }
            }
            // 更新统计：失败数等于总数减去成功和跳过的
            //$result['userUpdateSummary']['failed'] = count($userList) - $result['userUpdateSummary']['success'] - $result['userUpdateSummary']['skipped'];

            // 如果所有操作都成功，提交事务
            Db::commit();

        } catch
        (\Exception $e) {
            // 如果任何数据库操作失败，回滚事务
            Db::rollback();
            // 记录错误信息
            $result['errors'][] = "Transaction failed: " . $e->getMessage();
            // 可以根据需要将 insert/update 摘要设置为失败
            $result['userUpdateSummary']['failed'] = count($usersToUpdate); // 假设更新失败
            $result['insertGongXianSummary']['failed'] = count($gongXianDataToInsert); // 假设插入失败
            $result['insertPvSummary']['failed'] = count($pvDataToInsert);      // 假设插入失败
        }

        // --- 清理/最终结果赋值 (可选) ---
        // $result['gongXianDataOldList'] = $gongXianDataOldList; // 这些已合并到 ToInsert
        // $result['gongXianDataList'] = $gongXianDataList;
        // $result['pvDataOldList'] = $pvDataOldList;
        // $result['pvDataList'] = $pvDataList;

        return json($result);

        //        // 计算总业绩
        //        $totalPv = [];
        //        foreach ($user_team_amount as $order) {
        //            if (!isset($totalPv[$order['user_id']])) {
        //                $totalPv[$order['user_id']] = 0;
        //            }
        //            switch ($order['money']) {
        //                case 1180:
        //                    $totalPv[$order['user_id']] += 700;
        //                    break;
        //                case 11800:
        //                    $totalPv[$order['user_id']] += 7000;
        //                    break;
        //                case 10620:
        //                    $totalPv[$order['user_id']] += 6300;
        //                    break;
        //                case 2360:
        //                    $totalPv[$order['user_id']] += 1400;
        //                    break;
        //                case 9440:
        //                    $totalPv[$order['user_id']] += 5600;
        //                    break;
        //                default:
        //                    if ($order['money'] == 2344.99) {
        //                        break;
        //                    }
        //                    $totalPv[$order['user_id']] += round($order['money'] * 0.7, 2);
        //                    break;
        //            }
        //        }
        //        foreach ($totalPv as $uid => $pv) {
        //            Db::name("user")->where('is_old', 1)->where("uid", $uid)->update(['pv' => $pv]);
        //        }
        //
        //        return;
        //        /**
        //         * 周金花200(13959100621)
        //         * 黄金花200(18603401312)
        //         * 徐立苹100(13521438652)
        //         * 李素红200(13701061395)
        //         * 周行体200(13231658486)
        //         * 刘银霞100(13161909228)
        //         * 李卫东100(13911601230)
        //         * 金    波100(13801358713)
        //         * 王   玲 150(15810064711)
        //         * 侯玉兰150(15232797965)
        //         * 吕丽娣100(15960349667)
        //         * 张传莲100(15332507711)
        //         * 刘春梅100(18760167163)
        //         * 付天如100(18863873000)
        //         * 付绍先100(15324059286)
        //         * 黄桂林100(15960196876)
        //         * 温  煌100(18350134089)
        //         * 谭英先100(13978627072)
        //         * 陈玉珍100(19858353660)
        //         * 黄雪云100(18650055445)
        //         * 黄  玲100(13877193411)
        //         * 邱佳珍100(13960379098)
        //         * 隋彩云100（13601071082）
        //         */
        //        $data = [
        //            '13959100621' => 200,
        //            '18603401312' => 200,
        //            '13521438652' => 100,
        //            '13701061395' => 200,
        //            '13231658486' => 200,
        //            '13161909228' => 100,
        //            '13911601230' => 100,
        //            '13801358713' => 100,
        //            '15810064711' => 150,
        //            '15232797965' => 150,
        //            '15960349667' => 100,
        //            '15332507711' => 100,
        //            '18760167163' => 100,
        //            '18863873000' => 100,
        //            '15324059286' => 100,
        //            '15960196876' => 100,
        //            '18350134089' => 100,
        //            '13978627072' => 100,
        //            '19858353660' => 100,
        //            '18650055445' => 100,
        //            '13877193411' => 100,
        //            '13960379098' => 100,
        //            '13601071082' => 100,
        //        ];
        //        $result = Db::name("user")
        //            ->whereIn("account", array_keys($data))
        //            ->where('is_del', 0)
        //            ->field('uid, brokerage_price, account, nickname')
        //            ->select();
        //        $res = [];
        //        foreach ($result as $v) {
        //            Db::name("user")->where("uid", $v['uid'])->inc("brokerage_price", $data[$v['account']])->save();
        //            $this->bill_user_log111111($v['uid'], "佣金补贴", $data[$v['account']], "佣金补贴", 8);//股权分佣明细2.0系统
        //            $res[] = [
        //                'uid' => $v['uid'],
        //                'account' => $v['account'],
        //                'brokerage_price_pre' => $v['brokerage_price'],
        //                'brokerage_price' => $data[$v['account']],
        //                'nickname' => $v['nickname']
        //            ];
        //        }
        //        return json($res);

    }

    public function lst6(Request $request)
    {
        $startTime = $request->param('startTime', null);
        $endTime = $request->param('endTime', null);
        $isTest = $request->param('isTest', 1);
        $maxAllocationAmount = $request->param('maxAllocationAmount', null);
        // 查询测试人员账号信息
        //18973958920
        //15186694339
        //18833633835
        //19525470098
        //17756507016
        //18226705337
        $testAccount = ['18973958920', '15186694339', '18833633835', '19525470098', '17756507016', '18226705337', '17855366921'];
        $removeUserList = Db::name("user")
            ->whereIn('account', $testAccount)
            ->where("status", "<>", 0)
            ->where('is_del', '<>', 1)
            ->select()
            ->toArray();
        $removeUserIdList = array_column($removeUserList, 'uid');

        $zeroLineUidList = [1420, 2328, 1720];
        foreach ($zeroLineUidList as $uid) {
            //查询当前团队的用户列表
            $sql = "select getUserLevelId($uid) as uids";
            //\think\facade\Log::info("lplpDB".$sql);
            try {
                $spread_user_list = Db::query($sql);
            } catch (\Exception $exception) {
                return json($exception->getMessage());
            }
            $removeUserIdList = array_merge(explode(",", trim($spread_user_list[0]['uids'], '$,')), $removeUserIdList);
        }

        if (empty($startTime) || empty($endTime)) {
            $timeMap = $this->getTime('last_week');
            $startTime = $timeMap['startTime'] . ' 00:00:00';
            $endTime = $timeMap['endTime'] . ' 23:59:59';
        }

        // 定义分红金额
        $weekRecord = $this->getTeamPvByTime($startTime, $endTime, $removeUserIdList);
        // 分红金额 - 红包金额
        $redEnvelope = $this->getRedEnvelopeByTime($startTime, $endTime, $removeUserIdList);

        $weekRecord -= $redEnvelope;

        if (!is_null($maxAllocationAmount)) {
            $weekRecord = $maxAllocationAmount;
        }

        if ($weekRecord <= 0) {
            return json('无效分红金额');
        }

        // $stock_comm = round($weekRecord * 0.05 ,2);
        $stock_comm = floor(($weekRecord * 0.05) * 100) / 100;

        //获取股权分红的人

        $GetAllUserPackNum = db::name("old_user_stock")->sum("pack");//计算所有用户的份数总和

        $stockuserdatas = db::name("old_user_stock")->select();//获取所有用户

        $salesArr = [];
        if (count($stockuserdatas) > 0) {
            // $one_pack_comm_data = round($stock_comm / $GetAllUserPackNum,2);//获取每份的单佣金
            $one_pack_comm_data = floor(($stock_comm / $GetAllUserPackNum) * 100) / 100;

            foreach ($stockuserdatas as &$v) {
                $salesArr[] = [
                    'stock_comm' => $stock_comm,
                    'GetAllUserPackNum' => $GetAllUserPackNum,
                    'uid' => $v['user_id'],
                    'pack' => $v['pack'],
                    'one_pack_comm_data' => $one_pack_comm_data,
                    'getcomm' => floor(($v['pack'] * $one_pack_comm_data) * 100) / 100
                ];
                $v['getcomm'] = floor(($v['pack'] * $one_pack_comm_data) * 100) / 100;
                $v['allgetcomm'] = $v['allgetcomm'] + $v['getcomm'];
                $v['update_time'] = time();

                $yj_90 = $v['getcomm'] * 0.9;
                $fg_10 = $v['getcomm'] * 0.1;

                if ($isTest == 0) {
                    // // 更新 user_stock 表中的记录
                    $res = db::name("old_user_stock")->where("id", $v['id'])->update([
                        'getcomm' => $v['getcomm'],
                        'allgetcomm' => $v['allgetcomm'],
                        'update_time' => $v['update_time']
                    ]);

                    $res1 = Db::name("user")->where("uid", $v['user_id'])->inc("total_amount_old", $yj_90)->save();
                    $res2 = Db::name("user")->where("uid", $v['user_id'])->inc("amount_old", $yj_90)->save();
                    Db::name("user")->where("uid", $v['user_id'])->inc("brokerage_price", $yj_90)->save();
                    $res3 = Db::name("user")->where("uid", $v['user_id'])->inc("fugou", $fg_10)->save();

                    $res = true;
                    if ($res) {
                        $das = $this->change_user_log($v['user_id'], 'amount_old', 1, $yj_90, "member_award_stock", "股权分红入账" . "-" . $v['pack']);//释放佣金

                        //入账星级分红记录表
                        $week_data = [];
                        $week_data['user_id'] = $v['user_id'];
                        $week_data['user_star_id'] = 0;
                        $week_data['award_num'] = 0;
                        $week_data['award_num_sm'] = 0;
                        $week_data['remark'] = "股权分红主动执行" . $yj_90;
                        $week_data['week_record'] = $weekRecord;
                        $week_data['all_amount'] = $stock_comm;
                        $week_data['radio'] = 2;
                        $week_data['owner_bill'] = 0;  //总流水金额
                        $week_data['my_bill'] = 0;  //我的流水
                        $week_data['create_time'] = time();


                        Db::name("old_user_weekaward")->insert($week_data);

                        $userdatassss = db::name("old_user_jbp")->where("id", $v['user_id'])->find();
                        $datas_log = [
                            'note' => "名称:" . $userdatassss['nick_name'] . " 用户:" . $v['user_id'] . " 新增股权佣金:" . $yj_90,
                            'create_time' => date('Y-m-d H:i:s')
                        ];
                        $con_data = Db::name('test_log')->insert($datas_log);   //数据存到2.0数据表中

                        $this->bill_user_log111111($v['user_id'], "股权分佣", $yj_90, "股权明细入账", 13);//股权分佣明细2.0系统

                        $this->fugou_user_log($v['user_id'], $fg_10, 16, 1, 1);//复购金明细入账
                    }
                }
            }
        }
        return json($salesArr);
        //股权分红 end
    }

    //添加复购金
    public function fugou_user_log($uid, $num, $order_id, $type_inc_des, $status = -1)
    {

        $fugou_data = Db::name('user')->where("uid", $uid)->find();


        $bill = [
            'uid' => $uid,
            'number' => $num,//数量
            'status' => $status,//复购金状态1-有效 0-失效 -1待确认
            'mark' => "复购金",//备注
            'desc' => "10%作为复购金",//描述
            'order_id' => $order_id,//订单id
            'surplus' => 0,//剩余
            'order_type' => 11,//关联订单ID
            'type' => $type_inc_des,//复购金类型 :1赠送，2消耗
            'settlement_time' => date('Y-m-d H:i:s'),//添加时间,
            'addtime' => time(),
        ];

        Db::name('user_sign_fugou')->insert($bill);
    }

    //添加平台分佣2.0系统收益明细日志(养老金金额)
    public function bill_user_log111111($uid, $name, $num, $mark, $comm)
    {

        $con_data = Db::name('user')->where("uid", $uid)->find();
        //如果是会员专区就即刻到账

        // Db::name('user')->where("uid",$con_data['uid'])->update(['brokerage_price'=> $con_data['brokerage_price'] + $num]);


        $bill = [
            'uid' => $uid,
            'link_id' => 0,//关联订单id
            'pm' => 1,//0：支出，1：获得
            'title' => $name,//账单标题
            'category' => 'now_money',//明细种类
            'type' => 'commission',//明细类型
            'number' => $num,//明细数字
            'balance' => 0,//剩余
            'mark' => $mark,//备注
            'create_time' => date('Y-m-d H:i:s'),//添加时间
            'status' => 1,//0待确定，1有效，-1无效
            'commission_type' => $comm,//佣金类型 1代理费 2 消费佣金 3直推奖√ 4辖区佣金\r\n5 养老金√ 6 广告费
            //7 跨店奖励√ 8平台奖励 9渠道商\r\n10 推荐创客收益√ 11分红奖金√ 12代理区域收益√ 13消费循环佣金
            //14-推荐代理收益√ 15邀请小区团长升级√ 16大v分享奖√ 17创客合伙人√ 18积分奖励√ 19创客补贴√’
            'order_sn' => 0,//订单号
            'tripartite' => 0,//
            'type_shop' => 0,//0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上
            'mer_id' => 0,//商户id
            'source' => 0,//1线下 0线上
            'order_type' => 1,//1自营  2 第三方  订单类型
            'is_red_brokerage' => 0,//1红积分对冲佣金 0正常佣金
            'gzc' => 3,//养老金是否已进入公证处log表0：未进入。1：已进入
            'take_time' => time(),//结算时间
            'district_id' => '',//
            'street_id' => '',//
            'month' => '',//月份


        ];

        Db::name('user_bill')->insert($bill);
    }


    //发放佣金 示例: $this->change_user_log($v,'amount',1,$all_award,"member_award","星级分红入账"."-".$value['title']);//释放佣金
    function change_user_log($user_id, $type, $change_status, $money, $routine, $remark = "", $is_admin = 1, $appoint_money = 0)
    {
        $transition = [
            'pv' => 1,
            "gb" => 2,
            "df" => 3,
            "vr" => 4,
            "bt" => 5,
            "withdraw_quota_old" => 6,//提现
            "unsettled_pension" => 7,
            "amount_old" => 8//发放佣金
        ];
        $routineInfo = Db::name("old_routine_log_of_key")->where("key", $routine)->find();
        if (empty($routineInfo)) {
            return false;
        }
        $key_id = isset($routineInfo['id']) ? $routineInfo['id'] : 0;

        if ($appoint_money > 0) {
            $alter_money = $appoint_money;
        } else {
            //再去查询变更前的 金额
            $alter_money = Db::name("user")->where('uid', $user_id)->value($type);
        }
        if ($change_status == 1) {
            //新增前
            $alter_money = $alter_money - $money;
        } else if ($change_status == 2) {
            //减少前
            $alter_money = $alter_money + $money;
        }
        if ($alter_money < 0) {
            $alter_money = 0;
        }
        $inser_data = [];
        $inser_data['user_id'] = $user_id;
        $inser_data['type'] = $transition[$type];
        $inser_data['change_status'] = $change_status;
        $inser_data['money'] = $money;
        $inser_data['routine_log_of_key_id'] = $key_id;
        $inser_data['remark'] = $remark;
        $inser_data['is_admin'] = $is_admin;
        $inser_data['create_time'] = time();
        $inser_data['alter_money'] = isset($alter_money) ? $alter_money : 0;
        Db::name("old_user_log")->insert($inser_data);
    }

    public function getTime($timePeriod)
    {
        // 定义时间区间
        $now = time();
        $startTime = '';
        $endTime = '';
        if ($timePeriod == 'last_week') {
            // 上周的时间区间
            $startTime = date('Y-m-d', strtotime('monday last week', $now)); // 上周星期一的开始时间
            $endTime = date('Y-m-d', strtotime('sunday last week', $now)); // 上周星期日的结束时间
        } elseif ($timePeriod == 'this_week') {
            // 这周的时间区间
            $startTime = date('Y-m-d', strtotime('monday this week', $now)); // 这周星期一的开始时间
            $endTime = date('Y-m-d', strtotime('sunday this week', $now)); // 这周星期日的结束时间
        }
        //        return ['startTime' => '2025-03-10', 'endTime' => '2025-03-23'];
        return ['startTime' => $startTime, 'endTime' => $endTime];
    }

    public function getTeamPvByTime($startTime, $endTime, $removeUserIdList = [])
    {
        // 查询指定时间区间内的所有订单，并排除 pay_time 为 NULL 的订单
        $orders = Db::name("store_order")
            ->alias('a')
            ->where('a.mer_id', 496)
            ->whereNotIn('a.uid', $removeUserIdList)
            ->whereIn('a.status', [0, 1, 2, 3])
            // ->whereIn("a.total_price", [1180, 11800, 10620, 2360, 9440])
            ->whereBetween("a.pay_time", [$startTime, $endTime])
            ->whereNotNull("a.pay_time") // 排除 pay_time 为 NULL 的订单
            ->leftJoin('rrx_store_cart b', 'a.cart_id = b.cart_id')
            ->field('a.mer_id, a.cart_id, a.status, a.pay_time, a.total_price, b.product_id')
            ->select();

        // 计算总业绩
        $totalPv = 0;
        foreach ($orders as $order) {
            switch ($order['product_id']) {
                case in_array($order['product_id'], [15762, 15763]):
                    $totalPv += 700;
                    break;
                case in_array($order['product_id'], [15813, 15820]):
                    $totalPv += 7000;
                    break;
                case in_array($order['product_id'], [15814, 15819]):
                    $totalPv += 6300;
                    break;
                case in_array($order['product_id'], [15815, 15817]):
                    $totalPv += 1400;
                    break;
                case in_array($order['product_id'], [15816, 15818]):
                    $totalPv += 5600;
                    break;
                case in_array($order['product_id'], [17610]):
                    $totalPv += 35;
                    break;
                case in_array($order['product_id'], [17611]):
                    $totalPv += 175;
                    break;
                case in_array($order['product_id'], [17612]):
                    $totalPv += 350;
                    break;
            }
        }

        return $totalPv;
    }

    public function getRedEnvelopeByTime($startTime, $endTime, $removeUserIdList = [])
    {
        // 查询指定时间区间内的所有订单，并排除 pay_time 为 NULL 的订单
        $redEnvelopeList = Db::name("user_sign_hongbao")
            ->whereNotIn('uid', $removeUserIdList)
            ->where('status', 1)
            ->whereBetween("settlement_time", [$startTime, $endTime])
            ->select()
            ->toArray();
        return floor(array_sum(array_column($redEnvelopeList, 'number')) * 100) / 100;
    }
}
