<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class Member extends Base
{
    public const STATUS_NORMAL = 1;//正常
    public const STATUS_DISABLE = 0;//禁用

    public const MANAGER_ROLE_ID = 1;//角色id 2 为管理员
    public const ANENT_ROLE_ID = 2;//角色id 2 为代理商
    public const STAFF_ROLE_ID = 3;//角色id 2 为工作人员


    public static function getList($limit = 40)
    {
        return self::alias('m')
            ->leftjoin('auth_group g', 'g.id=m.group_id')
            ->field('m.id,m.username,m.login_time,m.group_id,g.title')
            ->order('m.id', 'asc')
            ->paginate($limit);
    }

    /**
     * 获取所有代理商
     * */
    public static function getAgentAll()
    {

        $subQuery = Db::name('member')
            ->field('id,business_code,nickname')
            ->whereRaw('(find_in_set("' . Member::ANENT_ROLE_ID . '", roles))')
            ->buildSql();

        return Db::table($subQuery . ' a')
            ->join("business b", "a.business_code = b.code")
            ->field("a.*")
            ->order('a.id', 'desc')
            ->select();
    }

    /**
     * 根据角色分组返回用户
     * @param int $groupId 角色分组ID
     * @param int $limit 每页数量
     */
    public static function getListByGroup($groupId, $limit = 40)
    {
        return self::alias('m')
            ->leftjoin('auth_group g', 'g.id=m.group_id')
            ->field('m.id,m.username,m.login_time,m.group_id,g.title')
            ->where('m.group_id', '=', $groupId)
            ->order('m.id', 'asc')
            ->paginate($limit);
    }

    //根据用户名获取管理账号
    public static function getByUserName($username)
    {
        return self::where('username', trim($username))
            ->findOrEmpty()
            ->toArray();
    }

    //根据ID获取管理账户和相关权限
    public static function getMemberAndRulesByID($memberId)
    {
        return self::alias('m')
            ->join('auth_group g', 'm.group_id = g.id', 'LEFT')
            ->field('m.group_id,g.rules')
            ->where('m.id', $memberId)
            ->findOrEmpty()
            ->toArray();
    }

    public static function updateCates($id, $cates)
    {
        $cates = implode(',', $cates);
        $data = ['cates' => $cates];
        self::updateById($id, $data);
    }

    /**
     * 验证当前用户是否是渠道商
     * @param string $roles
     * @return bool
     */
    public static function is_agency(string $roles)
    {
        if (empty($roles)) {
            return true;
        }

        $roles = explode(",", $roles);

        //包含管理员就返回false
        if (in_array(self::MANAGER_ROLE_ID, $roles)) {
            return false;
        }

        if (in_array(self::STAFF_ROLE_ID, $roles) || in_array(self::ANENT_ROLE_ID, $roles)) {

            return true;
        }
        return false;
    }

    public static function onAfterInsert ($obj)
    {
        $obj->create_time = date("Y-m-d H:i:s");
        $obj->save();
    }

    public static function hasStaff($id)
    {
        return self::where("pid",$id)->count();
    }
}