package jnpf.cultivate.controller.web.org;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.ActionResult;
import jnpf.cultivate.mapper.FtbCultivatePromotionPostNewMapper;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.po.org.FtbCultivatePositionGradeVO;
import jnpf.model.cultivate.po.org.FtbPositionGradesInfoBoundVO;
import jnpf.model.cultivate.po.promotion.FtbCultivatePromotionPostNew;
import jnpf.permission.PositionApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.BasePositionGradesEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.position.PositionGradesInfoBoundVO;
import jnpf.permission.model.position.PositionInfoNewVO;
import jnpf.permission.model.user.OrganizeInfoVo;
import jnpf.permission.model.user.PositionMoreBoundVO;
import jnpf.permission.model.user.SubordinateUserInfoVO;
import jnpf.permission.model.user.UserBoundMoreInfoVO;
import jnpf.permission.vo.v2.position.PositionAndGradesVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.permission.vo.v2.user.UserPageListVO;
import jnpf.util.UploaderUtil;
import jnpf.yozo.utils.HttpRequestUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * web和app模块组织信息
 *
 * @Author:peng.hao
 * @create: 2024/1/211:31
 */
@RestController
@RequestMapping("/cultivate-org")
public class FtbCultivateOrgController {

    @Autowired
    private UserApi userApi;

    @Autowired
    private UserApiV2Util userApiV2Util;

    @Resource
    private PositionApi positionApi;

    @Resource
    FtbCultivatePromotionPostNewMapper ftbCultivatePromotionPostNewMapper;


    /**
     * 根据用户id 查询当前岗位的信息包含职等信息 岗位详情信息(包含职级)
     */
    @GetMapping("/queryUserSCurrPoInfo")
    public ActionResult<List<FtbPositionGradesInfoBoundVO>> queryUserSCurrentPositionInformation(@RequestParam("userId") String userId,
                                                                                                 @RequestParam("orgId") String orgId) {
        List<FtbPositionGradesInfoBoundVO> list = getNewOrg(userId, orgId);
        return ActionResult.success(list);
    }

    private List<FtbPositionGradesInfoBoundVO> getNewOrg(String userId, String orgId) {
        Map<String, UserBoundVO> userPrimaryBoundBatchCompatible = userApiV2Util.getUserPrimaryBoundBatch(List.of(userId), null);
        UserBoundVO userPrimaryBoundVOS = userPrimaryBoundBatchCompatible.get(userId);
        if (userPrimaryBoundVOS != null) {
            FtbPositionGradesInfoBoundVO ftbPositionGradesInfoBoundVO = this.covertVoNew(userPrimaryBoundVOS);
            if(ftbPositionGradesInfoBoundVO!=null){
                return List.of(ftbPositionGradesInfoBoundVO);
            }
        }
        return null;
    }


    public FtbPositionGradesInfoBoundVO covertVoNew(UserBoundVO userBoundMoreInfoVO) {
        if (userBoundMoreInfoVO == null) {
            return null;
        }
        FtbPositionGradesInfoBoundVO ftbPositionGradesInfoBoundVO = new FtbPositionGradesInfoBoundVO();
        ftbPositionGradesInfoBoundVO.setUserId(userBoundMoreInfoVO.getId());
        ftbPositionGradesInfoBoundVO.setOrganizeId(userBoundMoreInfoVO.getOrganizeId());
        ftbPositionGradesInfoBoundVO.setOrganizeName(userBoundMoreInfoVO.getOrganizeName());
        ftbPositionGradesInfoBoundVO.setPositionId(userBoundMoreInfoVO.getPositionId());
        ftbPositionGradesInfoBoundVO.setPositionName(userBoundMoreInfoVO.getPositionName());
        ftbPositionGradesInfoBoundVO.setPositionGradesId(userBoundMoreInfoVO.getGradeId());
//        ftbPositionGradesInfoBoundVO.setPositionGradesLevel(userBoundMoreInfoVO.get());
        ftbPositionGradesInfoBoundVO.setPositionGradesName(userBoundMoreInfoVO.getGradeName());
//        UserEntity infoById = userApi.getInfoById(userBoundMoreInfoVO.getId());
        ftbPositionGradesInfoBoundVO.setUserName(userBoundMoreInfoVO.getUserName());
        return ftbPositionGradesInfoBoundVO;
    }


    /**
     * 根据用户id   查询当前组织的信息包含所有的岗位信息(当前组织内所有岗位信息)
     */
    @GetMapping("/queryUserOrganizeInfo/{userId}")
    public ActionResult<List<PositionAndGradesVO>> queryUserOrganizeInfo(@PathVariable("userId") String userId) {
        UserBoundVO userPrimaryBoundOne = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        if (userPrimaryBoundOne != null) {
            List<PositionAndGradesVO> positionAndGradesVOS = userApiV2Util.listPositionAndGradesByPositionNameForOrgIds(userPrimaryBoundOne.getOrganizeId(), null);
            return ActionResult.success(positionAndGradesVOS);
        }
//        List<OrganizeInfoVo> byUserId = userApi.getUserOrganizeInfoByUserId(userId);
        return ActionResult.success(new ArrayList<>());
    }

