package jnpf.authority.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import jnpf.authority.mapper.FtbPermissionRoleAuthorizePostMapper;
import jnpf.authority.service.FtbPermissionRoleAuthorizePostService;
import jnpf.base.ActionResult;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.base.vo.PageListVO;
import jnpf.model.authority.dto.authorize.FtbPermissionAuthorizeVO;
import jnpf.model.authority.dto.person.FtbPermissionRoleBatchDeleteDTO;
import jnpf.model.authority.dto.post.FtbPermissionRolePostAddDTO;
import jnpf.model.authority.po.FtbPermissionRoleAuthorizePost;
import jnpf.model.authority.vo.post.FtbAuthorizedPostVO;
import jnpf.model.cultivate.CultivatePage;
import jnpf.permission.V2PositionApi;
import jnpf.permission.V2UserApi;
import jnpf.permission.dto.v2.user.QueryUserBatchDTO;
import jnpf.permission.vo.v2.organzie.OrganizeFullBasicVO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.AuthUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 *
 *@Author: peng.hao
 *@create: 2025/3/5
 *
 */
@Service
public class FtbPermissionRoleAuthorizePostServiceImpl extends ServiceImpl<FtbPermissionRoleAuthorizePostMapper, FtbPermissionRoleAuthorizePost> implements FtbPermissionRoleAuthorizePostService{


    @Autowired
    V2UserApi v2UserApi;

    @Autowired
    V2PositionApi v2PositionApi;

