package jnpf.personnels.utils;

import cn.hutool.json.JSONUtil;
import jnpf.base.ActionResult;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.model.enums.GrowthLogEnum;
import jnpf.model.personnels.dto.regular.FtbPersonnelsRegularCreateDTO;
import jnpf.model.personnels.dto.staff.growth.AddGrowthLogDto;
import jnpf.model.personnels.dto.staff.registerform.ProbationPeriodDto;
import jnpf.model.personnels.dto.staff.roster.StaffBaseInfoDto;
import jnpf.model.personnels.po.FtbPersonnelsRegistrationFormField;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.permission.OrganizeApi;
import jnpf.permission.PositionApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.PositionEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.position.PositionGradesInfoVO;
import jnpf.personnels.service.FtbPersonnelsRegularManagementService;
import jnpf.personnels.service.FtbPersonnelsStaffGrowthLogService;
import jnpf.personnels.service.FtbPersonnelsStaffRegistrationFormDataService;
import jnpf.personnels.service.FtbPersonnelsStaffSalaryChangeLogService;
import jnpf.utils.FeignHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class PersonnelAsyncImportUtils {

    @Autowired
    @Lazy
    private FtbPersonnelsStaffSalaryChangeLogService salaryChangeLogService;

    @Autowired
    @Lazy
    private PersonnelOrgUtils personnelOrgUtils;

    @Autowired
    @Lazy
    private FtbPersonnelsStaffGrowthLogService growthLogService;

    @Autowired
    @Lazy
    private OrganizeApi organizeApi;

    @Autowired
    @Lazy
    private PositionApi positionApi;

    @Autowired
    @Lazy
    private UserApi userApi;

    @Autowired
    @Lazy
    private FtbPersonnelsRegularManagementService regularManagementService;

    @Autowired
    @Lazy
    private FtbPersonnelsStaffRegistrationFormDataService registrationFormDataService;

    @Async
    public void asyncUpdateFormData(Map<String, Object> formDataMap, String phone, String rosterId, Map<String, FtbPersonnelsRegistrationFormField> allFormFieldListMap, String tenantCode, Map<String, String> headers) {

        try {
            FeignHolder.set(headers);
            TenantDataSourceUtil.switchTenant(tenantCode);
            registrationFormDataService.importSyncData(formDataMap, phone, rosterId, allFormFieldListMap);
        } catch (Exception e) {
            log.error("异步处理组织岗位异常");
        } finally {
            FeignHolder.clear();
        }
    }

    @Async
    public void asyncDealImportRosterOtherData(FtbPersonnelsStaffRoster entity, ProbationPeriodDto probationPeriodDto, String tenantCode, Map<String, String> headers) {
        try {
            TenantDataSourceUtil.switchTenant(tenantCode);
            //员工成长
            AddGrowthLogDto addGrowthLogDto = new AddGrowthLogDto();
            addGrowthLogDto.setUserId(entity.getUserId());
            addGrowthLogDto.setChangeDate(new Date());
            if (entity.getJoinNum() > 1) {
                addGrowthLogDto.setGrowthType(GrowthLogEnum.REPEAT_JOIN.getCode());
                addGrowthLogDto.setNum(entity.getJoinNum());
            } else {
                addGrowthLogDto.setGrowthType(GrowthLogEnum.FIRST_JOIN.getCode());
            }
            // 添加导入实际入职日期
            addGrowthLogDto.setDetail(buildGrowthLogDetail(entity.getCurrOrg(), entity.getCurrPosition(), entity.getCurrRank(), entity.getCurrReportsTo(),entity.getActualStartDate()));
            addGrowthLogDto.setStartSalary(entity.getEntrySalary());
            addGrowthLogDto.setActualStartDate(entity.getActualStartDate());
            addGrowthLogDto.setEmployeeId(entity.getSystemWokerId());
            // 导入的
            growthLogService.addGrowthLog(addGrowthLogDto);

            //同步状态到内推池子
            personnelOrgUtils.sysWorkerStatusToUchisuike(entity.getPhone(), entity.getWorkerStatus());

            // 过滤为试用员工
            // 同步转正管理
            // 302、试用
            if (("302".equals(entity.getWorkerStatus())
                    || "306".equals(entity.getWorkerStatus())) && !probationPeriodDto.getType().equals("100")) {
                syncRegular(entity, probationPeriodDto.getType(), probationPeriodDto.getDays(), entity.getCurrReportsTo());
            }
            FeignHolder.sendFeign(headers, () -> {
                personnelOrgUtils.updateBaseInfoForBaseUser(entity);
                return null;
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异步导入花名册异常");
        } finally {
            FeignHolder.clear();
        }
    }

    private String buildGrowthLogDetail(String currOrg, String currPosition, String currRank, String currReportsTo, Date actualStartDate) {
        StaffBaseInfoDto dto = new StaffBaseInfoDto();
        dto.setCurrOrg(currOrg);
        dto.setCurrPosition(currPosition);
        dto.setCurrRank(currRank);
        dto.setReportsTo(currReportsTo);
        personnelOrgUtils.fillOrgNameById(dto);
        personnelOrgUtils.fillPositionNameById(dto);
        personnelOrgUtils.fillRankNameById(dto);
        UserEntity userEntity = personnelOrgUtils.queryUserInfo(currReportsTo);
        if (null != userEntity) {
            dto.setReportsToName(userEntity.getRealName());
        }
        dto.setActualStartDate(actualStartDate);
        return JSONUtil.toJsonStr(dto);
    }

    /**
     * 同步转正管理
     *
     * @param entity
     * @param probationPeriod
     * @param probationPeriodDay
     * @param currReportsTo
     */
    private void syncRegular(FtbPersonnelsStaffRoster entity,
                             String probationPeriod,
                             String probationPeriodDay,
                             String currReportsTo) {
        try {
            FtbPersonnelsRegularCreateDTO createDTO = FtbPersonnelsRegularCreateDTO.coverFtbPersonnelsRegularInfoVO(entity);
            OrganizeEntity infoById = organizeApi.getInfoById(createDTO.getOrgId());
            createDTO.setOrgName(infoById.getFullName());
            UserEntity userEntity = StringUtils.isEmpty(currReportsTo) ? null : userApi.getInfoById(currReportsTo);
            if (userEntity != null) {
                createDTO.setImmediateSuperName(userEntity.getRealName());
                createDTO.setImmediateSuperId(currReportsTo);
            }
            PositionEntity positionEntity = positionApi.queryInfoById(createDTO.getRegularPostId());
            createDTO.setRegularPostName(positionEntity.getFullName());
            createDTO.setOnboardPostName(positionEntity.getFullName());
            ActionResult<PositionGradesInfoVO> gradesInfo = positionApi.getGradesInfo(createDTO.getRegularGradeId());
            if (gradesInfo != null && gradesInfo.getData() != null) {
                createDTO.setRegularGradeName(gradesInfo.getData().getFullName());
                createDTO.setOnboardGradeName(gradesInfo.getData().getFullName());
            }
            calculatePlannedConversionTime(probationPeriod, probationPeriodDay, entity, createDTO);
            createDTO.setId(entity.getId());
            regularManagementService.applyForRegularization(createDTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 计算计划转正时间
     *
     * @param probationPeriod    是否是天
     * @param probationPeriodDay 时间
     * @param entity
     * @param createDTO
     */
    private void calculatePlannedConversionTime(String probationPeriod,
                                                String probationPeriodDay,
                                                FtbPersonnelsStaffRoster entity,
                                                FtbPersonnelsRegularCreateDTO createDTO) {
        // 入职日期
        Date actualStartDate = entity.getActualStartDate();
        int probation = 0;
        // 创建一个 Calendar 实例并设置为当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(actualStartDate);
        if ("101".equals(probationPeriod)) {
            // 这里就是天数
            createDTO.setProbationPeriodDay(probationPeriodDay);
            calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(probationPeriodDay));
        } else {
            switch (probationPeriod) {
                case "102":
                    probation = 1;
                    break;
                case "103":
                    probation = 2;
                    break;
                case "104":
                    probation = 3;
                    break;
                case "105":
                    probation = 4;
                    break;
                case "106":
                    probation = 5;
                    break;
                case "107":
                    probation = 6;
                    break;
                case "108":
                    probation = 7;
                    break;
                case "109":
                    probation = 8;
                    break;
            }
            calendar.add(Calendar.MONTH, probation);
        }
        Date time = calendar.getTime();
        createDTO.setProbation(probationPeriod);
        // 计算实际转正时间
        createDTO.setSchedConverDate(time);
    }

}