    /**
     * 根据用户id  该用户下属的成员信息
     */
    @GetMapping("/queryUnderlingByUserId")
    public ActionResult<List<FtbCultivatePositionGradeVO>> queryUnderlingByUserId(@RequestParam("userId") String userId,
                                                                                  @RequestParam("orgId") String orgId) {
//        List<SubordinateUserInfoVO> subordinateUserInfoVOS = userApi.userInfoByLeaderId(userId);
        List<UserPageListVO> subordinateUserInfoVOS = userApiV2Util.listUnderlingTargetUser(userId, null);
        List<FtbCultivatePositionGradeVO> list = new ArrayList<>();
        if (subordinateUserInfoVOS != null) {
            //筛选同组织下属

            for (UserPageListVO vo : subordinateUserInfoVOS) {
                if(!vo.getOrganizeId().equals(orgId)){
                    continue;
                }
                FtbCultivatePositionGradeVO newSub = new FtbCultivatePositionGradeVO();
                newSub.setRealName(vo.getName());
                newSub.setUserId(vo.getId());
                newSub.setOrganizeId(vo.getOrganizeId());
                newSub.setHeadIcon(UploaderUtil.uploaderImg(vo.getHeadIcon()));
                newSub.setOrganizeId(vo.getOrganizeId());
                newSub.setOrganizeName(vo.getOrganizeName());
                newSub.setPositionId(vo.getPositionId());
                newSub.setPositionName(vo.getPositionName());

                PositionGradesInfoBoundVO positionMoreBoundVO = new PositionGradesInfoBoundVO();
                positionMoreBoundVO.setUserId(vo.getId());
                positionMoreBoundVO.setOrganizeIds(List.of(vo.getOrganizeId()));
                positionMoreBoundVO.setOrganizeNames(List.of(vo.getOrganizeName()));
                positionMoreBoundVO.setPositionId(vo.getPositionId());
                positionMoreBoundVO.setPositionName(vo.getPositionName());
                positionMoreBoundVO.setPositionGradesId(vo.getGradeId());
                positionMoreBoundVO.setPositionGradesName(vo.getGradeName());
                newSub.setPositionGradesInfoBoundVO(positionMoreBoundVO);
                list.add(newSub);
            }

        }
        return ActionResult.success(list);
    }


    /**
     * 根据用户id和组织id 筛选晋升岗位信息
     */
    @GetMapping("/queryPostInfoByOrgAndUserId")
    public ActionResult<List<PositionInfoNewVO>> queryPostInfoByOrgAndUserId(@RequestParam("userId") String userId,
                                                                             @RequestParam("orgId") String orgId) {
        // 获取用户的岗位职等
        List<FtbPositionGradesInfoBoundVO> orgPositionInfoList = getNewOrg(userId, orgId);
        List<PositionInfoNewVO> result = new LinkedList<>();
        if (CollUtil.isEmpty(orgPositionInfoList)) {
            return ActionResult.success(result);
        }
        Map<String, String> stringStringMap = orgPositionInfoList.stream()
                .collect(
                        Collectors.toMap(FtbPositionGradesInfoBoundVO::getPositionId,
                                FtbPositionGradesInfoBoundVO::getPositionGradesId,
                                (a, b) -> a));
        // 查询当前岗位下的所有岗位加职等
        ActionResult<List<PositionInfoNewVO>> listByOrganizeIds = positionApi.getListByOrganizeIds(orgId);
        if (listByOrganizeIds.getCode() == 200) {
            List<PositionInfoNewVO> data = listByOrganizeIds.getData();
            for (PositionInfoNewVO positionInfoNewVO : data) {
                List<BasePositionGradesEntity> positionGradesList = positionInfoNewVO.getPositionGradesList();
                // 通过岗位ID获取职等id 进行过滤
                String positionGradesId = stringStringMap.get(positionInfoNewVO.getId());
                if (stringStringMap.containsKey(positionInfoNewVO.getId())) {
                    // 通过职等ID过滤已经存在的职等
                    List<BasePositionGradesEntity> newPositionGradesList =
                            positionGradesList.stream().filter(item -> !item.getId().equals(positionGradesId))
                                    .collect(Collectors.toList());

                    if (CollUtil.isNotEmpty(newPositionGradesList)) {
                        positionInfoNewVO.setPositionGradesList(null);
                        positionInfoNewVO.setPositionGradesList(newPositionGradesList);
                        // 过滤已存在的
                        result.add(positionInfoNewVO);
                    }
                } else {
                    // 封装每一个不存在的岗位
                    result.add(positionInfoNewVO);
                }
            }
        }
        return ActionResult.success(result);
    }

    /**
     * 岗位详情信息查询
     */
    @GetMapping("/getInfoNew")
    public ActionResult<PositionInfoNewVO> getInfoNew(@RequestParam("postId") String postId) throws Exception {
        ActionResult<PositionInfoNewVO> infoNew = positionApi.getInfoNew(postId);
        if (infoNew.getCode() == 200) {
            return ActionResult.success(infoNew.getData());
        }
        return ActionResult.fail("该岗位没有职等");
    }

    /**
     * 获取岗位信息列表过滤初始岗位
     *
     * @return
     */
    @GetMapping("/getLearnMapFilterInformation")
    public ActionResult<List<PositionInfoNewVO>> getLearnMapFilterInformation() {
        ActionResult<List<PositionInfoNewVO>> result = positionApi.allInfoList();
        if (result != null && result.getCode() != 200) {
            return ActionResult.fail("获取岗位信息失败");
        }
        LambdaQueryWrapper<FtbCultivatePromotionPostNew> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(FtbCultivatePromotionPostNew::getLevel, "1");
        List<FtbCultivatePromotionPostNew> postNews = ftbCultivatePromotionPostNewMapper.selectList(lambdaQuery);
        if (CollUtil.isNotEmpty(postNews)) {
            List<String> postIds = postNews.stream().map(FtbCultivatePromotionPostNew::getPostId).collect(Collectors.toList());
            List<PositionInfoNewVO> data = result.getData();
            // data = data.stream().filter(item->!postIds.contains(item.getId())).collect(Collectors.toList());
            return ActionResult.success(data);
        }
        return ActionResult.success(result.getData());
    }
}
