package nckd.jimin.jyyy.hr.swc.hcdm.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.business.servicehelper.HRMServiceHelper;
import kd.hr.hbp.common.util.HRArrayUtils;
import kd.hr.hbp.common.util.HRCollUtil;
import kd.hr.hbp.common.util.HRDateTimeUtils;
import kd.hr.hbp.common.util.HRObjectUtils;
import kd.hrmp.hrpi.business.infrastructure.utils.QFilterUtil;
import kd.sdk.plugin.Plugin;
import kd.tdc.tjga.business.application.external.ChgService;
import kd.tdc.tjga.business.domain.repository.BatchChangeJobRepository;
import kd.tdc.tjga.business.domain.service.hrpi.IHrpiDomainService;
import kd.tdc.tjga.business.task.BatchChangeGradeLevelTask;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 后台任务插件
 */
public class AdjustJobBillEffectTask extends AbstractTask implements Plugin {
    private static final Log log = LogFactory.getLog(AdjustJobBillEffectTask.class);
    private static HRBaseServiceHelper BillHelper = new HRBaseServiceHelper("nckd_jobadjustbill");
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map1) throws KDException {
        Date nowDateTime = HRDateTimeUtils.getNowDateTime();
        QFilter billStatus = new QFilter("billstatus", "=", "C");
        //QFilter auditStatus = new QFilter("auditstatus", "=", "C");
        QFilter changeOver = new QFilter("changeover", "=", "0");
        QFilter effectFilter = new QFilter("changeentry.changeeffdate", "<=", nowDateTime);
        QFilter changeStatus = new QFilter("changeentry.changestatus", "=", "0");
        DynamicObject[] batchJobObj = BillHelper.loadDynamicObjectArray(new QFilter[]{billStatus, changeOver, effectFilter, changeStatus});
        if (!HRArrayUtils.isEmpty(batchJobObj)) {
            List<DynamicObject> allEntryObjs = new ArrayList(16);
            DynamicObject[] var11 = batchJobObj;
            int var12 = batchJobObj.length;

            for(int var13 = 0; var13 < var12; ++var13) {
                DynamicObject jobObj = var11[var13];
                DynamicObjectCollection entryObj = jobObj.getDynamicObjectCollection("changeentry");
                if (!HRCollUtil.isEmpty(entryObj)) {
                    allEntryObjs.addAll(entryObj);
                }
            }

            if (!HRCollUtil.isEmpty(allEntryObjs)) {
                List<Long> employeeIds = (List)allEntryObjs.stream().map((e1) -> {
                    return e1.getLong("employee.id");
                }).collect(Collectors.toList());
                IHrpiDomainService hrpiDomainService = IHrpiDomainService.getInstance();
                Map<Long, DynamicObject> mainEmpposorgrels = hrpiDomainService.getEmpposorgrelByEmployeeIds(employeeIds, "employee,company");
                Iterator var28 = allEntryObjs.iterator();

                while(var28.hasNext()) {
                    DynamicObject entryObj = (DynamicObject)var28.next();
                    Date effectDate = entryObj.getDate("changeeffdate");
                    if (!nowDateTime.before(effectDate)) {
                        Map<String, Object> map = new HashMap(16);
                        map.put("personId", entryObj.getLong("person.id"));
                        Long employeeId = entryObj.getLong("employee.id");
                        map.put("employeeId", employeeId);
                        map.put("chgActionId", 1360L);
                        map.put("appId", "tjga");
                        map.put("effectTime", effectDate.getTime());

                        //查询任职经历Id
                        QFilter filter = QFilterUtil.getCurrentQf();
                        filter.and("datastatus", QCP.equals, "1");
                        filter.and("employee.id", QCP.equals, employeeId);
                        filter.and("person.id", QCP.equals, entryObj.getLong("person.id"));
                        DynamicObject posOrgRel = QueryServiceHelper.queryOne("hrpi_empposorgrel", "id", new QFilter[]{filter});
                        (new ChgService()).queryPersonInfo(posOrgRel.getLong("id"), map);
                        Map<String, Object> valueMap = new HashMap(16);
                        DynamicObject dynamicObject = (DynamicObject)mainEmpposorgrels.get(employeeId);
                        if (!HRObjectUtils.isEmpty(dynamicObject)) {
                            valueMap.put("1310_S_empjobrel_company", dynamicObject.getLong("company.id"));
                        }

                        valueMap.put("1310_S_empjobrel_hrbu", entryObj.getLong("hrbu.id"));
                        valueMap.put("1310_S_empjobrel_job", entryObj.getLong("job.id"));
                        valueMap.put("1310_S_empjobrel_jobgradescm", entryObj.getLong("jobgradescm.id"));
                        valueMap.put("1310_S_empjobrel_jobgrade", entryObj.getLong("jobgrade.id"));
                        valueMap.put("1310_S_empjobrel_joblevelscm", entryObj.getLong("joblevelscm.id"));
                        valueMap.put("1310_S_empjobrel_joblevel", entryObj.getLong("joblevel.id"));
                        if (!HRObjectUtils.isEmpty(entryObj.getDynamicObject("job"))) {
                            valueMap.put("1310_S_empjobrel_jobscm", entryObj.getDynamicObject("job").getLong("jobscm.id"));
                        }

                        DynamicObject jobObj = entryObj.getDynamicObject("job");
                        if (!HRObjectUtils.isEmpty(jobObj)) {
                            valueMap.put("1310_S_empjobrel_jobseq", jobObj.getLong("jobseq.id"));
                            valueMap.put("1310_S_empjobrel_jobfamily", jobObj.getLong("jobfamily.id"));
                            valueMap.put("1310_S_empjobrel_jobclass", jobObj.getLong("jobclass.id"));
                        }

                        valueMap.put("1310_S_empjobrel_variationtype", 102030L);
                        valueMap.put("1310_S_empjobrel_enddate", HRDateTimeUtils.getSysMaxDate());
                        map.put("valueMap", valueMap);
                        log.info("BatchChangeGradeLevelTask.begin");
                        Map<String, Object> userInfo = (Map) HRMServiceHelper.invokeHRService("hpfs", "IHPFSPersonChgService", "executeActionPersonalChange", new Object[]{map});
                        log.info("BatchChangeGradeLevelTask.end");
                        boolean success = (Boolean)userInfo.get("success");
                        if (!success) {
                            String errorMsg = (String)userInfo.get("errorMsg");
                            log.info("BatchChangeGradeLevelTask.error map value:{}", map.toString());
                            log.error("BatchChangeGradeLevelTask.error error:{}", errorMsg);
                            entryObj.set("synresult", "2");
                        } else {
                            entryObj.set("synresult", "1");
                            entryObj.set("changestatus", "1");
                        }
                    }
                }

                DynamicObject[] var29 = batchJobObj;
                int var31 = batchJobObj.length;

                for(int var32 = 0; var32 < var31; ++var32) {
                    DynamicObject gradeLevelObj = var29[var32];
                    DynamicObjectCollection dynamicObjectCollection = gradeLevelObj.getDynamicObjectCollection("changeentry");
                    if (!HRCollUtil.isEmpty(dynamicObjectCollection)) {
                        Long changedNum = dynamicObjectCollection.stream().filter((d) -> {
                            return "1".equals(d.getString("changestatus"));
                        }).count();
                        gradeLevelObj.set("changednum", changedNum.intValue());
                        gradeLevelObj.set("totalnum", dynamicObjectCollection.size());
                        if (changedNum.intValue() == dynamicObjectCollection.size()) {
                            gradeLevelObj.set("changeover", "1");
                        }
                    }
                }

                BatchChangeJobRepository.updates(batchJobObj);
            }
        }
    }
}