package jnpf.attendance.antifreeze;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import jnpf.authority.FtbAuthorityApi;
import jnpf.base.ActionResult;
import jnpf.file.FileUploadApi;
import jnpf.model.personnels.dto.staff.roster.FtbPersonnelsStaffRosterDto;
import jnpf.model.personnels.dto.staff.roster.WorkerGroupDataDto;
import jnpf.model.personnels.req.roster.StaffRosterListReq;
import jnpf.permission.V2UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.eum.v2.UserWorkStatusEnums;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.permission.vo.v2.user.UserBoundInfoVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.FtbPersonnelsRosterManagerApi;
import jnpf.util.StringUtil;
import jnpf.util.UploaderUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UserAntifreeze {
    @Resource
    private V2UserApi v2UserApi;
    @Resource
    private FileUploadApi fileUploadApi;
    @Resource
    private FtbAuthorityApi ftbAuthorityApi;
    @Resource
    private FtbPersonnelsRosterManagerApi managerApi;

    /**
     * 请求用户服务接口
     *
     * @param userIds 用户ID集合
     * @return 用户信息
     */
    public List<PartUserInfoVo> getInfoByIds(List<String> userIds, String tenantId) {
        List<PartUserInfoVo> infoByIds = CollUtil.newArrayList();
        try {
            ActionResult<List<UserBoundVO>> userList = v2UserApi.getAllUserInfoBatch(userIds, tenantId);
            if (200 == userList.getCode() && CollectionUtil.isNotEmpty(userList.getData())) {
                infoByIds = getPartUserInfoVos(userList.getData());
            }
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return infoByIds;
    }

    /**
     * 请求用户服务接口
     *
     * @param orgId 组织ID
     * @param workGroupId 班组ID
     * @return 用户信息
     */
    public List<UserBoundVO> getInfoByIds(String orgId, String workGroupId) {
        List<UserBoundVO> userBoundVoList = ftbAuthorityApi.listTargetOrganizeIdAuthApi(orgId,
                List.of(UserWorkStatusEnums.NONE));
        if (StringUtil.isEmpty(workGroupId)) {
            return userBoundVoList;
        }
        return userBoundVoList.stream().filter(vo -> StringUtil.equals(vo.getStoreTeamId(), workGroupId)).collect(Collectors.toList());
    }

    /**
     * 请求用户服务接口
     *
     * @param orgIds 组织ID集合
     * @param workStatusEnums 用户工作状态
     * @return 用户信息
     */
    public List<UserBoundVO> batchGetInfoByIds(List<String> orgIds, List<UserWorkStatusEnums> workStatusEnums) {
        return ftbAuthorityApi.listTargetOrganizeIdsAuthApi(orgIds,
                UserWorkStatusEnums.getDifferenceEnumsFromBase(workStatusEnums));
    }

    /**
     * 请求用户服务接口
     *
     * @param userIds 用户ID集合
     * @return 用户信息
     */
    public List<PartUserInfoVo> getStaffRosterListInfoByIds(List<String> userIds) {
        List<PartUserInfoVo> infoByIds = CollUtil.newArrayList();
        try {
            StaffRosterListReq req = new StaffRosterListReq();
            req.setUserIds(userIds);
            req.setIsQueryAuth("0");
            List<FtbPersonnelsStaffRosterDto> userBoundVos = managerApi.postWithSalaryNoPage(req);
            infoByIds = getStaffRosterVos(userBoundVos);
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return infoByIds;
    }

    private List<PartUserInfoVo> getStaffRosterVos(List<FtbPersonnelsStaffRosterDto> userBoundVos) {
        List<PartUserInfoVo> infoByIds;
        if (CollUtil.isEmpty(userBoundVos)) {
            return CollUtil.newArrayList();
        }
        infoByIds = userBoundVos.stream().map(x -> {
            PartUserInfoVo bean = BeanUtil.toBean(x, PartUserInfoVo.class);
            bean.setUserId(x.getUserId());
            bean.setRealName(StringUtil.isNotEmpty(x.getName()) ? x.getName() : "");
            bean.setMobilePhone(StringUtil.isNotEmpty(x.getPhone()) ? x.getPhone() : "");
            bean.setWorkerStatus(Objects.nonNull(x.getWorkerStatus()) ? x.getWorkerStatus() : "");
            bean.setHeadIcon(StringUtil.isNotEmpty(x.getHeadLogo()) ? fileUploadApi.getHeadIcon(UploaderUtil.uploaderImg(x.getHeadLogo())) : "");
            if(CollUtil.isNotEmpty(x.getOrgList())){
                WorkerGroupDataDto groupDataDto = x.getOrgList().stream().findFirst().orElse(null);
                if(Objects.nonNull(groupDataDto)){
                    bean.setOrganizeName(groupDataDto.getAffiliatedOrgName());
                    bean.setOrganizeId(groupDataDto.getAffiliatedOrg());
                    bean.setPositionId(groupDataDto.getAffiliatedPosition());
                    bean.setPositionName(groupDataDto.getAffiliatedPositionName());
                }
//                Optional.ofNullable(groupDataDto).ifPresent(groupDataDto1 -> {
//                    bean.setOrganizeName(groupDataDto1.getAffiliatedOrgName());
//                    bean.setOrganizeId(groupDataDto1.getAffiliatedOrg());
//                    bean.setPositionId(groupDataDto1.getAffiliatedPosition());
//                    bean.setPositionName(groupDataDto1.getAffiliatedPositionName());
//                });
            }
            return bean;
        }).collect(Collectors.toList());
        return infoByIds;
    }

    /**
     * 请求用户服务接口
     *
     * @param userIds 用户ID集合
     * @return 用户信息
     */
    public List<PartUserInfoVo> getInfoByIdsManyAndCopyPost(List<String> userIds, String tenantId) {
        List<PartUserInfoVo> infoByIds = CollUtil.newArrayList();
        try {
            List<UserBoundVO> userBoundVos = v2UserApi.userListAndCopy(userIds, null, tenantId);
            infoByIds = getPartUserInfoVos(userBoundVos);
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return infoByIds;
    }

    /**
     * 请求用户服务接口
     *
     * @param userIds 用户ID集合
     * @return 用户信息
     */
    public List<PartUserInfoVo> getAllByIds(List<String> userIds, String tenantId) {
        List<PartUserInfoVo> infoByIds = CollUtil.newArrayList();
        try {
            ActionResult<List<UserBoundVO>> userList = v2UserApi.getAllUserInfoBatch(userIds, tenantId);
            if (200 == userList.getCode() && CollectionUtil.isNotEmpty(userList.getData())) {
                infoByIds = getPartUserInfoVos(userList.getData());
            }
            if (CollUtil.isEmpty(infoByIds)) {
                List<UserBoundVO> userBoundVos = v2UserApi.userListAndCopy(userIds, true, tenantId);
                infoByIds = getPartUserInfoVos(userBoundVos);
                return infoByIds;
            }
            if (infoByIds.size() < userIds.size()) {
                List<String> collect = infoByIds.stream().map(PartUserInfoVo::getUserId).collect(Collectors.toList());
                userIds = userIds.stream().filter(userId -> !collect.contains(userId)).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(userIds)) {
                    List<UserBoundVO> userBoundVos = v2UserApi.userListAndCopy(userIds, true, tenantId);
                    List<PartUserInfoVo> partUserInfoVos = getPartUserInfoVos(userBoundVos);
                    infoByIds.addAll(partUserInfoVos);
                }
            }
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return infoByIds;
    }

    @NotNull
    private List<PartUserInfoVo> getPartUserInfoVos(List<UserBoundVO> userList) {
        List<PartUserInfoVo> infoByIds;
        if (CollUtil.isEmpty(userList)) {
            return CollUtil.newArrayList();
        }
        infoByIds = userList.stream().map(x -> {
            PartUserInfoVo bean = BeanUtil.toBean(x, PartUserInfoVo.class);
            bean.setUserId(x.getId());
            bean.setRealName(StringUtil.isNotEmpty(x.getUserName()) ? x.getUserName() : "");
            bean.setMobilePhone(StringUtil.isNotEmpty(x.getPhone()) ? x.getPhone() : "");
            bean.setWorkerStatus(Objects.nonNull(x.getWorkStatusEnums()) ? x.getWorkStatusEnums().getCode() : "");
            bean.setHeadIcon(StringUtil.isNotEmpty(x.getHeadIcon()) ? fileUploadApi.getHeadIcon(UploaderUtil.uploaderImg(x.getHeadIcon())) : "");
            return bean;
        }).collect(Collectors.toList());
        return infoByIds;
    }

    @NotNull
    private List<UserEntity> getUserInfoVos(List<UserBoundVO> userList) {
        if (CollUtil.isEmpty(userList)) {
            return CollUtil.newArrayList();
        }
        return userList.stream().map(x -> {
            UserEntity bean = BeanUtil.toBean(x, UserEntity.class);
            bean.setId(x.getId());
            bean.setRealName(x.getUserName());
            bean.setMobilePhone(x.getPhone());
            bean.setHeadIcon(fileUploadApi.getHeadIcon(UploaderUtil.uploaderImg(x.getHeadIcon())));
            return bean;
        }).collect(Collectors.toList());
    }

    /**
     * 请求用户服务接口
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    public PartUserInfoVo getInfo(String userId, String tenantId) {
        try {
            List<PartUserInfoVo> infoByIds = getAllByIds(CollUtil.newArrayList(userId), tenantId);
            if (CollUtil.isEmpty(infoByIds)) {
                return null;
            }
            return infoByIds.get(0);
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return null;
    }

    /**
     * 请求用户服务接口
     *
     * @param userIds 用户ID集合
     * @return 用户信息
     */
    public List<UserEntity> getInfoByIds(List<String> userIds) {
        List<UserEntity> infoByIds = CollUtil.newArrayList();
        try {
            List<UserBoundVO> userBoundVos = v2UserApi.userListAndCopy(userIds, false, null);
            infoByIds = getUserInfoVos(userBoundVos);
            if (CollUtil.isEmpty(infoByIds)) {
                return CollUtil.newArrayList();
            }
            infoByIds.stream().filter(Objects::nonNull).filter(user -> StringUtil.isNotEmpty(user.getHeadIcon())).forEach(user -> user.setHeadIcon(fileUploadApi.getHeadIcon(UploaderUtil.uploaderImg(user.getHeadIcon()))));
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return infoByIds;
    }


    /**
     * 请求用户服务接口
     *
     * @param userId 用户ID
     * @return 用户信息
     */
    public UserEntity getInfo(String userId) {
        try {
            ActionResult<UserBoundInfoVO> usersBound = v2UserApi.getUsersBound(userId, null);
            if (200 == usersBound.getCode() && null != usersBound.getData()) {
                UserEntity infoById = BeanUtil.copyProperties(usersBound.getData(), UserEntity.class);
                infoById.setRealName(usersBound.getData().getUserName());
                return infoById;
            }
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return null;
    }

    /**
     * 请求用户服务接口
     *
     * @param keyword 关键字
     * @return 用户信息
     */
    public List<UserEntity> getInfoByLikeName(String keyword) {
        List<UserEntity> infoByIds = CollUtil.newArrayList();
        if (StringUtil.isEmpty(keyword)) {
            return infoByIds;
        }
        try {
            List<UserBoundVO> userBoundVos = v2UserApi.userListAndCopyLikeName(keyword, null, null);
            infoByIds = getUserInfoVos(userBoundVos);
        } catch (Exception e) {
            log.error("用户接口请求失败：", e);
        }
        return infoByIds;
    }


}
