package com.engine.salary.maintainer.salaryarchive;

import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.salaryarchive.po.SalaryArchivePO;
import com.engine.salary.enums.salaryarchive.SalaryArchiveStatusEnum;
import com.engine.salary.mapper.archive.SalaryArchiveMapper;
import com.engine.salary.service.SalaryArchiveService;
import com.engine.salary.service.SalaryEmployeeService;
import com.engine.salary.service.impl.SalaryArchiveServiceImpl;
import com.engine.salary.service.impl.SalaryEmployeeServiceImpl;
import com.engine.salary.util.SalaryDateUtil;
import com.engine.salary.util.SalaryEntityUtil;
import com.engine.salary.util.db.MapperProxyFactory;
import org.apache.commons.lang3.StringUtils;
import weaver.hrm.User;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SalaryArchiveManager extends Service {
    private SalaryArchiveService getSalaryArchiveService(User user) {
        return ServiceUtil.getService(SalaryArchiveServiceImpl.class, user);
    }

    private SalaryEmployeeService getSalaryEmployeeService(User user) {
        return ServiceUtil.getService(SalaryEmployeeServiceImpl.class, user);
    }

    private SalaryArchiveMapper getSalaryArchiveMapper() {
        return MapperProxyFactory.getProxy(SalaryArchiveMapper.class);
    }

    public Boolean initPayStartDate() {
        //获取所有待定薪档案
        List<SalaryArchivePO> list = getSalaryArchiveService(user).listSome(SalaryArchivePO.builder().runStatus(SalaryArchiveStatusEnum.PENDING.getValue()).build());

        //过滤已存在起始发薪日期的数据
        List<SalaryArchivePO> needData = list.stream().filter(po -> po.getPayStartDate() == null).collect(Collectors.toList());
        List<Long> empIds = SalaryEntityUtil.properties(needData, SalaryArchivePO::getEmployeeId, Collectors.toList());

        //获取人员信息
        List<DataCollectionEmployee> emps = getSalaryEmployeeService(user).getEmployeeByIds(empIds);
        Map<Long, DataCollectionEmployee> longDataCollectionEmployeeMap = SalaryEntityUtil.convert2Map(emps, DataCollectionEmployee::getEmployeeId);

        //设置起始发薪日期
        List<SalaryArchivePO> collect1 = needData.stream().peek(po -> {
            Long employeeId = po.getEmployeeId();
            DataCollectionEmployee orDefault = longDataCollectionEmployeeMap.getOrDefault(employeeId, new DataCollectionEmployee());
            String companystartdate = orDefault.getCompanystartdate();
            if (StringUtils.isNotBlank(companystartdate)&&SalaryDateUtil.checkDay(companystartdate)) {
                Date parse = SalaryDateUtil.parse(companystartdate, SalaryDateUtil.DATE_FORMATTER_PATTERN);
                po.setPayStartDate(parse);
            }
        }).collect(Collectors.toList());

        collect1.forEach(getSalaryArchiveMapper()::update);

        return null;
    }
}
