package jnpf.personnels.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.model.personnels.dto.staff.roster.WorkerGroupDataDto;
import jnpf.model.personnels.po.FtbPersonnelsTurnoverManagement;
import jnpf.model.personnels.vo.roster.FtbThousandFacePersonVO;
import jnpf.personnels.mapper.FtbPersonnelsRegularManagementMapper;
import jnpf.personnels.mapper.FtbPersonnelsStaffEmploymentApplyMapper;
import jnpf.personnels.mapper.FtbPersonnelsTurnoverManagementMapper;
import jnpf.personnels.mapper.FtbThousandFacePersonMapper;
import jnpf.personnels.service.FtbThousandFacePersonService;
import jnpf.personnels.utils.PersonnelPerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FtbThousandFacePersonServiceImpl implements FtbThousandFacePersonService {

    @Resource
    private FtbThousandFacePersonMapper ftbThousandFacePersonMapper;

    @Resource
    private FtbPersonnelsTurnoverManagementMapper ftbPersonnelsTurnoverManagementMapper;

    @Resource
    private FtbPersonnelsRegularManagementMapper ftbPersonnelsRegularManagementMapper;

    @Resource
    private FtbPersonnelsStaffEmploymentApplyMapper ftbPersonnelsStaffEmploymentApplyMapper;

    @Autowired
    private PersonnelPerUtils personnelPerUtils;

    // 在职状态
    private static final List<String> ON_THE_JOB_STATUS = List.of("302", "303", "304", "306");

    @Override
    public FtbThousandFacePersonVO getPersonnelData() {
        List<String> userIds = selectedOrganizationAndPositionEmployees();
        FtbThousandFacePersonVO ftbThousandFacePersonVO = new FtbThousandFacePersonVO();
        // 花名册在职员工
        Long employeeNum = ftbThousandFacePersonMapper.getEmployeeNum(ON_THE_JOB_STATUS, userIds);
        ftbThousandFacePersonVO.setEmployeeNum(employeeNum);
        // 调岗员工数量
        Long turnoverNum = ftbThousandFacePersonMapper.getTurnoverAllPeople(userIds);
        ftbThousandFacePersonVO.setTurnoverNum(turnoverNum);
        //离职
        List<String> stringList = doEmployeesOfYourOrganization();
        Long lastInstallment = ftbPersonnelsTurnoverManagementMapper.getLeaveAllPeople(userIds);
        Long leaveNum =  ftbPersonnelsTurnoverManagementMapper.getTurnoverRateAndHeadcount(stringList);
        ftbThousandFacePersonVO.setLeaveNum(lastInstallment);
        ftbThousandFacePersonVO.setLeaveRate(calculateTheScale(lastInstallment, leaveNum));
        //转正
        Long regularNum = ftbPersonnelsRegularManagementMapper.queryNumberOfRegulars(userIds);
        ftbThousandFacePersonVO.setRegularNum(regularNum);
        //入职
        List<String> orgIds = selectedOrganization();
        Long onboardingNum = ftbPersonnelsStaffEmploymentApplyMapper.queryNumberOfOnboardedEmployees(orgIds);
        ftbThousandFacePersonVO.setOnboardingNum(onboardingNum);
        return ftbThousandFacePersonVO;
    }


    /**
     * 获取人事用户数据权限，返回为空，则表示为超级管理员（可以查询所有数据）
     */
    private List<String> selectedOrganizationAndPositionEmployees() {
        return personnelPerUtils.obtainPersonnelDataPermissions();
    }

    private List<String> selectedOrganization() {
        return  personnelPerUtils.obtainPersonnelOrganizationIdDataPermissions();
    }

    /**
     * 离职人员数据权限
     * @return
     */
    private List<String> doEmployeesOfYourOrganization() {
        List<String> orgIds = personnelPerUtils.obtainPersonnelOrganizationIdDataPermissions();
        if (CollUtil.isNotEmpty(orgIds)) {
            LambdaQueryWrapper<FtbPersonnelsTurnoverManagement> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(FtbPersonnelsTurnoverManagement::getEnableMark, 0);
            List<FtbPersonnelsTurnoverManagement> managements = ftbPersonnelsTurnoverManagementMapper.selectList(wrapper);
            if (CollUtil.isNotEmpty(orgIds))
                return managements.stream().filter(vo -> StringUtils.isNotEmpty(vo.getOrganizationInfo()))
                        .filter(vo -> CollUtil.isNotEmpty(JSONObject.parseArray(vo.getOrganizationInfo(), WorkerGroupDataDto.class)
                                .stream().map(WorkerGroupDataDto::getAffiliatedOrg).collect(Collectors.toList()).stream().filter(orgIds::contains).collect(Collectors.toList()))
                        ).map(FtbPersonnelsTurnoverManagement::getId).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 比率计算
     * @return
     */
    private BigDecimal calculateTheScale(Object a, Object b) {
        if (a == null || b == null) {
            return BigDecimal.ZERO;
        }
        // a/b 除数为0
        if (b instanceof Integer) {
            Integer b0 = (Integer) b;
            if (b0 == 0) {
                return BigDecimal.ZERO;
            }
        }
        if (b instanceof Long) {
            Long b0 = (Long) b;
            if (b0 == 0) {
                return BigDecimal.ZERO;
            }
        }
        if (b instanceof BigDecimal) {
            if (((BigDecimal) b).compareTo(BigDecimal.ZERO) == 0) {
                return BigDecimal.ZERO;
            }
        }
        BigDecimal a0 = new BigDecimal(String.valueOf(a));
        BigDecimal b0 = new BigDecimal(String.valueOf(b));
        return a0.divide(b0, 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
    }

}
