<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\DealerPlugin\model;

use think\Db;
use think\Page;
use think\Model;
use think\Config;

/**
 * 分销商模型
 */

load_trait('controller/Jump');
class DealerPluginModel extends Model
{
    use \traits\controller\Jump;

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        // 分销商申请
        $this->dealer = Db::name('weapp_dealer');
        // 分销商信息
        $this->dealerApply = Db::name('weapp_dealer_apply');
        // 分销商提现
        $this->dealerWithdraw = Db::name('weapp_dealer_withdraw');
        // 分销商佣金操作记录
        $this->dealerMoneyLog = Db::name('weapp_dealer_money_log');
        // 订单数据
        $this->shopOrder = Db::name('shop_order');
        $this->shopOrderDetails = Db::name('shop_order_details');
        // 分销商设置
        $this->dealerConfig = getUsersConfigData('dealer');
    }

    public function getDealerSummary()
    {
        // 查询分销商信息处理
        $dealerInfo = $this->dealerInfoHandle();

        // 查询分销订单，处理获取(待结算总佣金 and 已结算总佣金)
        $orderInfo = $this->getDealerOrderHandle();

        // 查询分销商提现订单，处理获取(提现待审核总佣金 and 提现待打款总佣金 and 已提现成功总佣金)
        $withdrawInfo = $this->getDealerWithdrawHandle();

        // 查询分销商可用总佣金
        $dealerAvailableMoney = $this->getDealerAvailableMoney();

        // 当天初始时间戳
        $todayTime = strtotime(date("Y-m-d"), time());
        $addDealer = $settledMoney = [];
        for ($i = 0; $i < 7; $i++) {
            $startTime = intval($todayTime) - (intval($i) * 86400);
            $endTime = intval($todayTime) - ((intval($i) - 1) * 86400);
            // 查询新增的分销商数
            $addDealer[$i] = $this->getAddDealerNum($startTime, $endTime);
            // 查询新增的分销商数
            $dealerOrder = $this->getDealerOrderHandle($startTime, $endTime);
            $settledMoney[$i] = !empty($dealerOrder['alreadySettledMoney']) ? floatval($dealerOrder['alreadySettledMoney']) : 0;
        }
        $addDealer = array_reverse($addDealer);
        $settledMoney = array_reverse($settledMoney);
        for ($i = 0; $i < 7; $i++) {
            if (empty($addDealer[$i])){
                $addDealer[$i] = 0;
            }
        }

        // 返回数据
        return [
            // 近七日新增分销商数
            'addDealer' => !empty($addDealer) ? $addDealer : [],
            // 近七日已结算的分销订单额
            'settledMoney' => !empty($settledMoney) ? $settledMoney : [],
            // 分销商信息处理，分销商待审核总数 and 分销商总数 and 一级分销商 and 二级分销商 and 分销商客户
            'dealerApply' => !empty($dealerInfo['dealerApply']) ? $dealerInfo['dealerApply'] : 0,
            'dealerTotal' => !empty($dealerInfo['dealerTotal']) ? $dealerInfo['dealerTotal'] : 0,
            'dealerOneLevel' => !empty($dealerInfo['dealerOneLevel']) ? $dealerInfo['dealerOneLevel'] : 0,
            'dealerTwoLevel' => !empty($dealerInfo['dealerTwoLevel']) ? $dealerInfo['dealerTwoLevel'] : 0,
            'dealerCustomer' => !empty($dealerInfo['dealerCustomer']) ? $dealerInfo['dealerCustomer'] : 0,
            // 分销商可用总佣金
            'dealerAvailableMoney' => !empty($dealerAvailableMoney) ? unifyPriceHandle($dealerAvailableMoney) : 0,
            // 分销订单，待结算总佣金 and 已结算总佣金
            'toBeSettledMoney' => !empty($orderInfo['toBeSettledMoney']) ? unifyPriceHandle($orderInfo['toBeSettledMoney']) : 0,
            'alreadySettledMoney' => !empty($orderInfo['alreadySettledMoney']) ? unifyPriceHandle($orderInfo['alreadySettledMoney']) : 0,
            // 提现信息，提现待审核总佣金 and 提现待打款总佣金 and 已提现成功总佣金
            'toBeReviewMoney' => !empty($withdrawInfo['toBeReviewMoney']) ? unifyPriceHandle($withdrawInfo['toBeReviewMoney']) : 0,
            'toBeHitPayMoney' => !empty($withdrawInfo['toBeHitPayMoney']) ? unifyPriceHandle($withdrawInfo['toBeHitPayMoney']) : 0,
            'alreadyDealerMoney' => !empty($withdrawInfo['alreadyDealerMoney']) ? unifyPriceHandle($withdrawInfo['alreadyDealerMoney']) : 0,
        ];
    }

    // 获取分销商列表数据
    public function getDealerIndexList()
    {
        // 查询条件
        $where = [
            // 仅读取用户分销商
            'a.system_dealer' => 0
        ];
        // 分销商姓名/手机号查询
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $where['a.dealer_name|a.dealer_mobile|b.nickname'] = array('LIKE', "%{$keywords}%");

        // 分销商状态查询
        $dealerStatus = input('dealer_status/d', 0);
        if (!empty($dealerStatus)) $where['a.dealer_status'] = intval($dealerStatus);

        // 分销商成为时间查询
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $where['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $where['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $where['a.add_time'] = array('elt', $end);
        }

        // 查询分销商列表数据
        $count = $this->dealer->alias('a')->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->count('dealer_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $field = 'a.*, b.username, b.nickname, b.mobile, b.users_money, b.head_pic, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
        $dealerList = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();
        
        // 查询下级(分销商/客户)信息
        $users_ids = array_unique(get_arr_column($dealerList, 'users_id'));
        $dealer_ids = array_unique(get_arr_column($dealerList, 'dealer_id'));
        $where = [
            'is_del' => 0,
            'is_lock' => 0,
            'parent_users_id' => ['IN', $users_ids],
            'parent_dealer_id' => ['IN', $dealer_ids]
        ];
        $field = 'users_id, is_dealer, parent_users_id, parent_dealer_id';
        $subUsers = Db::name('users')->field($field)->where($where)->select();
        $subUsers = !empty($subUsers) ? group_same_key($subUsers, 'parent_dealer_id') : [];
        $subData = [];
        if (!empty($subUsers)) {
            foreach ($subUsers as $key => $value) {
                $subDealerNum = $subUsersNum = 0;
                if (!empty($value)) {
                    foreach ($value as $value_1) {
                        if (!empty($value_1['is_dealer']) && 1 === intval($value_1['is_dealer'])) {
                            $subDealerNum++;
                        } else {
                            $subUsersNum++;
                        }
                    }
                }
                $subData[$key] = [
                    'subUsersNum' => $subUsersNum,
                    'subDealerNum' => $subDealerNum
                ];
            }
        }

        // 查询上级分销商信息
        $parentDealerID = array_filter(array_unique(get_arr_column($dealerList, 'parent_dealer_id')));
        $where = [
            // 'a.dealer_status' => 1,
            'a.dealer_id' => ['IN', $parentDealerID]
        ];
        $field = 'a.dealer_id, a.users_id, a.dealer_name, a.dealer_mobile, a.system_dealer, b.username, b.nickname';
        $parentDealer = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->getAllWithIndex('dealer_id');
        foreach ($parentDealer as $key => $value) {
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $parentDealer[$key] = $value;
        }

        // 分销商处理
        foreach ($dealerList as $key => $value) {
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            // 申请状态
            $value['status_name'] = 1 === intval($value['dealer_status']) ? '正常' : '冻结';
            // 下级客户数、下级分销商
            $value['subUsersNum'] = !empty($subData[$value['dealer_id']]['subUsersNum']) ? intval($subData[$value['dealer_id']]['subUsersNum']) : 0;
            $value['subDealerNum'] = !empty($subData[$value['dealer_id']]['subDealerNum']) ? intval($subData[$value['dealer_id']]['subDealerNum']) : 0;
            // 上级分销商(推荐人)
            $value['parentDealer'] = !empty($parentDealer[$value['parent_dealer_id']]) ? $parentDealer[$value['parent_dealer_id']] : [];
            // 累计获得佣金 (包含可用、冻结、已提现佣金)
            $value['dealer_total_money'] = unifyPriceHandle(floatval($value['dealer_money']) + floatval($value['freeze_money']) + floatval($value['withdraw_money']));
            $dealerList[$key] = $value;
        }

        $pageStr = $pageObj->show();
        $result = [
            'page' => $pageStr,
            'pager' => $pageObj,
            'dealerList' => $dealerList,
        ];

        return $result;
    }

    // 分销商状态处理
    public function dealerStatusHandle($post = [])
    {
        $where = [
            'dealer_id' => intval($post['dealer_id']),
        ];
        $update = [
            'dealer_status' => !empty($post['dealer_status']) ? intval($post['dealer_status']) : 0,
            'update_time' => getTime()
        ];
        return $this->dealer->where($where)->update($update);
    }

    // 获取分销商申请列表数据
    public function getDealerApplyList()
    {
        // 查询条件
        $where = [
            'a.review_status' => ['IN', [1, 3]]
        ];
        // 分销商姓名/手机号查询
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $where['a.dealer_name|a.dealer_mobile|b.nickname'] = array('LIKE', "%{$keywords}%");

        // 分销商审核状态查询
        $reviewStatus = input('review_status/d', 0);
        if (!empty($reviewStatus)) $where['a.review_status'] = intval($reviewStatus);

        // 分销商成为时间查询
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $where['a.apply_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $where['a.apply_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $where['a.apply_time'] = array('elt', $end);
        }

        // 查询入驻申请
        $count = $this->dealerApply->alias('a')->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->count('apply_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $field = 'a.*, b.username, b.nickname, b.mobile, b.users_money, b.head_pic, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
        $applyList = $this->dealerApply->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.apply_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();

        // 查询上级分销商信息
        $parentDealerID = array_filter(array_unique(get_arr_column($applyList, 'parent_dealer_id')));
        $where = [
            // 'a.dealer_status' => 1,
            'a.dealer_id' => ['IN', $parentDealerID]
        ];
        $field = 'a.dealer_id, a.users_id, a.dealer_name, a.dealer_mobile, b.username, b.nickname';
        $parentDealer = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->getAllWithIndex('dealer_id');
        foreach ($parentDealer as $key => $value) {
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $parentDealer[$key] = $value;
        }

        // 分销商申请处理
        foreach ($applyList as $key => $value) {
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            // 申请状态
            $value['status_name'] = '待审核';
            if (2 === intval($value['review_status'])) {
                $value['status_name'] = '通过';
            } else if (3 === intval($value['review_status'])) {
                $value['status_name'] = '拒接';
            }
            // 上级分销商
            $value['parentDealer'] = !empty($parentDealer[$value['parent_dealer_id']]) ? $parentDealer[$value['parent_dealer_id']] : [];
            $applyList[$key] = $value;
        }

        $pageStr = $pageObj->show();
        $result = [
            'page' => $pageStr,
            'pager' => $pageObj,
            'applyList' => $applyList,
        ];
        return $result;
    }

    // 审核分销商申请
    public function reviewDealerApply($post = [])
    {
        // 更新条件
        $where = [
            'apply_id' => intval($post['apply_id']),
        ];
        // 查询申请分销商的信息
        $findApply = $this->dealerApply->where($where)->find();
        if (empty($findApply)) return false;

        // 更新信息
        $times = getTime();
        $update = [
            'review_status' => intval($post['review_status']),
            'review_reason' => strval($post['review_reason']),
            'review_time' => $times,
            'update_time' => $times,
        ];
        // 执行更新
        $resultID = $this->dealerApply->where($where)->update($update);

        // 申请通过
        if (!empty($resultID) && 2 === intval($post['review_status'])) {
            // 添加分销商信息
            $insert = [
                'users_id' => !empty($findApply['users_id']) ? intval($findApply['users_id']) : 0,
                'dealer_name' => !empty($findApply['dealer_name']) ? strval($findApply['dealer_name']) : 0,
                'dealer_mobile' => !empty($findApply['dealer_mobile']) ? strval($findApply['dealer_mobile']) : 0,
                'add_time' => $times,
                'update_time' => $times,
            ];
            $dealerID = $this->dealer->insertGetId($insert);

            // 存在推荐人执行
            if (!empty($dealerID)) {
                // 更新会员为分销商
                $where = [
                    'users_id' => intval($findApply['users_id'])
                ];
                $update = [
                    'is_dealer' => 1,
                    'update_time' => getTime(),
                ];
                if (1 === intval($this->dealerConfig['dealer_level'])) {
                    // 如果是一级分销商模式则清空当前会员的上级和顶级分销商ID
                    $update['top_users_id'] = 0;
                    $update['top_dealer_id'] = 0;
                    $update['parent_users_id'] = 0;
                    $update['parent_dealer_id'] = 0;
                }
                Db::name('users')->where($where)->update($update);

                return true;
            }
            // 操作失败
            else {
                return false;
            }
        }
        // 申请拒绝
        else if (!empty($resultID) && 3 === intval($post['review_status'])) {
            return true;
        }
    }

    // 获取分销商列表数据
    public function getDealerSubordinateList($users_id = 0)
    {
        // 查询条件
        $where = [
            'b.is_dealer' => 1,
            'b.parent_users_id' => $users_id,
        ];

        // 分销商姓名/手机号查询
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $where['a.dealer_name|a.dealer_mobile'] = array('LIKE', "%{$keywords}%");

        // 分销商状态查询
        $dealerStatus = input('dealer_status/d', 0);
        if (!empty($dealerStatus)) $where['a.dealer_status'] = intval($dealerStatus);

        // 分销商成为时间查询
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $where['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $where['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $where['a.add_time'] = array('elt', $end);
        }

        // 查询分销商的下级分销商信息
        $count = $this->dealer->alias('a')->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->count('dealer_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $field = 'a.*, b.username, b.nickname, b.mobile, b.users_money, b.head_pic, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
        $dealerList = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();

        // 查询上级分销商信息
        $users_ids = array_unique(get_arr_column($dealerList, 'users_id'));
        $dealer_ids = array_unique(get_arr_column($dealerList, 'dealer_id'));
        $where = [
            'is_del' => 0,
            'is_lock' => 0,
            'parent_users_id' => ['IN', $users_ids],
            'parent_dealer_id' => ['IN', $dealer_ids]
        ];
        $field = 'users_id, is_dealer, parent_users_id, parent_dealer_id';
        $subUsers = Db::name('users')->field($field)->where($where)->select();
        $subUsers = !empty($subUsers) ? group_same_key($subUsers, 'parent_dealer_id') : [];
        $subData = [];
        if (!empty($subUsers)) {
            foreach ($subUsers as $key => $value) {
                $subDealerNum = $subUsersNum = 0;
                if (!empty($value)) {
                    foreach ($value as $value_1) {
                        if (!empty($value_1['is_dealer']) && 1 === intval($value_1['is_dealer'])) {
                            $subDealerNum++;
                        } else {
                            $subUsersNum++;
                        }
                    }
                }
                $subData[$key] = [
                    'subUsersNum' => $subUsersNum,
                    'subDealerNum' => $subDealerNum
                ];
            }
        }

        // 查询上级分销商信息
        $parentDealerID = array_filter(array_unique(get_arr_column($dealerList, 'parent_dealer_id')));
        $where = [
            // 'a.dealer_status' => 1,
            'a.dealer_id' => ['IN', $parentDealerID]
        ];
        $field = 'a.dealer_id, a.users_id, a.dealer_name, a.dealer_mobile, b.username, b.nickname';
        $parentDealer = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->getAllWithIndex('dealer_id');
        foreach ($parentDealer as $key => $value) {
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $parentDealer[$key] = $value;
        }

        // 分销商处理
        foreach ($dealerList as $key => $value) {
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            // 申请状态
            $value['status_name'] = 1 === intval($value['dealer_status']) ? '正常' : '冻结';
            // 下级客户数、下级分销商
            $value['subUsersNum'] = !empty($subData[$value['dealer_id']]['subUsersNum']) ? intval($subData[$value['dealer_id']]['subUsersNum']) : 0;
            $value['subDealerNum'] = !empty($subData[$value['dealer_id']]['subDealerNum']) ? intval($subData[$value['dealer_id']]['subDealerNum']) : 0;
            // 上级分销商(推荐人)
            $value['parentDealer'] = !empty($parentDealer[$value['parent_dealer_id']]) ? $parentDealer[$value['parent_dealer_id']] : [];
            // 累计获得佣金 (包含可用、冻结、已提现佣金)
            $value['dealer_total_money'] = unifyPriceHandle(floatval($value['dealer_money']) + floatval($value['freeze_money']) + floatval($value['withdraw_money']));
            $dealerList[$key] = $value;
        }

        $pageStr = $pageObj->show();
        $result = [
            'page' => $pageStr,
            'pager' => $pageObj,
            'dealerList' => $dealerList,
        ];
        return $result;
    }

    // 获取分销商客户列表数据
    public function getDealerCustomerList($users_id = 0)
    {
        $where = [
            'users_id' => $users_id,
        ];
        $dealer = $this->dealer->where($where)->find();
        $parent_users_id = isset($dealer['users_id']) ? intval($dealer['users_id']) : 0;
        $parent_dealer_id = isset($dealer['dealer_id']) ? intval($dealer['dealer_id']) : 0;
        $where = [
            'is_dealer' => 0,
            'parent_users_id' => $parent_users_id,
            'parent_dealer_id' => $parent_dealer_id,
        ];

        // 可搜索昵称/用户名/手机号
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $where['nickname|username|mobile'] = array('LIKE', "%{$keywords}%");

        // 首次绑定时间
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $where['bind_dealer_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $where['bind_dealer_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $where['bind_dealer_time'] = array('elt', $end);
        }

        // 查询分销商客户
        $count = Db::name('users')->where($where)->count('users_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $customer = Db::name('users')->where($where)->limit($pageObj->firstRow.','.$pageObj->listRows)->order('users_id desc')->select();

        // 查询客户的订单数
        $users_ids = get_arr_column($customer, 'users_id');
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 1,
            'users_id' => ['IN', $users_ids]
        ];
        $field = 'users_id, count(order_id) as order_num';
        $orderNum = Db::name('shop_order')->field($field)->group('users_id')->where($where)->getAllWithIndex('users_id');

        // 查询客户最后一次购买时间
        $where = [
            'dealer_order' => 1,
            'users_id' => ['IN', $users_ids],
            'order_status' => ['IN', [0, 1, 2, 3]],
        ];
        $field = 'order_id, users_id, max(add_time) as add_time';
        $lastOrderTime = Db::name('shop_order')->field($field)->where($where)->group('order_id')->getAllWithIndex('users_id');

        // 查询这个用户给上级分销商获利多少总佣金
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 1,
            'users_id' => ['IN', $users_ids]
        ];
        $field = 'order_id, users_id';
        $shopOrder = Db::name('shop_order')->field($field)->where($where)->select();
        $order_ids = !empty($shopOrder) ? get_arr_column($shopOrder, 'order_id') : [];
        // 查询佣金记录
        $where = [
            'log_type' => 1,
            'order_id' => ['IN', $order_ids],
            'users_id' => $parent_users_id,
            'dealer_id' => $parent_dealer_id,
        ];
        $field = 'order_id, log_action_money';
        $dealerMoneyLog = $this->dealerMoneyLog->field($field)->where($where)->getAllWithIndex('order_id');
        foreach ($shopOrder as $key => $value) {
            $logActionMoney = 0;
            if (!empty($dealerMoneyLog[$value['order_id']]['log_action_money'])) {
                $logActionMoney = floatval($dealerMoneyLog[$value['order_id']]['log_action_money']);
            }
            $shopOrder[$key]['dealer_total_money'] = !empty($logActionMoney) ? floatval($logActionMoney) : 0;
        }
        $shopOrder = !empty($shopOrder) ? group_same_key($shopOrder, 'users_id') : [];

        // 查询上级分销商信息
        $parent_users_id = array_filter(array_unique(get_arr_column($customer, 'parent_users_id')));
        $parent_dealer_id = array_filter(array_unique(get_arr_column($customer, 'parent_dealer_id')));
        $where = [
            // 'a.dealer_status' => 1,
            'a.users_id' => ['IN', $parent_users_id],
            'a.dealer_id' => ['IN', $parent_dealer_id]
        ];
        $field = 'a.*, b.username, b.nickname, b.mobile, b.users_money, b.head_pic, b.is_dealer, b.parent_users_id, b.parent_dealer_id, b.top_users_id, b.top_dealer_id, b.bind_dealer_time';
        $parentDealer = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->getAllWithIndex('users_id');
        foreach ($parentDealer as $key => $value) {
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $parentDealer[$key] = $value;
        }

        // 数据处理
        foreach ($customer as $key => $value) {
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            $value['nickname'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['bind_dealer_time'] = !empty($value['bind_dealer_time']) ? date('Y-m-d H:i:s', $value['bind_dealer_time']) : '';
            $value['parentDealer'] = !empty($parentDealer[$value['parent_users_id']]) ? $parentDealer[$value['parent_users_id']] : [];
            $value['order_num'] = !empty($orderNum[$value['users_id']]['order_num']) ? intval($orderNum[$value['users_id']]['order_num']) : 0;
            $value['last_order_time'] = !empty($lastOrderTime[$value['users_id']]['add_time']) ? intval($lastOrderTime[$value['users_id']]['add_time']) : 0;
            $value['last_order_time'] = !empty($value['last_order_time']) ? date('Y-m-d H:i:s', $value['last_order_time']) : '尚未下单';
            $value['dealer_total_money'] = !empty($shopOrder[$value['users_id']]) ? unifyPriceHandle(array_sum(get_arr_column($shopOrder[$value['users_id']], 'dealer_total_money'))) : 0;
            $customer[$key] = $value;
        }

        $pageStr = $pageObj->show();
        $result = [
            'page' => $pageStr,
            'pager' => $pageObj,
            'customer' => $customer,
        ];
        return $result;
    }

    public function getDealerOrderList($dealer_id = 0)
    {
        // 初始化数组和条件
        $where = [
            'a.dealer_order' => 1,
        ];
        // 查询指定分销商 and 关联下级分销商 and 关联客户 的订单
        if (!empty($dealer_id)) {
            $dealer_users_ids = [];
            $dealer_users_id = $this->dealer->where(['dealer_id'=>$dealer_id])->getField('users_id');
            if (!empty($dealer_users_id)) {
                $dealer_users_ids = Db::name('users')->where(['users_id|parent_users_id|top_users_id'=>$dealer_users_id])->column('users_id');
            }
            if (!empty($dealer_users_ids)) $where['a.dealer_users_id'] = ['IN', $dealer_users_ids];
        }

        // 订单号查询
        $order_code = input('order_code/s');
        if (!empty($order_code)) $where['a.order_code'] = ['LIKE', "%{$order_code}%"];

        // 下单时间查询
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $where['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $where['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $where['a.add_time'] = array('elt', $end);
        }

        // 订单状态查询
        $handle_rebate = input('handle_rebate/d', 0);
        if (!empty($handle_rebate)) $where['a.handle_rebate'] = (9 === intval($handle_rebate)) ? 0 : $handle_rebate;

        // 分页查询
        $count = $this->shopOrder->alias('a')->where($where)->count('order_id');
        $pageObj = new Page($count, config('paginate.list_rows'));

        // 订单主表数据查询
        $field = 'a.*, b.username as u_username, b.nickname as u_nickname, b.mobile as u_mobile, b.head_pic as u_head_pic, c.dealer_name as parent_dealer_name, d.dealer_name as top_dealer_name, e.dealer_name as e_top_dealer_name';
        $list = $this->shopOrder->alias('a')
            ->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->join('__WEAPP_DEALER__ c', 'a.dealer_users_id = c.users_id && a.dealer_id = c.dealer_id', 'LEFT')
            ->join('__WEAPP_DEALER__ d', 'b.parent_users_id = d.users_id && b.parent_dealer_id = d.dealer_id', 'LEFT')
            ->join('__WEAPP_DEALER__ e', 'b.top_users_id = e.users_id && b.top_dealer_id = e.dealer_id', 'LEFT')
            ->order('a.order_id desc')
            ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
            ->select();
        // dump($list);exit;
        if (empty($list) && !empty($order_code)) {
            // 通过商品名称查询订单号
            $where_1['product_name'] = ['LIKE', "%{$order_code}%"];
            $order_ids = $this->shopOrderDetails->where($where_1)->group('order_id')->column('order_id');
            // 重新查询订单主表
            unset($where['a.order_code']);
            $where['a.order_id'] = ['IN', $order_ids];
            // 分页查询
            $count = $this->shopOrder->alias('a')->where($where)->count('order_id');
            $pageObj = new Page($count, config('paginate.list_rows'));
            // 订单主表数据查询
            $list = $this->shopOrder->alias('a')
                ->field($field)
                ->where($where)
                ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
                ->join('__WEAPP_DEALER__ c', 'a.dealer_users_id = c.users_id && a.dealer_id = c.dealer_id', 'LEFT')
                ->join('__WEAPP_DEALER__ d', 'b.parent_users_id = d.users_id && b.parent_dealer_id = d.dealer_id', 'LEFT')
                ->join('__WEAPP_DEALER__ e', 'b.top_users_id = e.users_id && b.top_dealer_id = e.dealer_id', 'LEFT')
                ->order('a.order_id desc')
                ->limit($pageObj->firstRow . ',' . $pageObj->listRows)
                ->select();
        }

        // 处理订单详情数据
        $where = [
            'a.order_id' => ['IN', get_arr_column($list, 'order_id')]
        ];
        $detailsData = $this->shopOrderDetails->alias('a')
            ->field('a.*, b.service_id, b.status')
            ->where($where)
            ->join('__SHOP_ORDER_SERVICE__ b', 'a.details_id = b.details_id', 'LEFT')
            ->order('details_id asc')
            ->select();
        $archivesData = get_archives_data($detailsData, 'product_id');
        foreach ($detailsData as $key => $value) {
            // 商品链接
            $value['arcurl'] = get_arcurl($archivesData[$value['product_id']]);
            // 商品图片处理
            $value['litpic'] = handle_subdir_pic(get_default_pic($value['litpic']));
            // 售后信息处理
            $value['service_id'] = !empty($value['service_id']) ? $value['service_id'] : 0;
            $value['status'] = !empty($value['status']) ? $value['status'] : 0;
            $value['status_name'] = !empty($value['status']) && in_array($value['status'], [6, 7]) ? '维权完成' : '维权中';
            // 产品属性处理
            $productSpec = !empty($value['data']) ? unserialize($value['data']) : [];
            $productSpec = htmlspecialchars_decode(htmlspecialchars_decode($productSpec['spec_value']));
            // 组合数据
            $productSpec = explode('<br/>', $productSpec);
            $valueData = '';
            foreach ($productSpec as $key_1 => $value_1) {
                if (!empty($value_1)) $valueData .= '<span>' . trim(strrchr($value_1, '：'),'：') . '</span>';
            }
            $value['product_spec'] = $valueData;
            $detailsData[$key] = $value;
        }

        // 把订单详情数据植入订单数据
        $defaultDetails = [
            'details_id' => 0,
            'order_id' => 0,
            'users_id' => 0,
            'product_id' => 0,
            'product_name' => '',
            'num' => 0,
            'data' => '',
            'product_price' => 0,
            'prom_type' => 0,
            'litpic' => get_default_pic(),
            'apply_service' => 0,
            'is_comment' => 0,
            'add_time' => 0,
            'update_time' => 0,
            'service_id' => 0,
            'status' => 0,
            'status_name' => '',
            'arcurl' => '',
        ];
        // 把订单详情数据植入订单数据
        $detailsDataGroup = group_same_key($detailsData, 'order_id');
        $adminOrderStatusArr = Config::get('global.admin_order_status_arr');
        foreach ($list as $key => $value) {
            // 处理会员昵称
            $value['u_nickname'] = !empty($value['u_nickname']) ? $value['u_nickname'] : $value['u_username'];
            // 处理订单详情数据
            $value['Details'] = !empty($detailsDataGroup[$value['order_id']]) ? $detailsDataGroup[$value['order_id']] : [$defaultDetails];
            // 商品条数
            $value['rowspan'] = count($value['Details']);
            // 添加时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            // 更新时间
            $value['update_time'] = date('Y-m-d H:i:s', $value['update_time']);
            // 处理订单主表的地址数据处理，显示中文名字
            $value['country'] = '中国';
            $value['province'] = get_province_name($value['province']);
            $value['city'] = get_city_name($value['city']);
            $value['district'] = get_area_name($value['district']);
            $value['all_address'] = "{$value['province']}-{$value['city']}-{$value['district']}-{$value['address']}";

            // 顶级分销商名称处理
            if (!empty($value['e_top_dealer_name'])) {
                $value['top_dealer_name'] = $value['e_top_dealer_name'];
                unset($value['e_top_dealer_name']);
            }
            // 计算分销佣金信息
            $dealerTotalAmount = 0;
            $dealerRebate = !empty($value['dealer_rebate']) ? intval($value['dealer_rebate']) : 0;
            $oneLevelRebate = !empty($value['one_level_rebate']) ? intval($value['one_level_rebate']) / 100 : 0;
            $twoLevelRebate = !empty($value['two_level_rebate']) ? intval($value['two_level_rebate']) / 100 : 0;
            // 使用 订单商品合计总额 进行计算分佣
            if (!empty($dealerRebate) && 1 === intval($dealerRebate)) {
                $dealerTotalAmount = unifyPriceHandle($value['order_total_amount']);
            }
            // 使用 订单实际支付总额 进行计算分佣
            else if (!empty($dealerRebate) && 2 === intval($dealerRebate)) {
                $dealerTotalAmount = unifyPriceHandle($value['order_amount']);
                // 存在运费则扣除运费，运费不在分销佣金计算中
                if (!empty($value['shipping_fee'])) {
                    $dealerTotalAmount = unifyPriceHandle(floatval($dealerTotalAmount) - floatval($value['shipping_fee']));
                }
            }
            $value['dealer_total_amount'] = !empty($dealerTotalAmount) ? unifyPriceHandle($dealerTotalAmount) : 0;
            // 一级分销佣金
            if (!empty($oneLevelRebate) && !empty($dealerTotalAmount)) {
                // 计算一级返佣比例
                $value['order_one_rebate'] = unifyPriceHandle(floatval($oneLevelRebate) * floatval($dealerTotalAmount));
            }
            // 二级分销佣金
            if (!empty($twoLevelRebate) && !empty($dealerTotalAmount)) {
                // 计算一级返佣比例
                $value['order_two_rebate'] = unifyPriceHandle(floatval($twoLevelRebate) * floatval($dealerTotalAmount));
            }

            // 订单状态
            $value['order_status_text'] = !empty($adminOrderStatusArr[$value['order_status']]) ? $adminOrderStatusArr[$value['order_status']] : '';

            // 重新赋值数据
            $list[$key] = $value;
        }

        $pageStr = $pageObj->show();
        $result = [
            'list' => $list,
            'page' => $pageStr,
            'pager' => $pageObj,
        ];
        return $result;
    }

    // 获取分销商提现列表数据
    public function getDealerWithdraw()
    {
        // 查询条件
        $where = [];

        // 分销商姓名/手机号查询
        $keywords = input('keywords/s', '');
        if (!empty($keywords)) $where['b.dealer_name|b.dealer_mobile'] = array('LIKE', "%{$keywords}%");

        $dealer_id = input('dealer_id/d', 0);
        if (!empty($dealer_id)) $where['a.dealer_id'] = intval($dealer_id);

        // 分销商审核状态查询
        $reviewStatus = input('review_status/d', 0);
        if (!empty($reviewStatus)) $where['a.review_status'] = intval($reviewStatus);

        // 分销商提现申请时间
        $begin = strtotime(input('param.add_time_begin/s'));
        $end = input('param.add_time_end/s');
        !empty($end) && $end .= ' 23:59:59';
        $end = strtotime($end);
        // 时间检索
        if ($begin > 0 && $end > 0) {
            $where['a.add_time'] = array('between', "$begin, $end");
        } else if ($begin > 0) {
            $where['a.add_time'] = array('egt', $begin);
        } else if ($end > 0) {
            $where['a.add_time'] = array('elt', $end);
        }

        // 查询入驻申请
        $count = $this->dealerWithdraw->alias('a')->join('__WEAPP_DEALER__ b', 'a.users_id = b.users_id', 'LEFT')->where($where)->count('withdraw_id');
        $pageObj = new Page($count, config('paginate.list_rows'));
        $withdrawList = $this->dealerWithdraw->field('a.*, b.dealer_name, b.dealer_mobile, c.username, c.nickname, c.head_pic')
            ->where($where)
            ->alias('a')
            ->join('__WEAPP_DEALER__ b', 'a.users_id = b.users_id', 'LEFT')
            ->join('__USERS__ c', 'a.users_id = c.users_id', 'LEFT')
            ->order('a.withdraw_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();
        foreach ($withdrawList as &$value) {
            $value['head_pic'] = get_default_pic($value['head_pic'], true);
            // 审核状态
            $value['review_status_name'] = '待审核';
            if (2 == $value['review_status']) {
                $value['review_status_name'] = '待打款';
            } else if (3 == $value['review_status']) {
                $value['review_status_name'] = '已拒绝';
            } else if (4 == $value['review_status']) {
                $value['review_status_name'] = '已打款';
            }

            // 提现通道
            $value['withdraw_type_name'] = 1 === intval($value['withdraw_type']) ? '会员余额' : '微信余额';

            // 审核时间处理
            $value['review_time'] = !empty($value['review_time']) ? $value['review_time'] : '';
        }

        $pageStr = $pageObj->show();
        $result = [
            'page' => $pageStr,
            'pager' => $pageObj,
            'dealer_id' => $dealer_id,
            'withdrawList' => $withdrawList,
        ];
        return $result;
    }

    // 分销商提现审核
    public function reviewDealerWithdraw($post = [])
    {
        // 基础判断
        if (empty($post['withdraw_id'])) $this->error('请选择提现申请');
        if (empty($post['review_status'])) $this->error('请选择审核建议');
        if (empty($post['review_reason']) && 3 === intval($post['review_status'])) $this->error('请填写拒绝原因');

        $times = getTime();
        // 执行条件
        $where = [
            'withdraw_id' => $post['withdraw_id']
        ];
        // 更新信息
        $update = [
            'update_time' => $times,
            'review_time' => $times,
            'review_status' => !empty($post['review_status']) ? intval($post['review_status']) : 1,
            'review_reason' => !empty($post['review_reason']) ? strval($post['review_reason']) : ''
        ];
        if (4 === intval($update['review_status'])) $update['review_reason'] = '分销商提现款已转入会员余额';

        // 执行更新
        $resultID = $this->dealerWithdraw->where($where)->update($update);
        if (!empty($resultID)) {
            // 同意申请
            if (2 == $update['review_status']) {
                $this->success('操作成功');
            }
            // 拒绝申请
            else if (3 === intval($update['review_status'])) {
                // 拒绝后续操作
                $where = [
                    'review_status' => 3,
                    'withdraw_id' => $post['withdraw_id'],
                ];
                $withdraw = $this->dealerWithdraw->where($where)->find();
                // 减少分销商可提现余额，增加分销商提现中余额
                $where = [
                    'users_id' => intval($withdraw['users_id']),
                    'dealer_id' => intval($withdraw['dealer_id']),
                ];
                $update = [
                    'dealer_money' => Db::raw('dealer_money+'.(strval($withdraw['withdraw_money']))),
                    'freeze_money' => Db::raw('freeze_money-'.(strval($withdraw['withdraw_money']))),
                    'update_time' => $times,
                ];
                // 查询分销商未更新前信息
                $dealer = $this->dealer->where($where)->find();
                // 执行更新
                $resultID = $this->dealer->where($where)->update($update);
                if (!empty($resultID)) {
                    // 恢复分销商可用金额操作记录
                    $dealerCommonLogic = new \weapp\DealerPlugin\logic\DealerCommonLogic;
                    $dealerCommonLogic->dealerMoneyLog(['withdraw_id' => $post['withdraw_id']], $dealer, $withdraw['withdraw_money'], 3);
                    $this->success('操作成功');
                } else {
                    // 恢复提现申请未原状态
                    $this->recoveryDealerWithdraw($post['withdraw_id']);
                    $this->error('操作失败');
                }
            }
            // 确认打款
            else if (4 === intval($update['review_status'])) {
                // 通过后续操作
                $where = [
                    'review_status' => 4,
                    'withdraw_id' => $post['withdraw_id'],
                ];
                $withdraw = $this->dealerWithdraw->where($where)->find();
                // 减少分销商可提现余额，增加分销商提现中余额
                $where = [
                    'users_id' => intval($withdraw['users_id']),
                    'dealer_id' => intval($withdraw['dealer_id']),
                ];
                $update = [
                    'freeze_money' => Db::raw('freeze_money-'.(strval($withdraw['withdraw_money']))),
                    'withdraw_money' => Db::raw('withdraw_money+'.(strval($withdraw['withdraw_money']))),
                    'update_time' => $times,
                ];
                // 执行更新
                $resultID = $this->dealer->where($where)->update($update);
                if (!empty($resultID)) {
                    // 增加会员余额
                    $where = [
                        'users_id' => intval($withdraw['users_id']),
                    ];
                    $update = [
                        'users_money' => Db::raw('users_money+'.(strval($withdraw['withdraw_money']))),
                        'update_time' => $times,
                    ];
                    $users = Db::name('users')->field('users_id, users_money')->where($where)->find();
                    $resultID = Db::name('users')->where($where)->update($update);
                    if (!empty($resultID)) {
                        // 添加会员余额明细表
                        $this->addUsersMoneyLog($withdraw['withdraw_order'], $withdraw['withdraw_money'], $users);
                        $this->success('打款成功');
                    }
                }

                // 恢复提现申请未原状态
                $this->recoveryDealerWithdraw($post['withdraw_id'], 2);
                $this->error('操作失败');
            }
        }
    }

    // 添加会员余额明细表
    private function addUsersMoneyLog($orderCode = null, $orderAmount = null, $users = [])
    {
        if (empty($orderCode) || empty($orderAmount) || empty($users)) return false;
        $times = getTime();
        $usersMoney = sprintf("%.2f", $users['users_money'] += $orderAmount);
        $insert = [
            'users_id'     => intval($users['users_id']),
            'money'        => floatval($orderAmount),
            'users_money'  => floatval($usersMoney),
            'cause'        => '分销商提现增加',
            'cause_type'   => 8,
            'status'       => 3,
            'pay_details'  => '',
            'order_number' => strval($orderCode),
            'add_time'     => $times,
            'update_time'  => $times,
        ];
        Db::name('users_money')->insert($insert);
    }

    // 恢复提现申请未原状态
    private function recoveryDealerWithdraw($withdraw_id = 0, $review_status = 1)
    {
        if (!empty($withdraw_id)) {
            // 执行条件
            $where = [
                'withdraw_id' => $withdraw_id
            ];
            // 更新信息
            $update = [
                'review_time' => 0,
                'review_status' => $review_status,
                'review_reason' => '',
                'update_time' => getTime(),
            ];
            if (2 === intval($update['review_status'])) $update['review_reason'] = '已核实，同意提现申请';
            $this->dealerWithdraw->where($where)->update($update);
        }
    }

    // 更新二级分销商的分销能力(恢复、冻结)
    public function updateDealerAbility($dealerLevel = 0)
    {
        // 查询所有二级分销商ID
        $where = [
            'b.is_dealer' => 1,
            'b.parent_users_id' => ['GT', 0],
            'b.parent_dealer_id' => ['GT', 0],
        ];
        $dealer_ids = $this->dealer->alias('a')->where($where)->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->column('dealer_id');
        // 指定更新二级分销商
        $where = [
            'dealer_id' => ['IN', $dealer_ids]
        ];
        // 更新信息
        $update = [
            'dealer_status' => 0,
            'update_time' => getTime(),
        ];
        // 一级分销商模式 则执行 冻结所有二级分销商所有分销能力
        if (1 === intval($dealerLevel)) {
            $update['dealer_status'] = 2;
        }
        // 二级分销商模式 则执行 恢复所有二级分销商所有分销能力
        else if (2 === intval($dealerLevel)) {
            $update['dealer_status'] = 1;
        }
        // 执行更新
        if (!empty($update['dealer_status'])) $this->dealer->where($where)->update($update);
    }

    // 立即结算分销商订单
    public function settlementDealerOrder($postDealer = [])
    {
        // 查询订单
        $where = [
            'order_status' => 3,
            'dealer_order' => 1,
            'handle_rebate' => 0,
            'dealer_id' => ['>', 0],
            'dealer_users_id' => ['>', 0],
        ];
        $shopOrder = Db::name('shop_order')->where($where)->select();
        // 订单结算佣金处理
        $dealerCommonLogic = new \weapp\DealerPlugin\logic\DealerCommonLogic;
        foreach ($shopOrder as $value) {
            $dealerCommonLogic->dealerOrderSettlementExecute($value['order_id'], $value['users_id'], 'confirm', $postDealer);
        }
    }


    

    // 查询分销商信息处理
    private function dealerInfoHandle()
    {
        // 分销商信息处理，分销商待审核总数 and 分销商总数 and 一级分销商 and 二级分销商 and 分销商客户
        $dealerApply = $dealerTotal = $dealerOneLevel = $dealerTwoLevel = $dealerCustomer = 0;

        // 分销商待审核总数
        $where = [
            'review_status' => 1,
        ];
        $dealerApply = $this->dealerApply->where($where)->count('apply_id');

        // 查询分销商ID
        $where = [
            'b.is_dealer' => 1,
            'a.system_dealer' => 0,
        ];
        $field = 'a.*, b.parent_users_id, b.parent_dealer_id';
        $dealerList = $this->dealer->alias('a')->field($field)
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.dealer_id desc')
            ->select();
        // 分销商信息处理 (分销商总数 and 一级分销商 and 二级分销商)
        foreach ($dealerList as $key => $value) {
            $dealerTotal++;
            if (empty($value['parent_users_id']) && empty($value['parent_dealer_id'])) {
                $dealerOneLevel++;
            } else if (!empty($value['parent_users_id']) && !empty($value['parent_dealer_id'])) {
                $dealerTwoLevel++;
            }
        }

        // 分销商客户
        $parent_users_ids = array_unique(get_arr_column($dealerList, 'users_id'));
        $parent_dealer_ids = array_unique(get_arr_column($dealerList, 'dealer_id'));
        if (!empty($parent_users_ids) && !empty($parent_dealer_ids)) {
            $where = [
                'is_dealer' => 0,
                'parent_users_id' => ['IN', $parent_users_ids],
                'parent_dealer_id' => ['IN', $parent_dealer_ids],
            ];
            $dealerCustomer = Db::name('users')->where($where)->count('users_id');
        }

        return [
            'dealerApply' => intval($dealerApply),
            'dealerTotal' => intval($dealerTotal),
            'dealerOneLevel' => intval($dealerOneLevel),
            'dealerTwoLevel' => intval($dealerTwoLevel),
            'dealerCustomer' => intval($dealerCustomer),
        ];
    }

    // 查询分销商订单，处理获取(待结算总佣金 and 已结算总佣金)
    private function getDealerOrderHandle($startTime = 0, $endTime = 0)
    {
        // 待结算总佣金 and 已结算总佣金
        $toBeSettledMoney = $alreadySettledMoney = 0;

        // 查询分销订单
        $where = [
            'dealer_order' => 1,
            'dealer_id' => ['NEQ', 0],
            'dealer_users_id' => ['NEQ', 0],
            'order_status' => ['IN', [0, 1, 2, 3]]
        ];
        if (!empty($startTime) && !empty($endTime)) $where['add_time']  = ['between', [$startTime, $endTime]];
        $orderInfo = $this->shopOrder->where($where)->select();

        // 处理分销订单
        foreach ($orderInfo as $key => $value) {
            // 佣金计算额、 一级分销佣金、 二级分销佣金
            $dealerTotalAmount = $value['order_one_rebate'] = $value['order_two_rebate'] = 0;
            // 佣金计算方式 (订单商品合计总额 or 订单实际支付总额)
            $dealerRebate = !empty($value['dealer_rebate']) ? intval($value['dealer_rebate']) : 0;
            // 一级佣金比例
            $oneLevelRebate = !empty($value['one_level_rebate']) ? intval($value['one_level_rebate']) / 100 : 0;
            // 二级佣金比例
            $twoLevelRebate = !empty($value['two_level_rebate']) ? intval($value['two_level_rebate']) / 100 : 0;

            // 使用 订单商品合计总额 进行计算分佣
            if (!empty($dealerRebate) && 1 === intval($dealerRebate)) {
                $dealerTotalAmount = unifyPriceHandle($value['order_total_amount']);
            }
            // 使用 订单实际支付总额((余额抵扣+实付款)-运费) 进行计算分佣
            else if (!empty($dealerRebate) && 2 === intval($dealerRebate)) {
                $dealerTotalAmount = unifyPriceHandle($value['order_amount']);
                // 存在运费则扣除运费，运费不在分销佣金计算中
                $dealerTotalAmount = !empty($value['shipping_fee']) ? floatval($dealerTotalAmount) - floatval($value['shipping_fee']) : $dealerTotalAmount;
            }

            // 一级分销佣金
            if (!empty($oneLevelRebate) && !empty($dealerTotalAmount)) {
                $value['order_one_rebate'] = unifyPriceHandle(floatval($oneLevelRebate) * floatval($dealerTotalAmount));
            }
            // 二级分销佣金
            if (!empty($twoLevelRebate) && !empty($dealerTotalAmount)) {
                $value['order_two_rebate'] = unifyPriceHandle(floatval($twoLevelRebate) * floatval($dealerTotalAmount));
            }

            // 一级分销佣金 + 二级分销佣金
            $totalOrderRebate = 0;
            $totalOrderRebate = floatval($value['order_one_rebate']) + floatval($value['order_two_rebate']);
            // 待结算总佣金
            if (isset($value['handle_rebate']) && 0 === intval($value['handle_rebate'])) {
                $toBeSettledMoney = unifyPriceHandle(floatval($toBeSettledMoney) + floatval($totalOrderRebate));
            }
            // 已结算总佣金
            if (isset($value['handle_rebate']) && 1 === intval($value['handle_rebate'])) {
                $alreadySettledMoney = unifyPriceHandle(floatval($alreadySettledMoney) + floatval($totalOrderRebate));
            }
        }

        return [
            'toBeSettledMoney' => $toBeSettledMoney,
            'alreadySettledMoney' => $alreadySettledMoney,
        ];
    }

    // 查询分销商提现订单，处理获取(提现待审核总佣金 and 提现待打款总佣金 and 已提现成功总佣金)
    private function getDealerWithdrawHandle()
    {
        // 查询分销商ID
        $where = [
            'system_dealer' => 0,
            // 'dealer_status' => 1,
        ];
        $dealer_ids = $this->dealer->where($where)->column('dealer_id');

        // 查询分销提现订单
        $where = [
            'dealer_id' => ['IN', $dealer_ids]
        ];
        $withdraw = $this->dealerWithdraw->where($where)->select();

        // 处理提现订单 (提现待审核总佣金 and 提现待审核总佣金 and 已提现成功总佣金)
        $toBeReviewMoney = $toBeHitPayMoney = $alreadyDealerMoney = 0;
        foreach ($withdraw as $key => $value) {
            if (isset($value['review_status']) && 1 === intval($value['review_status'])) {
                $toBeReviewMoney = unifyPriceHandle(floatval($toBeReviewMoney) + floatval($value['withdraw_money']));
            } else if (isset($value['review_status']) && 2 === intval($value['review_status'])) {
                $toBeHitPayMoney = unifyPriceHandle(floatval($toBeHitPayMoney) + floatval($value['withdraw_money']));
            } else if (isset($value['review_status']) && 4 === intval($value['review_status'])) {
                $alreadyDealerMoney = unifyPriceHandle(floatval($alreadyDealerMoney) + floatval($value['withdraw_money']));
            }
        }

        return [
            'toBeReviewMoney' => $toBeReviewMoney,
            'toBeHitPayMoney' => $toBeHitPayMoney,
            'alreadyDealerMoney' => $alreadyDealerMoney,
        ];
    }

    // 分销商可用总佣金
    private function getDealerAvailableMoney()
    {
        $where = [
            'system_dealer' => 0,
            // 'dealer_status' => 1,
            'dealer_money' => ['GT', 0],
        ];
        return $this->dealer->where($where)->sum('dealer_money');
    }

    // 查询新增的分销商数
    private function getAddDealerNum($startTime = 0, $endTime = 0)
    {
        $where = [
            'system_dealer' => 0,
            // 'dealer_status' => 1,
            'add_time' => ['between', [$startTime, $endTime]],
        ];
        return $this->dealer->where($where)->count('dealer_id');
    }

}
