package nckd.jimin.jyyy.fi.task;

import com.google.common.collect.Lists;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
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.bos.servicehelper.operation.OperationServiceHelper;
import nckd.jimin.jyyy.fi.common.constant.BillTypeConstants;
import nckd.jimin.jyyy.fi.common.util.CommonUtils;
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;

import static kd.epm.emr.common.spread.domain.view.js.SpreadProperties.P.r;

public class PersonReimBigJobTask extends AbstractTask {

    private PersonReimQuotaHelper personReimQuotaHelper = new PersonReimQuotaHelper();


    protected PersonReimQuotaHelper getPersonReimQuotaHelper() {
        return Optional.ofNullable(personReimQuotaHelper).orElse(new PersonReimQuotaHelper());
    }
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {

        // 同步类型
        String updateType = (String)map.get("updatetype");

        // 获取全部人员生效中的岗位职级
        DynamicObjectCollection positionCol = QueryServiceHelper.query(BillTypeConstants.HRPI_EMPPOSORGREL, "person.id,person.number,company.id,company.number,position.id", new QFilter[]{
                new QFilter("businessstatus", QCP.equals, "1"),
                new QFilter("iscurrentversion", QCP.equals, "1"),
                new QFilter("isprimary", QCP.equals, "1")
        });

        Map<Long, DynamicObject> personPositionMap = positionCol.stream()
                .collect(Collectors.toMap(r -> r.getLong("person.id"), r -> r, (k1, k2) -> k1));
        Set<Long> personPositionSet = positionCol.stream().map(r -> r.getLong("person.id")).collect(Collectors.toSet());

        // 从职级职等中共查询职级发生变化的数据
        Map<Long, Long> personJobMap = QueryServiceHelper.query(BillTypeConstants.HRPI_EMPJOBREL, "person.id,joblevel.id", new QFilter[]{
                new QFilter("businessstatus", QCP.equals, "1"),
                new QFilter("iscurrentversion", QCP.equals, "1"),
                new QFilter("person.id", QCP.in, personPositionSet)
        }).stream().collect(Collectors.toMap(r -> r.getLong("person.id"), r -> r.getLong("joblevel.id"), (k1, k2) -> k1));

        List<List<Long>> partition = Lists.partition(new ArrayList<>(personPositionSet), 4);

        for(int i = 0 ; i < partition.size() ; i++){
            List<Long> patchDataList = partition.get(i);

            for(Long personId : patchDataList){

                if(!personPositionMap.containsKey(personId) || !personJobMap.containsKey(personId)){
                    continue;
                }
                DynamicObject positionInfo = personPositionMap.get(personId);


                DynamicObject company = QueryServiceHelper.queryOne("bos_org", "id", new QFilter("number", QCP.equals, positionInfo.getString("company.number")).toArray());
                DynamicObject userInfo = QueryServiceHelper.queryOne("bos_user", "id", new QFilter("number", QCP.equals, positionInfo.getString("person.number")).toArray());
                // 更新额度
                if("updatequota".equals(updateType)){
                    refreshPersonQuota(userInfo.getLong("id"),company.getLong("id"),positionInfo.getLong("position.id"),(Long)personJobMap.get(personId));
                    continue;
                }

                if("updatelever".equals(updateType)){
                    getPersonReimQuotaHelper().syncReimLever(userInfo.getLong("id"),company.getLong("id"),(Long)personJobMap.get(personId));
                    continue;
                }
            }

            // 回传进度
            feedbackProgress(100*(i+1)/partition.size());
        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("message", String.format("执行成功，总共执行条数%s",personPositionSet.size()));
        // 输出定制结果
        feedbackCustomdata(result);
    }

    /**
     * 刷新个人额度表
     * @param userId
     * @param positionId
     * @param jobId
     */
    protected void refreshPersonQuota(Long userId ,Long companyId , Long positionId,Long jobId) {

    }
}
