package org.jeecg.modules.adweb.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.adweb.common.util.ListUtil;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysAdwebApiImpl implements SysAdwebApi {
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysUserMapper userMapper;

    @Override
    public boolean isAdmin() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> adminRoleIdList = new ArrayList<>();    // 管理员角色id列表
        adminRoleIdList.add("admin");
        adminRoleIdList.add("adweb_admin");
        adminRoleIdList.add("seo_admin");
        adminRoleIdList.add("adweb_site_manager");
        adminRoleIdList.add("adweb_seo_manager");
        List<String> roles = sysUserRoleMapper.getRoleByUserName(username);
        for (String role : roles) {
            if (adminRoleIdList.contains(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isOem() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> adminRoleIdList = new ArrayList<>();    // 管理员角色id列表
        adminRoleIdList.add("adweb_oem");
        List<String> roles = sysUserRoleMapper.getRoleByUserName(username);
        for (String role : roles) {
            if ("adweb_oem".equals(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<String> getOemGroupUids() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = userMapper.getUserByName(loginUser.getUsername());
        String workNo = sysUser.getWorkNo();
        List<String> list = null;
        try {
            list = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getOemCode, workNo)).stream().map(SysUser::getId).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取当前登录渠道下客户群的uid");
        }
        if (ListUtil.isEmpty(list)) {
            list = new ArrayList<>();
            list.add("-1");
        }
        list.add(sysUser.getId());
        return list;
    }
}
