package nckd.jimin.jyyy.fi.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
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.api.StopTask;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import nckd.jimin.jyyy.fi.common.ReimAmountSourceTypeEnum;
import nckd.jimin.jyyy.fi.common.constant.JobPositionBakBillConstant;
import nckd.jimin.jyyy.fi.common.constant.LimitRelasetConstant;
import nckd.jimin.jyyy.fi.plugin.operate.Helper.PersonReimQuotaHelper;
import nckd.jimin.jyyy.fi.plugin.operate.Helper.PersonReimQuotaVO;

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

/**
 * 员工额度同步任务
 */
public class PersonReimQuotaSyncTask extends AbstractTask implements StopTask {

    private PersonReimQuotaHelper personReimQuotaHelper = new PersonReimQuotaHelper();

    private static final Log logger = LogFactory.getLog(PersonReimQuotaSyncTask.class);



    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        logger.info("-----------PersonReimQuotaSyncTask begin--------------" , map);
        // 查询员工额度备份全部数据，
        DynamicObject[] personPositionJobBakArray = getPersonPositionJobBakCol();
        // 查询费用标准配置 按照费用项目分组
        Map<Long, Map<Long, List<DynamicObject>>> limitRelasetExpenseItemMap = personReimQuotaHelper.getLimitRelasetMap();

        Arrays.stream(personPositionJobBakArray).forEach(jobBakInfo -> createPersonPotitionJobQuota(jobBakInfo,limitRelasetExpenseItemMap));

        logger.info("-----------PersonReimQuotaSyncTask end--------------" );

    }

    protected void createPersonPotitionJobQuota(DynamicObject jobBakInfo,Map<Long, Map<Long, List<DynamicObject>>> limitRelasetExpenseItemMap){

        String userNumber = jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_USER).getString(JobPositionBakBillConstant.KEY_NUMBER);
        // 判断组织是否发生变更
            // 1.旧公司为空  新公司不为空
        if( (jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD) == null && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW) != null)){
            //创建新公司下的个人额度
            logger.info(String.format("人员【%s】新增公司，开始创建公司【%s】下的个人额度。",userNumber,jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW).getString(JobPositionBakBillConstant.KEY_NAME)));
            personReimQuotaHelper.createQuotaJobleverChange(jobBakInfo,limitRelasetExpenseItemMap,ReimAmountSourceTypeEnum.COMPANYCHANGE);
            personReimQuotaHelper.createQuotaPositionChange(jobBakInfo,limitRelasetExpenseItemMap,ReimAmountSourceTypeEnum.COMPANYCHANGE);
            return;
        }
             // 2.旧公司不为空  新公司为空
        if( (jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD) != null && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW) == null)){
            logger.info(String.format("人员【%s】离职，开始作废公司【%s】下的个人额度。",userNumber,jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW).getString(JobPositionBakBillConstant.KEY_NAME)));
            //将旧公司下创建的个人额度关闭
            personReimQuotaHelper.doInvalidPersonReim(new QFilter[]{
                    new QFilter("company.id", QCP.equals, jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD).getLong(JobPositionBakBillConstant.ID)),
                    new QFilter("user.id", QCP.equals, jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_USER).getLong(JobPositionBakBillConstant.ID))
            });
            return;
        }
            // 2.新、旧公司不为空且不相等
        if( (jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD) != null && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW) != null)
                && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD).getLong(JobPositionBakBillConstant.ID) != jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW).getLong(JobPositionBakBillConstant.ID)){
            logger.info(String.format("人员【%s】组织变更，开始作废公司【%s】下的个人额度,同时创建公司【%s】下的个人额度",userNumber,
                    jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD).getString(JobPositionBakBillConstant.KEY_NAME),
                    jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_NEW).getString(JobPositionBakBillConstant.KEY_NAME)));
            //判断新旧公司是否一致
            //将旧公司下创建的个人额度关闭
            personReimQuotaHelper.doInvalidPersonReim(new QFilter[]{
                    new QFilter("company.id", QCP.equals, jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_ORG_OLD).getLong(JobPositionBakBillConstant.ID)),
                    new QFilter("user.id", QCP.equals, jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_USER).getLong(JobPositionBakBillConstant.ID))
            });
            personReimQuotaHelper.createQuotaJobleverChange(jobBakInfo,limitRelasetExpenseItemMap,ReimAmountSourceTypeEnum.COMPANYCHANGE);
            personReimQuotaHelper.createQuotaPositionChange(jobBakInfo,limitRelasetExpenseItemMap,ReimAmountSourceTypeEnum.COMPANYCHANGE);
            return;
        }

        // 判断职级是否发生变更
        if( jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_JOBLEVEL_OLD) != null && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_JOBLEVEL_NEW) != null
            && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_JOBLEVEL_OLD).getLong(JobPositionBakBillConstant.ID) != jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_JOBLEVEL_NEW).getLong(JobPositionBakBillConstant.ID)){
            logger.info(String.format("人员【%s】职级发生变动，开始创建个人额度。",userNumber));
            personReimQuotaHelper.createQuotaJobleverChange(jobBakInfo,limitRelasetExpenseItemMap,null);
        }

        // 判断岗位是否发生变更
        if( jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_POSITION_OLD) != null && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_POSITION_OLD) != null
            && jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_POSITION_OLD).getLong(JobPositionBakBillConstant.ID) != jobBakInfo.getDynamicObject(JobPositionBakBillConstant.KEY_NCKD_POSITION_NEW).getLong(JobPositionBakBillConstant.ID)){
            logger.info(String.format("人员【%s】岗位发生变动，开始创建个人额度。",userNumber));
            personReimQuotaHelper.createQuotaPositionChange(jobBakInfo,limitRelasetExpenseItemMap,null);
        }
    }

    protected DynamicObject[] getPersonPositionJobBakCol() {
        Set<Long> bakBillIdSet = QueryServiceHelper.query(JobPositionBakBillConstant.ENTITYID, JobPositionBakBillConstant.ID, QFilter.isNotNull(JobPositionBakBillConstant.ID).toArray())
                .stream()
                .map(r -> r.getLong(JobPositionBakBillConstant.ID))
                .collect(Collectors.toSet());
        return BusinessDataServiceHelper.load(bakBillIdSet.toArray(), EntityMetadataCache.getDataEntityType(JobPositionBakBillConstant.ENTITYID));
    }


}
