<?php


namespace app\controller\api\store\merchant;


use think\facade\Db;
use think\Request;

class TaskZeroLinePartnerProfits
{
    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, $userIdList = [])
    {
        // 查询指定时间区间内的所有订单，并排除 pay_time 为 NULL 的订单
        // 0平台1多多进宝2唯品会3苏宁易购4网易考拉5淘宝客6京东联盟7饿了么8线上9话费10线下
        $pvLogList = Db::name("user_pv_log")
            ->whereIn('uid', $userIdList)
            // ->whereIn('order_type', [0])
            ->where('status', '=', 1)
            ->whereBetween("settlement_time", [$startTime, $endTime])
            ->whereNotNull("settlement_time") // 排除 pay_time 为 NULL 的订单
            ->select()
            ->toArray();

        // 计算总业绩
        $totalPv = 0;
        foreach ($pvLogList as $pvLog) {
            $totalPv = bcadd($totalPv, $pvLog['pv'], 2);
        }

        return $totalPv;
    }

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

    public function partnerProfitsByZeroLine(Request $request)
    {

        $startTime = $request->param('startTime', null);
        $endTime = $request->param('endTime', null);
        $isTest = $request->param('isTest', 1);
        $maxAllocationAmount = $request->param('maxAllocationAmount', null);

        // 查询测试人员账号信息
        $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');

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

        $zeroLineUidList = [32];
        $result = [];
        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) {
                $result[$uid] = $exception->getMessage();
                continue;
            }
            $spread_user_list = array_diff(explode(",", trim($spread_user_list[0]['uids'], '$,')), $removeUserIdList);
            if (empty($spread_user_list)) {
                $result[$uid] = '无团队成员1';
                continue;
            }

            // 定义分红金额
            $performance = $this->getTeamPvByTime($startTime, $endTime, $spread_user_list);
            // 分红金额 - 红包金额
            // $redEnvelope = $this->getRedEnvelopeByTime($startTime, $endTime, $spread_user_list);
            $redEnvelope = 0.00;
            $weekRecord = bcsub($performance, $redEnvelope, 2);
            if (!is_null($maxAllocationAmount)) {
                $weekRecord = $maxAllocationAmount;
            }

            if ($weekRecord <= 0) {
                $result[$uid] = '无效分红金额';
                continue;
                // return json('无效分红金额');
            }

            // 1、获取用户星级信息
            //$star_list = Db::name("user_star")->order("statement_all_num desc")->select()->toArray();//旧星级等级
            $starList = Db::name("old_user_starlevel")
                ->whereIn('title', ['初级', '中级', '高级'])
                ->order("statement_all_num desc")
                ->select()
                ->toArray();//星级等级

            // 2、循环星级信息 并分组归类
            $salesArr = array_column($starList, null, 'title');

            // 3、获取 分红用户 信息 （`user_group` tinyint(1) DEFAULT '1' COMMENT '1消费者 2,推广业务员 3，业务经理 4初级合伙人5中级合伙人 6高级合伙人 7.懂事',）
            $list = Db::name("user")
                ->whereIn('uid', $spread_user_list)
                ->where("user_group", "IN", [4, 5, 6])
                ->where("status", "<>", 0)
                ->where('is_del', '<>', 1)
                ->select()
                ->toArray();

            if (empty($list)) {
                $result[$uid] = '无有效分红人员';
                continue;
            }

            // 4、将用户装载到 星级等级 分红数据中
            $salesArr['初级']['user_group'] = 4;
            $salesArr['初级']['divider_people']= [] ;
            $salesArr['中级']['user_group'] = 5;
            $salesArr['中级']['divider_people'] = [];
            $salesArr['高级']['user_group'] = 6;
            $salesArr['高级']['divider_people'] = [];

            foreach ($list as $key => $value) {
                if ($value['user_group'] == 4) {
                    $salesArr['初级']['user_group'] = $value['user_group'];
                    $salesArr['初级']['divider_people'][] = $value['uid'];
                } else if ($value['user_group'] == 5) {
                    $salesArr['中级']['user_group'] = $value['user_group'];
                    $salesArr['中级']['divider_people'][] = $value['uid'];
                } else if ($value['user_group'] == 6) {
                    $salesArr['高级']['user_group'] = $value['user_group'];
                    $salesArr['高级']['divider_people'][] = $value['uid'];
                }
            }
            $salesArr['初级']['divider_people_count'] = count($salesArr['初级']['divider_people']);
            $salesArr['中级']['divider_people_count'] = count($salesArr['中级']['divider_people']);
            $salesArr['高级']['divider_people_count'] = count($salesArr['高级']['divider_people']);

            if (!empty($salesArr['高级']['divider_people']) && in_array($uid, $salesArr['高级']['divider_people'])) {
                $result[$uid] = '已有高级合伙人';
                continue;
            }

            // 5、移除特定人员

            // 6、执行分开发放
            $partnerProfitsPvListByUid = [];
            foreach ($salesArr as $key => $value) {
                // 6.1 计算可分红金额
                //比如这个周的总业绩是 8400
                //周总业绩(8400) * 合伙人级别的分佣比例(15%) = 可分红的佣金(1260)
                //            $salesArr[$key]['fs_money_nums'] = round($weekRecord * $value['profit_rate'], 2);
                $salesArr[$key]['fs_money_nums'] = floor(($weekRecord * ($value['profit_rate'] / 100)) * 100) / 100;
                //可分红的业绩(分为两半，各50%，一部分是分给双联盟比例，一部分是小业绩比例)
                //把本周的业绩(8400) * 合伙人级别的分佣比例(15%) * 0.5 = 630（可分红佣金的 50%）
                //            $salesArr[$key]['fs_money'] = round($salesArr[$key]['fs_money_nums'] / 2, 2);
                $salesArr[$key]['fs_money'] = floor(($salesArr[$key]['fs_money_nums'] / 2) * 100) / 100;

                // 6.2 计算所有人的 PV值
                $salesArr[$key]['weekRecord'] = $weekRecord;
                $salesArr[$key]['redEnvelope'] = $redEnvelope;
                $salesArr[$key]['maxValueAll'] = 0;
                $salesArr[$key]['sumOfOthersAll'] = 0;
                $salesArr[$key]['dividerPeoplePv'] = [];
                foreach ($value['divider_people'] as $k => $v) {
                    // 6.2.1 查出分红人的所有部门 即 下级用户
                    $spreadUserUidList = $this->getSpreadUserUidListByUidList([$v]);
                    if (empty($spreadUserUidList[$v])) {
                        continue;
                    }

                    // 6.2.2 获取当前分红人的所有部门 内的下级成员，递归获取至最低一级
                    $subordinatesBatch = $this->getSubordinatesBatch($spreadUserUidList[$v]);
                    // 6.2.3 获取所有部门（下线）的PV值
                    foreach ($subordinatesBatch as $k1 => $v1) {
                        $partnerProfitsPvListByUid[$v][$k1] = 0;
                        // 获取当前下线的PV值, 忽略测试人员的账号
                        // $pv = $this->getPv(array_merge($v1, [$k1]), $removeUserIdList);
                        // $partnerProfitsPvListByUid[$v][$k1] += $pv;
                        $pvNew = $this->getPvNew(array_merge($v1, [$k1]), $removeUserIdList);
                        $partnerProfitsPvListByUid[$v][$k1] += $pvNew;
                    }

                    // 6.2.4 将PV值进行记录 以便后续计算
                    if (!empty($partnerProfitsPvListByUid[$v])) {
                        // 获取数组中的最大值
                        $maxValue = max($partnerProfitsPvListByUid[$v]);
                        // 计算总和
                        $totalSum = array_sum($partnerProfitsPvListByUid[$v]);
                        // 计算除最大值外其余值的和
                        $sumOfOthers = $totalSum - $maxValue;

                        $salesArr[$key]['dividerPeoplePv'][$v]['maxValue'] = $maxValue;
                        $salesArr[$key]['dividerPeoplePv'][$v]['sumOfOthers'] = $sumOfOthers;
                        $salesArr[$key]['maxValueAll'] += $maxValue;
                        $salesArr[$key]['sumOfOthersAll'] += $sumOfOthers;
                    }
                }
            }

            // 7、执行分红
            $testRecord = [];
            foreach ($salesArr as $key => $value) {
                $amount = $value['fs_money'];//可分红的总佣金，分红佣金的一半,中级合伙61.95
                $fsMoneyNums = $value['fs_money_nums'];//中级合伙人级别，可分红的总佣金
                $maxValueAll = $value['maxValueAll'];//当前级别合伙人下面所有的双联盟业绩
                $sumOfOthersAll = $value['sumOfOthersAll'];//当前级别合伙人下面所有的小区(业绩小的部分)总业绩

                if (count($value['divider_people']) <= 0) {
                    continue;
                }
                //每人分红金额
                foreach ($value['divider_people'] as $v) {

                    //个人小区(佣金少的一部分) 权重 计算权重
                    //返回是数组，下标0是最小的值(业绩小的)，下标1是最大的值(业绩大的)
                    $userPvSmallNum = $value['dividerPeoplePv'][$v]['sumOfOthers'] ?? 0;
                    //                $myMixMoney = round($amount * ($userPvSmallNum / $sumOfOthersAll), 2);
                    $myMixMoney = floor(($amount * (floor(($userPvSmallNum / $sumOfOthersAll) * 100000) / 100000)) * 100) / 100;

                    //个人双区总佣金 权重 计算
                    $myBill = $value['dividerPeoplePv'][$v]['maxValue'] ?? 0;
                    //中级合伙人。userid=17可以分到双区可分红的金额
                    //可分红的佣金 * (中级合伙人个人的双区总业绩 / 当前等级所有合伙人的双联盟业绩) = 当前用户可以获取到的分红佣金(双区联盟总业绩加权佣金),287742 * (61.95/431032)=41.36
                    //                $myWeightMoney = round($amount * ($myBill / $maxValueAll), 2);
                    $myWeightMoney = floor(($amount * (floor((($myBill + $userPvSmallNum) / ($maxValueAll + $sumOfOthersAll)) * 100000) / 100000)) * 100) / 100;


                    $salesArr[$key]['dividerPeoplePv'][$v]['myWeightMoney'] = $myWeightMoney;
                    $salesArr[$key]['dividerPeoplePv'][$v]['myMixMoney'] = $myMixMoney;
                    $salesArr[$key]['dividerPeoplePv'][$v]['maxValueAll'] = $maxValueAll;
                    $salesArr[$key]['dividerPeoplePv'][$v]['sumOfOthersAll'] = $sumOfOthersAll;

                    # code...
                    $allAward = $myWeightMoney + $myMixMoney;

                    //90%给佣金，10给复购金
                    $yj_90 = floor($allAward * 0.9 * 100) / 100;
                    $fg_10 = floor($allAward * 0.1 * 100) / 100;

                    //                $yj_90 = bcsub($yj_90, $user_bill_uid_list[$v]['number'] ?? 0.00, 2);
                    //
                    //                $fg_10 = bcsub($fg_10, $user_sign_fugou_uid_list[$v]['number'] ?? 0.00, 2);
                    //
                    //                if ($yj_90 < 0) {
                    //                    $testRecord['yj_fushu'][] = ['uid' => $v, 'num' => floor($allAward * 0.9 * 100) / 100, 'exist' => $user_bill_uid_list[$v]['number'] ?? 0.00, 'yj' => $yj_90];
                    //                }
                    //                if ($fg_10 < 0) {
                    //                    $testRecord['fg_fushu'][] = ['uid' => $v, 'num' => floor($allAward * 0.1 * 100) / 100, 'exist' => $user_sign_fugou_uid_list[$v]['number'] ?? 0.00, 'fg' => $fg_10];
                    //                }

                    if ($isTest == 0) {
                        $userdatassss = db::name("old_user_jbp")->where("id", $v)->find();
                        $datas_log = [
                            'note' => "名称:" . $userdatassss['nick_name'] . " 用户:" . $v . " 双联盟总业绩:" . $maxValueAll . " 我的双区业绩:" . $myBill . " 小区总业绩:" . $userPvSmallNum . " 我的业绩小的:" . $myMixMoney . "  可分红佣金:" . $amount . "  可分红总佣金:" . $fsMoneyNums . "  小区业绩可分红:" . $myMixMoney . " 双区业绩可分红:" . $myWeightMoney . " 实际分得:" . $yj_90,
                            'create_time' => date('Y-m-d H:i:s')
                        ];
                        $con_data = Db::name('test_log')->insert($datas_log);   //数据存到2.0数据表中

                        # code...
                        $res = Db::name("user")->where("uid", $v)->inc("total_amount_old", $yj_90)->save();

                        Db::name("user")->where("uid", $v)->inc("amount_old", $yj_90)->save();//不用冻结金额和提现额度来限制佣金发放
                        Db::name("user")->where("uid", $v)->inc("brokerage_price", $yj_90)->save();

                        Db::name("user")->where("uid", $v)->inc("fugou", $fg_10)->save();


                        //if($res) {
                        $this->change_user_log($v, 'amount_old', 1, $yj_90, "member_award", "星级分红入账" . "-" . $value['title']);//释放佣金
                        // //入账星级分红记录表
                        // $week_data = [];
                        // $week_data['user_id'] = $v;
                        // $week_data['user_star_id'] = $value['id'];
                        // $week_data['award_num'] = $myWeightMoney;
                        // $week_data['award_num_sm'] = $myMixMoney;
                        // $week_data['remark'] = "星级分红主动执行:" . $yj_90;
                        // $week_data['week_record'] = $weekRecord;
                        // $week_data['all_amount'] = $fsMoneyNums;
                        // $week_data['radio'] = 2;
                        // $week_data['owner_bill'] = $maxValueAll;  //总流水金额
                        // $week_data['my_bill'] = $myBill;  //我的流水
                        // $week_data['create_time'] = time();
                        // Db::name("old_user_weekaward")->insert($week_data);

                        // 入账记录
                        $week_data = [];
                        $week_data['user_id'] = $v;
                        $week_data['user_group'] = $value['user_group'];
                        $week_data['start_time'] = $startTime;
                        $week_data['end_time'] = $endTime;
                        $week_data['performance'] = $performance;
                        $week_data['red_envelope'] = $redEnvelope;
                        $week_data['reality_performance'] = $weekRecord;
                        $week_data['dividend_ratio'] = $value['profit_rate'];
                        $week_data['dividend'] = $fsMoneyNums;
                        $week_data['performance_part'] = $userPvSmallNum;
                        $week_data['performance_part_all'] = $sumOfOthersAll;
                        $week_data['part_money'] = $myMixMoney;
                        $week_data['performance_total'] = ($myBill + $userPvSmallNum);
                        $week_data['performance_total_all'] = ($maxValueAll + $sumOfOthersAll);
                        $week_data['total_money'] = $myWeightMoney;
                        $week_data['brokerage'] = $yj_90;
                        $week_data['fugou'] = $fg_10;
                        $week_data['radio'] = 2;
                        $week_data['create_time'] = date('Y-m-d H:i:s');
                        Db::name("partner_profit_records")->insert($week_data);

                        $this->bill_user_log111111($v, "合伙人分佣", $yj_90, "合伙人分佣明细入账", 11);//联创分佣明细2.0系统
                        $this->fugou_user_log($v, $fg_10, 16, 1, 1);//复购金明细入账
                    }
                }
                $salesArr['cs'] = $testRecord;
            }
            $result[$uid] = $salesArr;

        }
        return json($result);
    }

    /**
     * 获取该会员的所有下级会员
     */
    public function getSpreadUserUidListByUidList(array $uidList)
    {
        $son_ids = Db::name("user")
            ->whereIn("level_id", $uidList)
            ->field("uid,level_id")
            ->select()
            ->toArray();
        $new_array_ids = [];
        foreach ($son_ids as $key => $value) {
            $new_array_ids[$value['level_id']][] = $value['uid'];
        }
        return $new_array_ids;
    }

    /**
     * 递归查询下级用户并分组
     *
     * @param array $uids 初始用户ID数组
     * @return array 分组后的下级用户ID数组
     */
    public function getSubordinates(array $uids): array
    {
        $result = [];

        foreach ($uids as $uid) {
            $result[$uid] = $this->getSubordinatesRecursively($uid);
        }

        return $result;
    }

    /**
     * 获取该会员的所有下级会员
     */
    public function getSpreadUserUidAccountListByUidList($uid, $account = '')
    {
        $son_ids = Db::name("user")
            ->where("level_id", $uid)
            ->field("uid,level_id,account")
            ->select()
            ->toArray();
        $new_array_ids = [];
        foreach ($son_ids as $key => $value) {
            $childList = $this->getSpreadUserUidAccountListByUidList($value['uid'], $value['account']);
            $new_array_ids[] = [
                '当前用户ID' => $value['uid'],
                '当前用户的上级用户ID' => $value['level_id'],
                '用户账号（手机号）' => $value['account'],
                '当前用户的下级用户列表' => $childList
            ];
        }
        return $new_array_ids;
    }

    /**
     * 递归查询单个用户的下级用户
     *
     * @param int $uid 用户ID
     * @param array $subordinates 用于存储下级用户ID的数组(内部使用, 递归传递)
     * @return array 下级用户ID数组
     */
    private function getSubordinatesRecursively(int $uid, array &$subordinates = []): array
    {
        $subUidList = Db::name("user")
            ->where("level_id", $uid)  // 直接使用 $uid, 不需要 whereIn
            ->field("uid") //只需要查询uid
            ->select()
            ->toArray();

        if (!empty($subUidList)) {
            foreach ($subUidList as $subUser) {
                $subUid = $subUser['uid'];
                $subordinates[] = $subUid; // 添加到下级用户数组
                $this->getSubordinatesRecursively($subUid, $subordinates); // 递归查询下级的下级
            }
        }
        return $subordinates;
    }

    /**
     * 递归获取所有下级ID（不分组）
     * @param int $uid
     * @param array $allSubordinates
     * @return array
     */
    public function getAllSubordinates(int $uid, array &$allSubordinates = []): array
    {
        $subUidList = Db::name("user")
            ->where("level_id", $uid)
            ->column("uid");  // 使用 column 方法直接获取 uid 数组

        if (!empty($subUidList)) {
            foreach ($subUidList as $subUid) {
                $allSubordinates[] = $subUid;
                $this->getAllSubordinates($subUid, $allSubordinates);
            }
        }

        return $allSubordinates;
    }

    /**
     *  更高效的获取所有下级 (使用循环代替递归, 避免栈溢出)
     * @param array $uids
     * @return array
     */
    public function getAllSubordinatesIterative(array $uids): array
    {
        $result = [];

        foreach ($uids as $uid) {
            $result[$uid] = [];
            $queue = [$uid];  // 使用队列来存储待处理的 UID
            $processed = []; // 记录已经处理过的

            while (!empty($queue)) {
                $currentUid = array_shift($queue); // 从队列头部取出 UID
                if (in_array($currentUid, $processed)) {
                    continue; // 已经处理过
                }
                $processed[] = $currentUid;
                $subUidList = Db::name("user")
                    ->where("level_id", $currentUid)
                    ->column("uid");

                if (!empty($subUidList)) {
                    $result[$uid] = array_merge($result[$uid], $subUidList); //合并
                    $queue = array_merge($queue, $subUidList);  // 将新找到的下级 UID 加入队列尾部
                }
            }
            $result[$uid] = array_unique($result[$uid]);//去重
        }
        return $result;
    }

    /**
     * 获取多个用户的所有下级,  返回分组后的数组.  (更高效, 使用循环, 减少数据库查询次数)
     * @param array $uids
     * @return array 形如 ['A1' => [A11, A12, ...], 'A2' => [...]]
     */
    public function getSubordinatesBatch(array $uids): array
    {
        $result = [];
        $allSubordinates = [];
        $queue = $uids;
        $processed = [];
        //1. 找出所有的下级ID (不去重)
        while (!empty($queue)) {
            $currentUids = array_splice($queue, 0, 500); // 一次最多处理500个,防止in太多.  可以根据实际情况调整.
            $currentUids = array_diff($currentUids, $processed); //去除已经查询过的
            if (empty($currentUids)) continue;  //没有新的需要处理的
            $processed = array_merge($processed, $currentUids);//记录
            $subUidList = Db::name("user")
                ->whereIn("level_id", $currentUids)
                ->field("uid,level_id") // 需要查询 level_id 用于后续分组
                ->select()
                ->toArray();

            if (!empty($subUidList)) {
                $allSubordinates = array_merge($allSubordinates, $subUidList); //所有下级
                $nextLevelUids = array_column($subUidList, 'uid');
                $queue = array_merge($queue, $nextLevelUids);  //放到队列中
            }
        }
        //2. 分组
        foreach ($uids as $uid) {
            $result[$uid] = []; // 初始化每个用户的下级数组
        }
        $allSubordinatesMap = [];
        foreach ($allSubordinates as $item) {
            $allSubordinatesMap[$item['level_id']][] = $item['uid'];
        }

        //3. 递归的将查到的下级进行分组
        $group = function ($spreadUid) use (&$group, &$allSubordinatesMap, &$result) {
            if (isset($allSubordinatesMap[$spreadUid])) {
                foreach ($allSubordinatesMap[$spreadUid] as $subUid) {
                    if (isset($result[$spreadUid])) {
                        $result[$spreadUid][] = $subUid; //直接添加到结果中
                    } else { //不属于直接上级, 查找上级的上级
                        foreach ($result as $rootUid => &$subordinates) {
                            if (in_array($spreadUid, $subordinates) || $rootUid == $spreadUid) {
                                $subordinates[] = $subUid;
                                break;
                            }
                        }
                    }
                    $group($subUid); //递归下一层
                }
            }
        };
        foreach ($uids as $uid) {
            $group($uid);
        }

        // 4. 去重 (如果需要)
        foreach ($result as $key => $value) {
            $result[$key] = array_values(array_unique($value));
        }
        return $result;
    }

    // 获取用户PV值
    public function getPv($userIdList, $removeUserIdList = [])
    {
        if (!empty($removeUserIdList)) {
            $userIdList = array_values(array_diff($userIdList, $removeUserIdList));
        }
        // 基础查询构建器
        $user_team_amount = Db::name("old_user_of_goods")
            ->whereIn("user_id", $userIdList)
            ->where('status', 1)
            ->where('money', 1180)
            ->select();
        //$money1180Records = $this->old_user_of_goods->where('status', 1)->where('money', 1180)->select();
        // 计算 status 为 1 且 money 为 1180 的记录总和（减去相应值后）
        $money1180Sum = 0;
        foreach ($user_team_amount as $record) {
            $money1180Sum += $record['money'] - 300 - 180;
        }

        // 获取 status 为 1 且 money 为 11800 的记录集合
        $money11800Records = Db::name("old_user_of_goods")
            ->whereIn("user_id", $userIdList)
            ->where('status', 1)
            ->where('money', 11800)
            ->select();
        // 计算 status 为 1 且 money 为 11800 的记录总和（减去相应值后）
        $money11800Sum = 0;
        foreach ($money11800Records as $record) {
            $money11800Sum += $record['money'] - 3000 - 1800;
        }

        $money10620Records = Db::name("old_user_of_goods")
            ->whereIn("user_id", $userIdList)
            ->where('status', 1)
            ->where('money', 10620)
            ->select();
        // 计算 status 为 1 且 money 为 10620 的记录总和（减去相应值后）
        $money10620Sum = 0;
        foreach ($money10620Records as $record) {
            $money10620Sum += $record['money'] - 2700 - 1620;
        }


        $money9440Records = Db::name("old_user_of_goods")
            ->whereIn("user_id", $userIdList)
            ->where('status', 1)
            ->where('money', 9440)
            ->select();
        // 计算 status 为 1 且 money 为 9440 的记录总和（减去相应值后）
        $money9440Sum = 0;
        foreach ($money9440Records as $record) {
            $money9440Sum += $record['money'] - 2400 - 1440;
        }

        $money2360Records = Db::name("old_user_of_goods")
            ->whereIn("user_id", $userIdList)
            ->where('status', 1)
            ->where('money', 2360)
            ->select();
        // 计算 status 为 1 且 money 为 2360 的记录总和（减去相应值后）
        $money2360Sum = 0;
        foreach ($money2360Records as $record) {
            $money2360Sum += $record['money'] - 600 - 360;
        }

        // 计算除去特定值后的总和
        $otherMoneyRecords = [];
        //        $otherMoneyRecords = Db::name("old_user_of_goods")
        //            ->whereIn("user_id", $userIdList)
        //            ->whereNotIn('money', [1180, 11800, 10620, 9440, 2360])
        //            ->select();
        $otherMoneySum = 0;
        foreach ($otherMoneyRecords as $record) {
            $otherMoneySum += $record['money'];
        }
        return $money1180Sum + $money11800Sum + $money10620Sum + $money9440Sum + $money2360Sum + (floor($otherMoneySum * 70) / 100);
    }

    // 获取用户PV值
    public function getPvNew($userIdList, $removeUserIdList = [])
    {
        if (!empty($removeUserIdList)) {
            $userIdList = array_values(array_diff($userIdList, $removeUserIdList));
        }
        $pvLogList = Db::name("user_pv_log")
            ->whereIn('uid', $userIdList)
            // ->whereIn('order_type', [0])
            ->where('status', '=', 1)
            // ->whereBetween("settlement_time", [$startTime, $endTime])
            // ->whereNotNull("settlement_time") // 排除 pay_time 为 NULL 的订单
            ->select()
            ->toArray();

        // 计算总业绩
        $totalPv = 0;
        foreach ($pvLogList as $pvLog) {
            $totalPv = bcadd($totalPv, $pvLog['pv'], 2);
        }

        return $totalPv;
    }

    //发放佣金 示例: $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);
    }

    //添加平台分佣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' => '',//结算时间
            'district_id' => '',//
            'street_id' => '',//
            'month' => '',//月份


        ];

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

    //添加复购金
    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);
    }
}