package cn.axzo.workflow.server.xxljob;

import cn.axzo.karma.client.feign.FlowSupportApi;
import cn.axzo.karma.client.model.request.PersonProfileQueryReq;
import cn.axzo.karma.client.model.response.PersonProfileResp;
import cn.axzo.workflow.common.model.dto.es.DataSyncSummaryDTO;
import cn.axzo.workflow.common.model.dto.es.HistoricProcessInstanceSearchForEsDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.conf.SupportRefreshProperties;
import cn.axzo.workflow.core.service.BpmnProcessInstanceForEsService;
import cn.axzo.workflow.es.model.ProcessTaskDocument;
import cn.axzo.workflow.es.service.aggregation.AggregateProcessInstanceService;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.axzo.workflow.server.controller.delegate.AbstractBpmnTaskAssigneeSelector.parseApiResult;

/**
 * 在途的和新发起的流程实例数据同步至 ES
 *
 * @author wangli
 * @since 2024-09-27 11:03
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class SpecifyProcessInstanceSyncEsJobHandler {
    private final BpmnProcessInstanceForEsService bpmnProcessInstanceForEsService;
    private final AggregateProcessInstanceService aggregateProcessInstanceService;
    private final SpringProcessEngineConfiguration springProcessEngineConfiguration;
    private final ApplicationContext context;
    private final SupportRefreshProperties refreshProperties;
    private final FlowSupportApi flowSupportApi;

    @XxlJob("specifyProcessInstanceSyncToEs")
    public ReturnT<String> execute(String processInstanceId) {
        log.info("Sync specify processInstance id: {}", processInstanceId);
        XxlJobHelper.log("Sync specify processInstance id: {}", processInstanceId);

        // 开始同步流程数据到 ES
        DataSyncSummaryDTO summary = doSync(processInstanceId);

        log.info("Insert Summary: ProcessInstance Count: {}, ProcessTask Count: {}", summary.getProcessInstanceCount(), summary.getProcessTaskCount());
        XxlJobHelper.log("Insert Summary: ProcessInstance Count: {}, ProcessTask Count: {}", summary.getProcessInstanceCount(), summary.getProcessTaskCount());
        return ReturnT.SUCCESS;
    }

    /**
     * 开始处理的入口
     *
     * @param processInstanceId
     */
    private DataSyncSummaryDTO doSync(String processInstanceId) {
        HistoricProcessInstanceSearchForEsDTO search = new HistoricProcessInstanceSearchForEsDTO();
        search.setProcessInstanceId(processInstanceId);
        List<HistoricProcessInstance> instances = bpmnProcessInstanceForEsService.queryHistoricProcessInstance(search, null);
        AtomicLong totalProcessTaskCount = new AtomicLong(0);
        instances.forEach(hpi -> {
            aggregateProcessInstanceService.deleteDocumentParentAndChild(hpi.getId());
            List<ProcessTaskDocument> processTaskDocuments = aggregateProcessInstanceService.syncProcessInstance(hpi, this::queryPersonByIds);
            totalProcessTaskCount.getAndSet(totalProcessTaskCount.get() + processTaskDocuments.size());
        });
        return new DataSyncSummaryDTO(1L, totalProcessTaskCount.get());

    }

    private Map<Long, BpmnTaskDelegateAssigner> queryPersonByIds(List<BpmnTaskDelegateAssigner> users) {
        Map<Long, BpmnTaskDelegateAssigner> result = new HashMap<>();
        if (CollectionUtils.isEmpty(users)) {
            return result;
        }
        Map<Long, BpmnTaskDelegateAssigner> map = users.stream()
                .filter(i -> StringUtils.hasText(i.getPersonId()) && !Objects.equals("null", i.getPersonId()) && NumberUtil.isNumber(i.getPersonId()))
                .collect(Collectors.toMap(i -> NumberUtil.parseLong(i.getPersonId()), Function.identity(), (s, t) -> s));

        PersonProfileQueryReq query = new PersonProfileQueryReq();
        ArrayList<Long> personIds = Lists.newArrayList(map.keySet());
        query.setPersonIds(personIds);
        Map<Long, PersonProfileResp> personProfileMap = parseApiResult(() -> flowSupportApi.listPersons(PersonProfileQueryReq.builder().personIds(personIds).build()),
                "根据 PersonId 查询自然人档案", "cn.axzo.karma.client.feign.FlowSupportApi.listPersons", refreshProperties, context, personIds)
                .stream().collect(Collectors.toMap(PersonProfileResp::getId, Function.identity(), (s, t) -> s));

        personProfileMap.forEach((k, v) -> {
            result.put(k, BpmnTaskDelegateAssigner.builder()
                    .personId(String.valueOf(v.getId()))
                    .assignerName(v.getRealName())
                    .avatar(v.getAvatarUrl())
                    .build());
        });
        return result;
    }

}
