<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\model\dealer;

use app\common\model\dealer\Referee as RefereeModel;

/**
 * 分销商推荐关系模型
 * Class Referee
 * @package app\store\model\dealer
 */
class Referee extends RefereeModel
{
    /**
     * 获取下级团队成员ID集
     * @param int $dealerId
     * @param int $level
     * @return array
     */
    public function getTeamUserIds(int $dealerId, int $level = -1): array
    {
        $level > -1 && $this->where('m.level', '=', $level);
        return $this->alias('m')
            ->join('user', 'user.user_id = m.user_id')
            ->where('m.dealer_id', '=', $dealerId)
            ->where('user.is_delete', '=', 0)
            ->column('m.user_id');
    }

    /**
     * 获取指定用户的推荐人列表
     * @param int $userId
     * @return Referee[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRefereeList(int $userId)
    {
        return (new static)->with(['dealer'])->where('user_id', '=', $userId)->select();
    }

    /**
     * 清空下级成员推荐关系
     * @param int $dealerId
     * @param int $level
     * @return bool|int
     */
    public function onClearTeam(int $dealerId, int $level = -1)
    {
        $where = [['dealer_id', '=', $dealerId]];
        $level > -1 && $where[] = ['level', '=', $level];
        return static::deleteAll($where);
    }

    /**
     * 清空上级推荐关系
     * @param int $userId
     * @param int $level
     * @return bool|int
     */
    public function onClearReferee(int $userId, int $level = -1)
    {
        $where = [['user_id', '=', $userId]];
        $level > -1 && $where[] = ['level', '=', $level];
        return static::deleteAll($where);
    }

    /**
     * 清空2-3级推荐人的关系记录
     * @param array $teamIds
     * @return bool
     */
    public function onClearTop(array $teamIds): bool
    {
        return $this->where('user_id', 'in', $teamIds)
            ->where('level', 'in', [2, 3])
            ->delete();
    }
}