package nckd.jimin.jyyy.fi.task;

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.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 kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
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 java.util.*;
import java.util.stream.Collectors;


/**
 * 同步人员报销级别
 */
public class PersonReimLeverSyncTask extends AbstractTask implements StopTask {

    private static final Log log = LogFactory.getLog(PersonReimLeverSyncTask.class);

    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 {
        log.info("-------- PersonReimLeverSyncTask 启动同步人员报销级别任务 --------");

        // 查询所有人员的报销级别设置
        DynamicObject[] reimburseSettingArray = BusinessDataServiceHelper.load("er_reimbursesetting_rel", "user.id,user.number,reimburselevel.id,company.id",
                QFilter.isNotNull("user.id").toArray());
        Map<String, List<DynamicObject>> userReimLeverSettingMap = Arrays.stream(reimburseSettingArray)
                .filter(r -> r.getDynamicObject("user") != null)
                .collect(Collectors.groupingBy(r -> r.getString("user.number")));
        // 查询当前生效的人员岗位信息
        DynamicObjectCollection positionCol = QueryServiceHelper.query(BillTypeConstants.HRPI_EMPPOSORGREL, "person.number,company.id", new QFilter[]{
                new QFilter("businessstatus", QCP.equals, "1"),
                new QFilter("iscurrentversion", QCP.equals, "1"),
                new QFilter("datastatus", QCP.equals, "1"),
                new QFilter("isprimary", QCP.equals, "1")
        });
//        Map<String, Long> personCompanyMap = positionCol.stream().collect(Collectors.toMap(r -> r.getString("person.number"), r -> r.getLong("company.id"), (k1, k2) -> k1));
        // 获取所有人员最新的职级
        Map<String, Long> personJobMap = QueryServiceHelper.query(BillTypeConstants.HRPI_EMPJOBREL, "person.number,joblevel.id", new QFilter[]{
                new QFilter("businessstatus", QCP.equals, "1"),
                new QFilter("datastatus", QCP.equals, "1"),
                new QFilter("iscurrentversion", QCP.equals, "1")
        }).stream().collect(Collectors.toMap(r -> r.getString("person.number"), r -> r.getLong("joblevel.id"), (k1, k2) -> k1));
        // 获取人员最新的报销级别
        PersonReimQuotaHelper helper = getPersonReimQuotaHelper();
        // 默认职级
        DynamicObject defultReimLever = helper.getDefultReimLever();

        // 通过公司查询共享策略查询报销级别；没有查到就取默认
        for(DynamicObject personPosition : positionCol){
            String personNumber = personPosition.getString("person.number");
            if(personJobMap.containsKey(personNumber)){
                Long jobId = personJobMap.get(personNumber);
                Long companyId = personPosition.getLong("company.id");
                if(companyId != null){
                    DynamicObject reimLever = null;
                    if(jobId != null){
                       reimLever = helper.getReimLever(jobId, companyId);
                    }
                    if (reimLever == null) {
                        reimLever = defultReimLever;
                    }
                    DynamicObject reimSettingInfo = null;
                    // 存在报销级别设置
                    if(userReimLeverSettingMap.containsKey(personNumber)){
                        List<DynamicObject> reimLeverSettingCol = userReimLeverSettingMap.get(personNumber);
                        Optional<DynamicObject> findCompanyOp = reimLeverSettingCol.stream()
                                .filter(r -> companyId == r.getLong("company.id")).findFirst();
                        if(findCompanyOp.isPresent()){
                            reimSettingInfo = findCompanyOp.get();
                            reimSettingInfo.set("reimburselevel", reimLever.getLong("id"));

                        }
                    }
                    if(Objects.isNull(reimSettingInfo)){
                        DynamicObject userInfo = BusinessDataServiceHelper.loadSingleFromCache("bos_user", new QFilter("number", QCP.equals, personNumber).toArray());
                        DynamicObject org = BusinessDataServiceHelper.loadSingle(companyId, "bos_org");
                        reimSettingInfo = BusinessDataServiceHelper.newDynamicObject("er_reimbursesetting_rel");
                        reimSettingInfo.set("user",userInfo);
                        reimSettingInfo.set("reimburselevel",reimLever);
                        reimSettingInfo.set("company",org);
                    }
                    SaveServiceHelper.save(new DynamicObject[]{ reimSettingInfo });

                    // 查看状态，调用已审核
                    DynamicObject reimBurseSetting = BusinessDataServiceHelper.loadSingle("er_reimbursesetting", new QFilter("number", QCP.equals, personNumber).toArray());
                    if("A".equals(reimBurseSetting.getString("auditstatus"))){
                        OperationResult operationResult = OperationServiceHelper.executeOperate("audit","er_reimbursesetting",  new DynamicObject[]{reimBurseSetting}, OperateOption.create());
                        if(!operationResult.isSuccess()){
                            log.info(String.format("人员【%s】报销级别审核失败%s", personNumber, CommonUtils.getOperationResultErrorInfos(operationResult)));
                        }
                    }
                }
            }

        }
        log.info("-------- PersonReimLeverSyncTask 同步人员报销级别任务结束 --------");
    }

}
