package jnpf.personnels.service.impl;

import jnpf.authority.utils.PermissionsUtils;
import jnpf.base.ActionResult;
import jnpf.model.personnels.po.FtbPersonnelsStaffEmploymentApply;
import jnpf.model.personnels.vo.mcp.OnboardingThisMonthStatsVO;
import jnpf.model.personnels.vo.mcp.StaffBirthdayVO;
import jnpf.model.personnels.vo.mcp.StaffNotSignContractVO;
import jnpf.permission.V2UserApi;
import jnpf.permission.eum.v2.UserWorkStatusEnums;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.personnels.mapper.FtbPersonStaffMCPMapper;
import jnpf.personnels.mapper.FtbPersonnelsStaffEmploymentApplyMapper;
import jnpf.personnels.service.FtbPersonStaffMCPService;
import jnpf.personnels.service.FtbPersonnelsBlacklistService;
import jnpf.util.UserProvider;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class FtbPersonStaffMCPServiceImpl implements FtbPersonStaffMCPService {

    @Resource
    private FtbPersonnelsStaffEmploymentApplyMapper ftbPersonnelsStaffEmploymentApplyMapper;

    @Resource
    private FtbPersonStaffMCPMapper ftbPersonStaffMCPMapper;

    @Resource
    private V2UserApi v2UserApi;

    @Resource
    private FtbPersonnelsBlacklistService ftbPersonnelsBlacklistService;

    @Autowired
    PermissionsUtils permissionsUtils;

    @Override
    public List<FtbPersonnelsStaffEmploymentApply> getSubmittedButNotOnboarded() {
        List<String> userIds = getUserIds();
        if (userIds != null && userIds.isEmpty()) return new ArrayList<>();
        return ftbPersonnelsStaffEmploymentApplyMapper.getSubmittedButNotOnboarded(userIds);
    }

    @Override
    public OnboardingThisMonthStatsVO getOnboardingThisMonthStats(String startTime, String endTime) {
        List<String> userIds = getUserIds();
        if (userIds != null && userIds.isEmpty()) return new OnboardingThisMonthStatsVO();
        OnboardingThisMonthStatsVO vo = new OnboardingThisMonthStatsVO();
        Long created = ftbPersonnelsStaffEmploymentApplyMapper.getCountEmploymentApplyCreatedInPeriod(startTime, endTime,userIds);
        Long completed = ftbPersonnelsStaffEmploymentApplyMapper.getCountEmploymentApplyToRosterInPeriod(startTime, endTime,userIds);
        vo.setNewEmployeesThisMonth(created != null ? created : 0L);
        vo.setCompletedOnboardingThisMonth(completed != null ? completed : 0L);
        return vo;
    }

    @Nullable
    private List<String> getUserIds() {
        List<String> userIds = null;
        Boolean isAdministrator = UserProvider.getUser().getIsAdministrator();
        if (!isAdministrator) {
            List<UserWorkStatusEnums> workStatusEnums = Arrays.stream(UserWorkStatusEnums.values()).filter(v -> v.getCode().equals(UserWorkStatusEnums.RESIGNED.getCode())).collect(Collectors.toList());
            userIds = permissionsUtils.getPersonnelUserIdDataPermissions(UserProvider.getUser().getUserId(), workStatusEnums);
        }
        return userIds;
    }

    @Override
    public List<FtbPersonnelsStaffEmploymentApply> getListOfNotSubmittedForm() {
        List<String> userIds = getUserIds();
        if (userIds != null && userIds.isEmpty()) return new ArrayList<>();
        return ftbPersonnelsStaffEmploymentApplyMapper.getListOfNotSubmittedForm(userIds);
    }

    /**
     * 查询本月生日的员工列表
     * @return 本月生日员工列表（包含姓名、组织、岗位）
     */
    @Override
    public List<StaffBirthdayVO> getStaffBirthdayList() {
        LocalDate now = LocalDate.now();
        int month = now.getMonthValue();
        String startBirthdayTime = String.format("%02d-01", month);
        String endBirthdayTime = String.format("%02d-31", month);
        List<String> userIdPermissions = null;
        if (!UserProvider.getUser().getIsAdministrator()) {
            userIdPermissions = permissionsUtils.getPersonnelUserIdDataPermissions(UserProvider.getUser().getUserId(), null);
        }
        List<StaffBirthdayVO> list = ftbPersonStaffMCPMapper.getStaffBirthdayList(startBirthdayTime, endBirthdayTime,userIdPermissions);
        // 用户Id集合
        List<String> userIds = list.stream().map(StaffBirthdayVO::getUserId).collect(Collectors.toList());
        ActionResult<List<UserBoundVO>> allUserInfoBatch = v2UserApi.getAllUserInfoBatch(userIds, null);
        // 判断是否获取成功
        if (allUserInfoBatch.getData() != null) {
            List<UserBoundVO> userList = allUserInfoBatch.getData();
            Map<String, UserBoundVO> userBoundVOMap = userList.stream().collect(Collectors.toMap(UserBoundVO::getId, Function.identity()));
            // 将用户信息填充到列表中
            for (StaffBirthdayVO staffBirthdayVO : list) {
                UserBoundVO userBoundVO = userBoundVOMap.get(staffBirthdayVO.getUserId());
                // 判断是否为空，并设置姓名、岗位、组织
                if (userBoundVO != null) {
                    staffBirthdayVO.setName(userBoundVO.getName());
                    staffBirthdayVO.setPositionName(userBoundVO.getPositionName());
                    staffBirthdayVO.setOrgName(userBoundVO.getOrganizeName());
                }
            }
        }
        return list;
    }

    /**
     * 根据手机号查询是否在黑名单中
     * @param phone 手机号
     * @return true为在黑名单中，false为不在黑名单中
     */
    @Override
    public Boolean isInBlacklist(String phone) {
        return ftbPersonnelsBlacklistService.hasItBeenBlacklisted(phone);
    }

    @Override
    public List<StaffNotSignContractVO> getListNotSignedContractHalfMonth() {
        List<StaffNotSignContractVO> list = ftbPersonStaffMCPMapper.getListNotSignedContractHalfMonth();
        if (list == null || list.isEmpty()) {
            return list;
        }
        // 用户Id集合
        List<String> userIds = list.stream().map(StaffNotSignContractVO::getUserId).collect(Collectors.toList());
        ActionResult<List<UserBoundVO>> allUserInfoBatch = v2UserApi.getAllUserInfoBatch(userIds, null);
        // 判断是否获取成功
        if (allUserInfoBatch.getData() != null) {
            List<UserBoundVO> userList = allUserInfoBatch.getData();
            Map<String, UserBoundVO> userBoundVOMap = userList.stream().collect(Collectors.toMap(UserBoundVO::getId, Function.identity()));
            // 将用户信息填充到列表中
            for (StaffNotSignContractVO vo : list) {
                UserBoundVO userBoundVO = userBoundVOMap.get(vo.getUserId());
                if (userBoundVO != null) {
                    vo.setName(userBoundVO.getName());
                    vo.setPositionName(userBoundVO.getPositionName());
                    vo.setOrgName(userBoundVO.getOrganizeName());
                }
            }
        }
        return list;
    }

}
