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

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
@Slf4j
public class ElderAgeUpdateJob implements JobHandler {
    private final static Logger logger = LoggerFactory.getLogger(ElderContractUpdateJob.class);

    @Resource
    private ElderlyInfoMapper elderlyInfoMapper;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        Long tenantId = TenantContextHolder.getTenantId();
        logger.info("租户{},=====================长者年龄更新===================", tenantId);
        updateElderAge(tenantId);
        return String.format("租户{}长者年龄更新情况", tenantId);
    }
    private void updateElderAge(Long tenantId){
        List<ElderlyInfoDO> elderlyInfoList = elderlyInfoMapper.selectList(new LambdaQueryWrapperX<ElderlyInfoDO>().eq(ElderlyInfoDO::getTenantId, tenantId));
        for (ElderlyInfoDO elderlyInfo : elderlyInfoList) {
            if(elderlyInfo.getBirthday() != null){
                LocalDate birthDayLocalDate = elderlyInfo.getBirthday().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                elderlyInfo.setElderAge((int) Math.abs(ChronoUnit.YEARS.between(birthDayLocalDate, LocalDate.now())));
            }
        }
        elderlyInfoMapper.updateBatch(elderlyInfoList);
    }
}
