package com.yifu.cloud.plus.v1.business.service.vacation.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.business.dto.vacation.AddOrSaveVacationRuleDTO;
import com.yifu.cloud.plus.v1.business.entity.vacation.TVacationRuleConfig;
import com.yifu.cloud.plus.v1.business.mapper.vacation.TVacationRuleConfigMapper;
import com.yifu.cloud.plus.v1.business.service.vacation.TVacationRuleConfigService;
import com.yifu.cloud.plus.v1.business.vo.vacation.VacationRuleConfigVO;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.BigDecimalUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

/**
 * @description: 假期配置 service实现层
 * @author: huyc
 * @date: 2023/1/13
 */
@Service
public class TVacationRuleConfigServiceImpl extends ServiceImpl<TVacationRuleConfigMapper, TVacationRuleConfig>
implements TVacationRuleConfigService {

    public static final Integer YEAR = 365;

    /**
     * @description: 获取年假配置规则
     * @return: com.yifu.cloud.v1.common.core.util.R<com.yifu.cloud.v1.hrobusiness.api.vo.vacation.VacationRuleConfigVO>
	 * @author: huyc
	 * @date: 2023/1/13
     */
    @Override
    public R<VacationRuleConfigVO> getVacationRuleConfig() {
        TVacationRuleConfig tVacationRuleConfig = this.lambdaQuery()
                .eq(TVacationRuleConfig::getType, CommonConstants.ONE_STRING).last(CommonConstants.LAST_ONE_SQL).one();
        VacationRuleConfigVO vo = new VacationRuleConfigVO();
        vo = TVacationRuleConfig.entityConvertToObj(vo, tVacationRuleConfig);
        return R.ok(vo,"查询成功");
    }

    /**
     * @description:
     * @param user
     * @param dto
     * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 * @author: huyc
	 * @date: 2023/1/13
     */
    @Override
    public R<Boolean> addOrSave(YifuUser user, AddOrSaveVacationRuleDTO dto) {
        TVacationRuleConfig tVacationRuleConfig = TVacationRuleConfig.objConvertToEntity(dto);
        TVacationRuleConfig entity = this.lambdaQuery().eq(TVacationRuleConfig::getType, tVacationRuleConfig.getType()).one();
        if (null == entity) {
            // 新增
            tVacationRuleConfig.setCreateTime(LocalDateTime.now());
            tVacationRuleConfig.setCreateUserId(String.valueOf(user.getId()));
        } else {
            // 更新
            if (null == tVacationRuleConfig.getId()) {
                return R.failed("数据校验失败：更新状态下id不能为空");
            }
            tVacationRuleConfig.setUpdateTime(LocalDateTime.now());
            tVacationRuleConfig.setUpdateUserId(String.valueOf(user.getId()));
        }
        boolean isSuccess = this.saveOrUpdate(tVacationRuleConfig);
        if (isSuccess) {
            return R.ok(true,"操作成功");
        }
        return R.failed(false,"操作失败");
    }

    /**
     * @description: 根据入职时间返回年假天数
     * @param enjoinDate 入职时间
     * @return: java.lang.Integer 年假天数
     * @author: huyc
     * @date: 2023/1/13
     */
    @Override
    public Integer annualLeaveCalculationFormula(LocalDateTime enjoinDate) {
        LocalDateTime now = LocalDateTime.now();
        // 当前距离入职天数
        long offsetDays = Duration.between(enjoinDate, now).toDays();
        // 入职满一年的时间
        LocalDateTime enjoinOnYear = enjoinDate.plus(YEAR, ChronoUnit.DAYS);

        LocalDateTime oneYear = enjoinDate.plus(YEAR, ChronoUnit.DAYS).with(TemporalAdjusters.lastDayOfYear());
        LocalDateTime tenYear = enjoinDate.plus(10L * YEAR, ChronoUnit.DAYS).with(TemporalAdjusters.lastDayOfYear());
        LocalDateTime twentyYear = enjoinDate.plus(20L * YEAR, ChronoUnit.DAYS).with(TemporalAdjusters.lastDayOfYear());

        // 入职满一年距离下次1月1日
        long lastDay = Duration.between(enjoinOnYear, oneYear).toDays();

        if (offsetDays>= YEAR && now.isBefore(oneYear)) {
            // 入职=1年，年假天数=（年末-当前日期）/365天*休假天数5，四舍五入，立即发放
            return BigDecimalUtils.safeMultiply(5, BigDecimalUtils.safeDivide(lastDay, YEAR, BigDecimal.ZERO, 4)).setScale(0, RoundingMode.HALF_UP).intValue();
        } else if (now.isAfter(oneYear) && now.isBefore(tenYear)) {
            // 入职年限＞1年＜10年，当年度已发放休假天数的，次年发放：年假天数5天
            return 5;
        } else if ((now.isAfter(tenYear) || now.isEqual(tenYear)) && now.isBefore(twentyYear)){
            // 入职年限≥10年＜20年，当年度已发放休假天数的，次年发放：年假天数10天
            return 10;
        } else if (now.isEqual(twentyYear) || now.isAfter(twentyYear)) {
            // 大于等于20 发放15天
            return 15;
        } else {
            return 0;
        }
    }

}




