package com.engine.salary.timer;

import com.engine.common.util.ServiceUtil;
import com.engine.salary.biz.SalarySobRangeBiz;
import com.engine.salary.entity.salarysob.po.SalarySobPO;
import com.engine.salary.entity.salarysob.po.SalarySobRangePO;
import com.engine.salary.service.SalarySobRangeService;
import com.engine.salary.service.SalarySobService;
import com.engine.salary.service.impl.SalarySobRangeServiceImpl;
import com.engine.salary.service.impl.SalarySobServiceImpl;
import com.engine.salary.util.db.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weaver.general.BaseBean;
import weaver.hrm.User;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自动同步个税扣缴以为人人员范围至，账套人员范围
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: 泛微软件</p>
 *
 * @author qiantao
 * @version 1.0
 **/
@Slf4j
public class SyncTaxAgentEmp2SobEmpJob extends BaseCronJob {

    private SalarySobService getSalarySobService(User user) {
        return ServiceUtil.getService(SalarySobServiceImpl.class, user);
    }

    private SalarySobRangeService getSalarySobRangeService(User user) {
        return ServiceUtil.getService(SalarySobRangeServiceImpl.class, user);
    }

    private String salarySobIds;



    @Override
    public void execute() {
        User user = new User();
        user.setUid(1);
        user.setLoginid("sysadmin");
        List<SalarySobPO> salarySobPOS;
        if (StringUtils.isNotEmpty(salarySobIds)) {
            // 只同步指定的账套
            List<Long> salarySobIdList = Arrays.asList(StringUtils.split(salarySobIds, ",")).stream().map(Long::valueOf).collect(Collectors.toList());
            salarySobPOS = getSalarySobService(user).listByIds(salarySobIdList);
        } else {
            salarySobPOS = getSalarySobService(user).listAll();
        }
        BaseBean baseBean = new BaseBean();
        SalarySobRangeBiz salarySobRangeBiz = new SalarySobRangeBiz();
        for (SalarySobPO po : salarySobPOS) {
            List<SalarySobRangePO> salarySobRangePOS = new ArrayList<>();
            try {
                baseBean.writeLog("开始同步人员范围至账套账套：{}",po.getId());
                // 保存前先删除
                salarySobRangePOS = salarySobRangeBiz.listSome(SalarySobRangePO.builder().salarySobId(po.getId()).build());
                getSalarySobRangeService(user).deleteBySalarySobIds(Collections.singletonList(po.getId()));
                getSalarySobService(user).saveDefaultEmployeeRange(po);
            } catch (Exception e) {
                baseBean.writeLog("同步人员范围至账套账套出错：" + e.getMessage());
                salarySobRangePOS.stream().forEach(p -> p.setId(IdGenerator.generate()));
                salarySobRangeBiz.batchInsert(salarySobRangePOS);
            }
        }
    }


}
