package jnpf.notice.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;
import jnpf.authority.utils.PermissionsUtils;
import jnpf.base.UserInfo;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.notice.dto.FtbNoticeAnnouncementsReceiveDto;
import jnpf.model.notice.dto.NoticeUserDto;
import jnpf.model.notice.dto.UserOrgAndPositionDto;
import jnpf.model.notice.enums.NoticeEnums;
import jnpf.model.notice.req.announcement.QueryUserListReq;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.mapper.FtbPersonnelsStaffRosterMapper;
import jnpf.util.Constants;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public class NoticeUtils {


    @Autowired
    private UserApiV2Util userApiV2Util;

    @Autowired
    private PermissionsUtils permissionsUtils;

    @Autowired
    private UserApi userApi;

    public static final String NOTICE_UPDATE_KEY = "notice_upd_pub_alt:%s";
    public static final Integer NOTICE_UPDATE_MAX_TIME = 5;//最大执行时间，key过期
    
    /**
     * Redis key: 定时发布公告的最大发布时间
     */
    public static final String NOTICE_SCHEDULED_MAX_TIME_KEY = "notice:scheduled:notice_time:%s";

    /**
     * 补充用户信息
     *
     * @param userIds   用户列表
     * @param filterOut 是否过滤离职员工 true 过滤  false 不过滤
     * @return
     */
    public List<NoticeUserDto> FillUserInfo(List<String> userIds, Boolean filterOut) {
        if (CollectionUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);

        if (userPrimaryBoundBatch.isEmpty()) {
            return new ArrayList<>();
        }
        List<NoticeUserDto> userDtoList = new ArrayList<>();
        for (Map.Entry<String, UserBoundVO> entry : userPrimaryBoundBatch.entrySet()) {
            UserBoundVO userBoundVO = entry.getValue();
            // 处理逻辑
            NoticeUserDto noticeUserDto = new NoticeUserDto();
            noticeUserDto.setUserId(userBoundVO.getId());
            noticeUserDto.setUserName(userBoundVO.getName());
            noticeUserDto.setHeadLogo(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
            noticeUserDto.setFlowerName(userBoundVO.getNickname());
            UserOrgAndPositionDto userOrgAndPositionDto = getUserOrgAndPositionDto(userBoundVO);
            noticeUserDto.setOrgList(List.of(userOrgAndPositionDto));
            userDtoList.add(noticeUserDto);
        }
        return userDtoList;
    }


    public List<String> queryEffectiveUserIds(List<String> userIds, Boolean filterOut) {
        if (CollectionUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        List<UserBoundVO> userPrimaryBoundBatchReturnList = userApiV2Util.getUserPrimaryBoundBatchReturnList(userIds, null);

        List<String> userIdList = new ArrayList<>();
        for (UserBoundVO roster : userPrimaryBoundBatchReturnList) {
            userIdList.add(roster.getId());
        }
        return userIdList;
    }

    /**
     * 查询所有的正常用户
     *
     * @return 用户列表
     */
    public List<String> queryAllUserId() {
        InnerPowerUserVO innerPowerUserVO = userApiV2Util.getLoginManagerUserIdsForEncode();
        if (innerPowerUserVO.getCode().equals(0)) {
            return queryAllValidUserId();
        } else if (innerPowerUserVO.getCode().equals(1)) {
            return innerPowerUserVO.getUserIds();
        } else {
            return new ArrayList<>();
        }
    }

    public List<String> queryAllValidUserId() {
        List<UserBoundVO> allUserList = userApiV2Util.getAllUserList(null);
        if (CollectionUtil.isEmpty(allUserList)) {
            return new ArrayList<>();
        }
        List<String> userIdList = new ArrayList<>();
        for (UserBoundVO userBoundVO : allUserList) {
            userIdList.add(userBoundVO.getId());
        }
        return userIdList;
    }


    /**
     * 根据用户id查询权限（非登录用户）
     * @param userId 用户id
     * @param moduleId 模块id
     * @return 权限列表
     */
    public List<String> queryPermissionForUserId(String userId, String moduleId,String tenantId) {
        //判断是否是超级管理员
        List<UserEntity> userListNoData = userApi.getUserListNoData(List.of(userId), tenantId);
        if(CollectionUtil.isEmpty(userListNoData)){
            return new ArrayList<>();
        }
        //超级管理员自己获取
        if(userListNoData.get(0).getIsAdministrator() == 1){
            List<UserBoundVO> allUserList = userApiV2Util.getAllUserList(tenantId);
            if (CollectionUtil.isEmpty(allUserList)) {
                return new ArrayList<>();
            }
            List<String> userIdList = new ArrayList<>();
            for (UserBoundVO userBoundVO : allUserList) {
                userIdList.add(userBoundVO.getId());
            }
            return userIdList;
        }
        return permissionsUtils.obtainPersonnelUserIdDataPermissions(userId, moduleId);
    }
    /**
     * 查询用户列表
     *
     * @param req 查询参数
     * @return 用户列表
     */

    public PageInfo<FtbNoticeAnnouncementsReceiveDto> queryUserByPage(QueryUserListReq req) {
        List<UserBoundVO> allUserList = userApiV2Util.getAllUserList(null);
        int pageNum = 1;
        if (req.getCurrentPage() != null && req.getCurrentPage() > 0) {
            pageNum = req.getCurrentPage();
        }

        int pageSize = 10; // 每页数量
        if (req.getPageSize() != null && req.getPageSize() > 0) {
            pageSize = req.getPageSize();
        }
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, allUserList.size());

        List<UserBoundVO> records = allUserList.subList(fromIndex, toIndex);
        //转换查询对象
        List<FtbNoticeAnnouncementsReceiveDto> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            for (UserBoundVO record : records) {
                FtbNoticeAnnouncementsReceiveDto dto = new FtbNoticeAnnouncementsReceiveDto();
                dto.setUserId(record.getId());
                dto.setUserName(record.getName());
                dto.setRosterId(record.getId());
                dto.setReadStatus(NoticeEnums.ReadStatus.UNREAD.getCode());
                list.add(dto);
            }
            fillFlowerAndHeadLog(list);
        }

        //构建分页返回数据
        PageInfo<FtbNoticeAnnouncementsReceiveDto> pageInfo = new PageInfo<>();
        pageInfo.setList(list);
        pageInfo.setPageSize((int) req.getPageSize());
        pageInfo.setPageNum((int) req.getCurrentPage());
        pageInfo.setTotal((int) allUserList.size());
        return pageInfo;
    }

    /**
     * 查询用户的岗位信息
     *
     * @param userId 用户id
     * @return 岗位信息
     */
    public List<UserOrgAndPositionDto> getUserOrgBoundInfo(String userId) {
        List<UserBoundVO> list = userApiV2Util.getUserPrimaryBoundBatchReturnList(List.of(userId), null);
        if (CollectionUtil.isEmpty(list)) {
            return CollectionUtil.newArrayList();
        }
        List<UserOrgAndPositionDto> retList = new ArrayList<>();
        for (UserBoundVO vo : list) {
            UserOrgAndPositionDto dto = new UserOrgAndPositionDto();
            dto.setOrgId(vo.getOrganizeId());
            dto.setOrgName(vo.getOrganizeName());
            dto.setOrgEncode(vo.getOrganizeEnCode());

            dto.setPositionId(vo.getPositionId());
            dto.setPositionName(vo.getPositionName());
            dto.setPositionEncode(vo.getPositionEnCode());
            dto.setRankId(vo.getGradeId());
            dto.setRankName(vo.getGradeName());
            retList.add(dto);
        }
        return retList;
    }


    /**
     * 对应字符串list去重复
     *
     * @param list 字符串集合
     * @return 去重后的字符串集合
     */
    public List<String> uniqueStringList(List<String> list) {
        if (CollectionUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream()
                .filter(Objects::nonNull) // 过滤掉 null 值
                .filter(str -> !str.isEmpty()) // 过滤掉空字符串
                .distinct() // 去重
                .collect(Collectors.toList()); // 收集为 List
    }

    /**
     * 获取随机数
     *
     * @return 随机数
     */
    private Integer getRandom() {
        Random random = new Random();
        return random.nextInt(60);
    }

    /**
     * 填充用户的花名和头像
     *
     * @param list 用户列表
     */
    public <T extends NoticeUserDto> void fillFlowerAndHeadLog(List<T> list) {
        List<String> userIds = new ArrayList<>();
        for (NoticeUserDto noticeUserDto : list) {
            userIds.add(noticeUserDto.getUserId());
        }
        Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        for (NoticeUserDto noticeUserDto : list) {
            UserBoundVO userBoundVO = userPrimaryBoundBatch.get(noticeUserDto.getUserId());
            if (userBoundVO != null) {
                noticeUserDto.setUserId(userBoundVO.getId());
                noticeUserDto.setUserName(userBoundVO.getName());
                noticeUserDto.setHeadLogo(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
                noticeUserDto.setFlowerName(userBoundVO.getNickname());
                UserOrgAndPositionDto userOrgAndPositionDto = getUserOrgAndPositionDto(userBoundVO);
                noticeUserDto.setOrgList(List.of(userOrgAndPositionDto));
            }
        }
    }


    @NotNull
    public static UserOrgAndPositionDto getUserOrgAndPositionDto(UserBoundVO userBoundVO) {
        UserOrgAndPositionDto userOrgAndPositionDto = new UserOrgAndPositionDto();
        userOrgAndPositionDto.setOrgId(userBoundVO.getOrganizeId());
        userOrgAndPositionDto.setOrgEncode(userBoundVO.getOrganizeEnCode());
        userOrgAndPositionDto.setOrgName(userBoundVO.getOrganizeName());
        userOrgAndPositionDto.setPositionId(userBoundVO.getPositionId());
        userOrgAndPositionDto.setPositionEncode(userBoundVO.getPositionEnCode());
        userOrgAndPositionDto.setPositionName(userBoundVO.getPositionName());
        userOrgAndPositionDto.setRankId(userBoundVO.getGradeId());
        userOrgAndPositionDto.setRankName(userBoundVO.getGradeName());
        return userOrgAndPositionDto;
    }

    /**
     * 去掉富文本中的script 脚本
     *
     * @param htmlString
     * @return 去掉的富文本
     */

    public String replaceAllScript(String htmlString) {
        if (StringUtils.isEmpty(htmlString)) {
            return "";
        }
        return htmlString.replaceAll("<script[^>]*>", "").replaceAll("<SCRIPT[^>]*>", "")
                .replaceAll("</script>", "").replaceAll("</SCRIPT>", "");
    }

    /**
     * 去除html标签 并且截取前maxNum个字符
     *
     * @param htmlString html字符串
     * @param maxNum     截取最大长度
     * @return 截取后的字符串
     */
    public String clearHtmlTag(String htmlString, Integer maxNum) {
        if (StringUtils.isEmpty(htmlString)) {
            return "";
        }
        htmlString = replaceImgTagsWithText(htmlString);
        String cleanedHtml = HtmlUtil.cleanHtmlTag(htmlString);
        return StrUtil.sub(cleanedHtml, 0, maxNum); // 从第0个字符开始截取，长度为10
    }

    /**
     * 将HTML字符串中的所有<img>, <video>, <audio>标签替换为对应的文字。
     *
     * @param htmlContent 要处理的HTML字符串
     * @return 处理后的字符串
     */
    public String replaceImgTagsWithText(String htmlContent) {
        Pattern pattern = Pattern.compile("(?i)<(img|video|audio)[^>]*>");
        Matcher matcher = pattern.matcher(htmlContent);
        // 使用正则表达式的replaceAll方法替换匹配到的标签
        htmlContent = matcher.replaceAll(match -> {
            String tag = match.group(1);
            switch (tag.toLowerCase()) {
                case "img":
                    return "[图片]";
                case "video":
                    return "[视频]";
                case "audio":
                    return "[音频]";
                default:
                    return match.group();
            }
        });
        return htmlContent
                .replaceAll("</img>", "").replaceAll("</IMG>", "")
                .replaceAll("</video>", "").replaceAll("</VIDEO>", "")
                .replaceAll("</audio>", "").replaceAll("</AUDIO>", "");
    }

    /**
     * 获取租户编码
     *
     * @return  String
     */
    public String getTenantId() {
        UserInfo userInfo = UserProvider.getUser();
        return userInfo.getTenantId();
    }

    /**
     * 根据用户ID 查询用户的基本信息 姓名 头像 花名
     *
     * @param userId 用户ID
     * @return NoticeUserDto
     */
    public NoticeUserDto queryUserInfoForUserId(String userId) {
        NoticeUserDto noticeUserDto = new NoticeUserDto();
        if (StringUtils.isEmpty(userId)) {
            return noticeUserDto;
        }
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        if (userPrimaryBoundOne != null) {
            noticeUserDto.setUserId(userPrimaryBoundOne.getId());
            noticeUserDto.setUserName(userPrimaryBoundOne.getName());
            noticeUserDto.setHeadLogo(UploaderUtil.uploaderImg(userPrimaryBoundOne.getHeadIcon()));
            noticeUserDto.setFlowerName(userPrimaryBoundOne.getNickname());
            UserOrgAndPositionDto userOrgAndPositionDto = getUserOrgAndPositionDto(userPrimaryBoundOne);
            noticeUserDto.setOrgList(List.of(userOrgAndPositionDto));
        }


        return noticeUserDto;
    }

    /**
     * 获取登录头信息
     *
     * @return  Map
     */
    public Map<String, String> getHeadersForLogin() {
        UserInfo userInfo = UserProvider.getUser();
        String token = userInfo.getToken();
        if (StringUtils.isEmpty(token)) {
            token = "";
        }
        return ImmutableMap.of(Constants.AUTHORIZATION.toLowerCase(), token);
    }

    /**
     * 过滤无效用户
     *
     * @param userList 用户id列表
     * @return 过滤后的用户id列表
     */
    public List<String> filterInvalidUser(List<String> userList) {
        if (CollectionUtil.isEmpty(userList)) {
            return Collections.emptyList();
        }

        // 查询所有有效用户ID
        List<String> validUsers = queryAllValidUserId();
        if (CollectionUtil.isEmpty(validUsers)) {
            return Collections.emptyList();
        }
        try {
            return getIntersection(userList, validUsers);
        } catch (Exception e) {
            // 根据实际需求决定是否记录日志或抛出异常
            // 示例：log.warn("过滤无效用户时发生异常", e);
            return Collections.emptyList();
        }
    }

    /**
     * 获取两个List<String>的交集
     *
     * @param list1 第一个列表
     * @param list2 第二个列表
     * @return 交集列表
     */
    public static List<String> getIntersection(List<String> list1, List<String> list2) {
        if (CollectionUtil.isEmpty(list1) || CollectionUtil.isEmpty(list2)) {
            return new ArrayList<>();
        }

        Set<String> set2 = new HashSet<>(list2);
        return list1.stream()
                .filter(s -> s != null && set2.contains(s))
                .distinct()
                .collect(Collectors.toList());
    }
}
