package cn.iocoder.yudao.module.system.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyContractDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyContractMapper;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

@Component
public class BizUtil {
    @Resource
    private ElderlyContractMapper elderlyContractMapper;
    /**
     * 加上合同日期获取费用截止日期
     */
    public LocalDate getEndDateWithExpireDate(Long elderId, Long contractId,LocalDate... localDates){
        ElderlyContractDO elderlyContractDO;
        if(contractId == null){
            List<ElderlyContractDO> elderlyContractDOS = elderlyContractMapper.selectList(new LambdaQueryWrapperX<ElderlyContractDO>()
                    .eq(ElderlyContractDO::getElderId, elderId)
                    .orderByDesc(ElderlyContractDO::getCreatedTime));
            if(CollectionUtil.isEmpty(elderlyContractDOS)){
                throw exception(ErrorCodeConstants.ELDERLY_RETREAT_CONTRACT_NOT_EXISTS);
            }
            elderlyContractDO = elderlyContractDOS.get(0);
        }else {
            elderlyContractDO = elderlyContractMapper.selectById(contractId);
        }
        LocalDate expireLocalDate = elderlyContractDO.getExpireTime().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        List<LocalDate> list = new ArrayList<>(Arrays.asList(localDates));
        list.add(expireLocalDate);
        return Collections.min(list);
    }
}
