package com.engine.salary.timer;

import cn.hutool.core.util.StrUtil;
import com.engine.salary.entity.hrm.po.HrmSnapshotPO;
import com.engine.salary.mapper.hrm.HrmSnapshotMapper;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.db.IdGenerator;
import com.engine.salary.util.db.MapperProxyFactory;
import lombok.extern.slf4j.Slf4j;
import weaver.hrm.User;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Slf4j
public class HrmSnapshotJob extends BaseCronJob {

    //指定筷子时间
    private String appointSnapshotTime;

    private HrmSnapshotMapper getHrmSnapshotMapper() {
        return MapperProxyFactory.getProxy(HrmSnapshotMapper.class);
    }

    @Override
    public void execute() {
        User user = new User();
        user.setUid(1);
        user.setLoginid("sysadmin");

        try {
            List<HrmSnapshotPO> hrmSnapshotPOS = getHrmSnapshotMapper().currentEmpData();

            Date snapshotTime = StrUtil.isNotBlank(appointSnapshotTime) && SalaryDateUtil.checkDay(appointSnapshotTime) ? SalaryDateUtil.dateStrToLocalDate(appointSnapshotTime) : SalaryDateUtil.localDateToDate(LocalDate.now());

            //先删除当日快照
            getHrmSnapshotMapper().deleteBySnapshotTime(snapshotTime);

            hrmSnapshotPOS.forEach(hrmSnapshotPO -> {

                hrmSnapshotPO.setId(IdGenerator.generate());
                hrmSnapshotPO.setSnapshotTime(snapshotTime);

                getHrmSnapshotMapper().insertIgnoreNull(hrmSnapshotPO);

            });
        }catch (Exception e){
            log.error("生成快照失败", e);
        }
    }

}