    @Override
    public void addPost(FtbPermissionRolePostAddDTO ftbPermissionRolePostAddDTO) {
        LambdaQueryWrapper<FtbPermissionRoleAuthorizePost> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FtbPermissionRoleAuthorizePost::getEnableMark,0);
        lambdaQueryWrapper.eq(FtbPermissionRoleAuthorizePost::getRoleId,ftbPermissionRolePostAddDTO.getRoleId());
        List<FtbPermissionRoleAuthorizePost> authorizePosts = baseMapper.selectList(lambdaQueryWrapper);
        List<String> postIds = ftbPermissionRolePostAddDTO.getPostIds();
        // 清空所有绑定岗位
        List<String> collected = authorizePosts.stream().map(FtbPermissionRoleAuthorizePost::getPostId).collect(Collectors.toList());
        if(CollUtil.isEmpty(postIds) && CollUtil.isNotEmpty(authorizePosts)){
            baseMapper.deleteBatchIds(authorizePosts.stream().map(SuperBaseEntity.SuperIBaseEntity::getId).collect(Collectors.toList()));
            clearUserLogins(collected);
            return;
        }
        if (CollUtil.isNotEmpty(authorizePosts)){
            List<String> newPostIds = postIds.stream().filter(v -> !collected.contains(v)).collect(Collectors.toList());
            List<String> finalPostIds = postIds;
            List<String> deletePostIds = collected.stream().filter(v->!finalPostIds.contains(v)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(deletePostIds)){
                baseMapper.deleteBatchIds(authorizePosts.stream().filter(v->deletePostIds.contains(v.getPostId())).map(SuperBaseEntity.SuperIBaseEntity::getId).collect(Collectors.toList()));
            }
            postIds = newPostIds;
        }
        if (CollUtil.isEmpty(postIds)) return;
        List<FtbPermissionRoleAuthorizePost> savePost = postIds.stream().map(v -> {
            FtbPermissionRoleAuthorizePost ftbPermissionRoleAuthorizePost = new FtbPermissionRoleAuthorizePost();
            ftbPermissionRoleAuthorizePost.setRoleId(ftbPermissionRolePostAddDTO.getRoleId());
            ftbPermissionRoleAuthorizePost.setPostId(v);
            return ftbPermissionRoleAuthorizePost;
        }).collect(Collectors.toList());
        Db.saveBatch(savePost);
        clearUserLogins(postIds);
    }

    /**
     *
     * @param postIds
     */
    private void clearUserLogins(List<String> postIds) {
        if (CollUtil.isEmpty(postIds)) return;
        QueryUserBatchDTO userBatchDTO = new QueryUserBatchDTO();
        userBatchDTO.setPositionIds(postIds);
        userBatchDTO.setTenantId(UserProvider.getUser().getTenantId());
        ActionResult<List<UserBoundVO>> userInfoBatch = v2UserApi.getUserInfoBatch(userBatchDTO);
        if (userInfoBatch ==  null || userInfoBatch.getData() == null) return;
        List<String> userIds = userInfoBatch.getData().stream().map(UserBoundVO::getId).collect(Collectors.toList());
        // 员工踢下线
        userIds.forEach(AuthUtil::kickoutByUserId);
    }

    @Override
    public PageListVO<FtbAuthorizedPostVO> authorizePost(Page<FtbAuthorizedPostVO> page, String roleId) {
        LambdaQueryWrapper<FtbPermissionRoleAuthorizePost> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FtbPermissionRoleAuthorizePost::getRoleId, roleId);
        wrapper.eq(FtbPermissionRoleAuthorizePost::getEnableMark,0);
        List<FtbPermissionRoleAuthorizePost> authorizePosts = baseMapper.selectList(wrapper);
        if(CollUtil.isEmpty(authorizePosts)) return new PageListVO<>();
        List<String> postIds = authorizePosts.stream().map(FtbPermissionRoleAuthorizePost::getPostId).collect(Collectors.toList());
        List<String> userIds = authorizePosts.stream().map(FtbPermissionRoleAuthorizePost::getCreatorUserId).collect(Collectors.toList());
        ActionResult<List<UserBoundVO>> boundBatch = v2UserApi.getUserPrimaryBoundBatch(userIds, UserProvider.getUser().getTenantId());
        Map<String, UserBoundVO> idsPost = new HashMap<>();
        if(boundBatch != null && CollUtil.isNotEmpty(boundBatch.getData())){
            List<UserBoundVO> data = boundBatch.getData();
            idsPost = data.stream().collect(Collectors.toMap(UserBoundVO::getId, item -> item, (k1, k2) -> k1));
        }
        ActionResult<List<PositionVO>> listActionResult = v2PositionApi.listPositionDetailInfo(postIds);
        Map<String, PositionVO> finalIdsPost = new HashMap<>();
        if (listActionResult !=null && CollUtil.isNotEmpty(listActionResult.getData())) {
            finalIdsPost= listActionResult.getData().stream()
                    .collect(Collectors.toMap(PositionVO::getId, item -> item, (k1, k2) -> k1));
        }
        Map<String, UserBoundVO> finalIdsPost1 = idsPost;
        Map<String, PositionVO> finalIdsPost2 = finalIdsPost;
        List<FtbAuthorizedPostVO> authorizedPostVOS = authorizePosts.stream().map(v -> {
            FtbAuthorizedPostVO convert = FtbAuthorizedPostVO.convert(v);
            if(finalIdsPost1.containsKey(v.getCreatorUserId())){
                UserBoundVO userInfoVo = finalIdsPost1.get(v.getCreatorUserId());
                convert.setOperatorUserName(userInfoVo.getUserName());
            }
            if(finalIdsPost2.containsKey(v.getPostId())) {
                PositionVO dimensionVO = finalIdsPost2.get(v.getPostId());
                convert.setPostName(dimensionVO.getFullName());
                List<OrganizeFullBasicVO> organizes = dimensionVO.getOrganizes();
                if(CollUtil.isEmpty(organizes)) return convert;
                convert.setOrgName( organizes.stream().map(OrganizeFullBasicVO::getName).collect(Collectors.joining(",")));
            }
            return convert;
        }).collect(Collectors.toList());
        return CultivatePage.paginate(authorizedPostVOS,page);
    }

    @Override
    public List<String> getRoleIdsByPostIds(FtbPermissionAuthorizeVO vo) {
        LambdaQueryWrapper<FtbPermissionRoleAuthorizePost> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FtbPermissionRoleAuthorizePost::getEnableMark,0);
        wrapper.in(FtbPermissionRoleAuthorizePost::getRoleId,vo.getAuthorizationId());
        List<FtbPermissionRoleAuthorizePost> list = baseMapper.selectList(wrapper);
        List<String> hasBandPostIds = list.stream().map(FtbPermissionRoleAuthorizePost::getPostId).distinct().collect(Collectors.toList());
        List<String> postIds = vo.getIds();
        if(CollUtil.isNotEmpty(hasBandPostIds)){
            return postIds.stream().filter(v -> !hasBandPostIds.contains(v)).collect(Collectors.toList());
        }
        return postIds;
    }

    @Override
    public void batchDelete(FtbPermissionRoleBatchDeleteDTO rolePersonDeleteDTO) {
        List<FtbPermissionRoleAuthorizePost> posts = baseMapper.selectBatchIds(rolePersonDeleteDTO.getPrimaryKeyIds());
        baseMapper.deleteBatchIds(rolePersonDeleteDTO.getPrimaryKeyIds());
        clearUserLogins(posts.stream().map(FtbPermissionRoleAuthorizePost::getPostId).distinct().collect(Collectors.toList()));
    }

    @Override
    public void clearRoleByPostId(List<String> postIds) {
        if(CollUtil.isEmpty(postIds)) return;
        LambdaQueryWrapper<FtbPermissionRoleAuthorizePost> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FtbPermissionRoleAuthorizePost::getEnableMark,0);
        queryWrapper.in(FtbPermissionRoleAuthorizePost::getPostId,postIds);
        baseMapper.delete(queryWrapper);
    }

}
