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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcoding.http.util.StringUtil;

import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.DictPropertyModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.common.constant.NumConstant;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.site.service.ISiteUserPermissionService;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysDictItemMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

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

    @Resource private SysUserMapper userMapper;

    @Resource private SysDictItemMapper sysDictItemMapper;

    @Autowired private ISiteUserPermissionService siteUserPermissionService;

    @Autowired private IAdwebSiteService adwebSiteService;

    @Autowired private ISysBaseAPI sysBaseAPI;

    @Autowired private ISysDictService sysDictService;

    @Autowired private ISysUserTenantService sysUserTenantService;

    @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 isChannelAdmin() {
        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_channel_admin".equals(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<String> getChannelGroupUids() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser sysUser = userMapper.getUserByName(loginUser.getUsername());
        Integer tenantId = sysUser.getLoginTenantId();
        List<String> list = null;
        try {
            list = sysUserTenantService.getUserIdsByTenantId(tenantId);
        } catch (Exception e) {
            log.error("获取当前登录渠道下客户群的uid");
        }
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
            list.add("-1");
        }
        list.add(sysUser.getId());
        return list;
    }

    /**
     * @param siteId
     * @return
     */
    @Override
    public boolean isNotOwnSite(Integer siteId) {
        if (siteId == null) {
            return true;
        }

        LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();

        if (this.isChannelAdmin()) {
            List<String> channelGroupUids = this.getChannelGroupUids();
            List<String> codeList =
                    siteUserPermissionService.getSiteCodeListByUids(channelGroupUids);
            queryWrapper.in(AdwebSite::getCode, codeList);
        } else if (!this.isAdmin()) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> codeList = siteUserPermissionService.getSiteCodeList(loginUser.getId());
            queryWrapper.in(AdwebSite::getCode, codeList);
        }
        queryWrapper.eq(AdwebSite::getId, siteId);
        queryWrapper.ne(AdwebSite::getStatus, NumConstant.ZERO);
        List<AdwebSite> list = adwebSiteService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return false;
        }
        return true;
    }

    /**
     * @param siteCode
     * @return
     */
    @Override
    public boolean isNotOwnSite(String siteCode) {
        if (this.isAdmin()) {
            return false;
        }
        if (StringUtil.isEmpty(siteCode)) {
            return true;
        }
        LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();

        if (this.isChannelAdmin()) {
            List<String> channelGroupUids = this.getChannelGroupUids();
            List<String> codeList =
                    siteUserPermissionService.getSiteCodeListByUids(channelGroupUids);
            queryWrapper.in(AdwebSite::getCode, codeList);
        } else if (!this.isAdmin()) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> codeList = siteUserPermissionService.getSiteCodeList(loginUser.getId());
            queryWrapper.in(AdwebSite::getCode, codeList);
        }
        queryWrapper.eq(AdwebSite::getCode, siteCode);
        queryWrapper.ne(AdwebSite::getStatus, AdwebConstant.SITE_DEL);
        List<AdwebSite> list = adwebSiteService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return false;
        }
        return true;
    }

    /** 判断一个用户是否是adweb会员 */
    @Override
    public boolean isAdwebVip() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseAPI.getRolesByUsername(username);
        for (String role : roles) {
            if ("adweb_vip".equals(role)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return
     */
    @Override
    public boolean isAdwebSubVip() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseAPI.getRolesByUsername(username);
        for (String role : roles) {
            if ("adweb_sub_vip".equals(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<DictPropertyModel> queryDictInfoByDictCode(String dictCode) {
        List<DictModel> dictModels = sysDictService.queryDictItemsByCode(dictCode);
        List<DictPropertyModel> propertyModels = new ArrayList<>();
        for (DictModel data : dictModels) {
            DictPropertyModel propertyModel = new DictPropertyModel();
            propertyModel.setCatalogCode(dictCode);
            propertyModel.setLabel(data.getText());
            propertyModel.setValue(data.getValue());
            propertyModels.add(propertyModel);
        }
        return propertyModels;
    }

    @Override
    public List<SysDictItem> selectItemsByDictCode(String dictCode) {
        return sysDictItemMapper.selectItemsByDictCode(dictCode);
    }
}
